edge ppv2: final review fixes in the edge, host guard and proxyproto
From the whole-branch review (fix-wave W1-W8): - noClientGate's two 503s go through UnavailableHeader (CI's TestEvery503GoesThroughUnavailable). - RaiseTrustBarrier sets the flag and sweeps before it writes the file, so a stalled disk never delays containment; not-persisted contract kept. - The activation guard reads host.env through sandboxHostEnvironmentAt (no symlinks, non-blocking, regular files); readProxyHostEnv deleted. - proxy-allows-prev applies the exec-sandbox rule before it runs carlos.prev; a refused predecessor is never run. - trust-status carries by_listener (per-listener counters and per-node proxied) and edge_instance; the decoder validates both. - proxyproto.Conn forwards CloseWrite. - Witnesses: unlisted-peer header ignored, proxied HTTP/2 identity.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+824
−162
internal/edge/proxyingress.go+82 −26internal/edge/proxyingress_test.go+215 −7internal/host/edgetrust.go+140 −35internal/host/edgetrust_linux_test.go+31 −6internal/host/edgetrust_test.go+88 −27internal/host/edgetrust_wiring_test.go+13 −1internal/host/proxyfeature.go+38 −43internal/host/proxyfeature_linux_test.go+135 −0internal/host/proxyfeature_test.go+9 −17internal/proxyproto/conn.go+13 −0internal/proxyproto/listener_test.go+60 −0
Intent
diff --git a/internal/edge/proxyingress.go b/internal/edge/proxyingress.go| index 906ae7a4f..a58b87753 100644 |
| --- a/internal/edge/proxyingress.go |
| +++ b/internal/edge/proxyingress.go |
| @@ -12,6 +12,8 @@ package edge |
| import ( |
| "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| "errors" |
| "fmt" |
| "log" |
| @@ -56,10 +58,17 @@ type proxyIngress struct { |
| trusted []netip.Addr // sorted |
| barrierPath string |
| barrier atomic.Bool |
| + // instance is a random id set once when the edge arms (once per edge |
| + // process, before either listener is wrapped): the counters' lifetime. |
| + // A reader that sees it change knows the counters started again. |
| + instance string |
| // parseHook is proxyproto.Config.ParseHook; nil in production, set by |
| // tests before the listeners are wrapped. |
| parseHook func(stage string) |
| + // persist writes the barrier file; nil is writeBarrierFile. Tests set |
| + // it to hold the write. |
| + persist func(path string) error |
| // mu serialises the barrier verbs. |
| mu sync.Mutex |
| @@ -102,9 +111,14 @@ func (e *Edge) loadProxyIngress(getenv func(string) string, dataDir string) erro |
| // 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 { |
| + var id [16]byte |
| + if _, err := rand.Read(id[:]); err != nil { |
| + return fmt.Errorf("edge: proxy protocol: edge instance id: %w", err) |
| + } |
| p := &proxyIngress{ |
| trusted: slices.Clone(trusted), |
| barrierPath: barrierFile(dataDir), |
| + instance: hex.EncodeToString(id[:]), |
| } |
| slices.SortFunc(p.trusted, netip.Addr.Compare) |
| switch _, err := os.Lstat(p.barrierPath); { |
| @@ -187,7 +201,8 @@ func proxyConnOf(c net.Conn) *proxyproto.Conn { |
| // 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. |
| +// before any routing, limit, analytics or forwarding. Both 503s go through |
| +// UnavailableHeader (#421 finding 1), as every edge 503 does. |
| // |
| // 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 |
| @@ -201,8 +216,9 @@ func (e *Edge) noClientGate(p *proxyIngress, l *proxyproto.Listener, health bool |
| } |
| if pc != nil && health && r.URL.Path == lbhealth.Path && (r.Method == http.MethodGet || r.Method == http.MethodHead) { |
| if !e.lbHealthAnswer(w, r) { |
| + // Region HA off: nothing on this box answers the check. |
| w.Header().Set("Cache-Control", "no-store") |
| - w.WriteHeader(http.StatusServiceUnavailable) |
| + UnavailableHeader(w, "proxy-health-off", 10) |
| } |
| return |
| } |
| @@ -213,21 +229,22 @@ func (e *Edge) noClientGate(p *proxyIngress, l *proxyproto.Listener, health bool |
| } |
| w.Header().Set("Connection", "close") |
| w.Header().Set("Cache-Control", "no-store") |
| - w.WriteHeader(http.StatusServiceUnavailable) |
| + UnavailableHeader(w, "proxy-no-client", 2) |
| }) |
| } |
| -// 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, and a proxied connection the sweep has not reached yet |
| -// is refused by the gate. Calling it again rewrites the file and sweeps |
| -// again. |
| +// RaiseTrustBarrier raises the trust barrier (spec §4.7): it sets the |
| +// flag, then closes every trusted connection on both public listeners, |
| +// pending ones included, then writes the barrier file (synced, with its |
| +// directory), and returns how many connections it closed. The order is the |
| +// guarantee: a connection the sweep misses resolves after the flag, so its |
| +// header grants nothing, and a proxied connection the sweep has not reached |
| +// yet is refused by the gate. Containment never waits on the disk: a |
| +// stalled data disk delays only the file. Calling it again sweeps again |
| +// and rewrites the file. |
| // |
| -// 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 |
| +// A failed write does not undo the raise: the flag is up and the sweep has |
| +// run, 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() |
| @@ -236,15 +253,19 @@ func (e *Edge) RaiseTrustBarrier() (closed int, err error) { |
| } |
| p.mu.Lock() |
| defer p.mu.Unlock() |
| - 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()} { |
| if l != nil { |
| closed += l.CloseTrusted() |
| } |
| } |
| + persist := p.persist |
| + if persist == nil { |
| + persist = writeBarrierFile |
| + } |
| + if werr := persist(p.barrierPath); werr != nil { |
| + err = fmt.Errorf("%w: %w", ErrBarrierNotPersisted, werr) |
| + } |
| return closed, err |
| } |
| @@ -274,19 +295,43 @@ func (e *Edge) TrustBarrierUp() bool { |
| 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) { |
| +// ProxyStatus is an armed edge's PROXY protocol counters, per public |
| +// listener, and the edge's instance. |
| +type ProxyStatus struct { |
| + // Instance is a random id set once when the edge armed: unchanged |
| + // while these counters keep counting, new after a restart. |
| + Instance string |
| + // Listeners holds each public listener's counters since the edge |
| + // started, keyed "80" and "443"; a listener not yet wrapped counts |
| + // zero. |
| + Listeners map[string]proxyproto.Counters |
| +} |
| + |
| +// ProxyStatus reads both public listeners' counters, one snapshot each, |
| +// and the edge's instance. It reports false on an edge that is not armed. |
| +func (e *Edge) ProxyStatus() (ProxyStatus, bool) { |
| p := e.proxy.Load() |
| if p == nil { |
| - return proxyproto.Counters{}, false |
| + return ProxyStatus{}, false |
| } |
| - sum := proxyproto.Counters{ProxiedByNode: map[netip.Addr]uint64{}} |
| - for _, l := range []*proxyproto.Listener{p.http.Load(), p.https.Load()} { |
| - if l == nil { |
| - continue |
| + s := ProxyStatus{Instance: p.instance, Listeners: make(map[string]proxyproto.Counters, 2)} |
| + for port, l := range map[string]*proxyproto.Listener{"80": p.http.Load(), "443": p.https.Load()} { |
| + c := proxyproto.Counters{} |
| + if l != nil { |
| + c = l.Counters() |
| + } |
| + if c.ProxiedByNode == nil { |
| + c.ProxiedByNode = map[netip.Addr]uint64{} |
| } |
| - c := l.Counters() |
| + s.Listeners[port] = c |
| + } |
| + return s, true |
| +} |
| + |
| +// SumProxyCounters adds per-listener counters into one. |
| +func SumProxyCounters(listeners map[string]proxyproto.Counters) proxyproto.Counters { |
| + sum := proxyproto.Counters{ProxiedByNode: map[netip.Addr]uint64{}} |
| + for _, c := range listeners { |
| sum.Proxied += c.Proxied |
| sum.NoClient += c.NoClient |
| sum.NoClientRefused += c.NoClientRefused |
| @@ -299,7 +344,18 @@ func (e *Edge) ProxyCounters() (proxyproto.Counters, bool) { |
| sum.ProxiedByNode[a] += n |
| } |
| } |
| - return sum, true |
| + return sum |
| +} |
| + |
| +// ProxyCounters sums both public listeners' counters since start: the |
| +// trust metric's and the journal's view. It reports false on an edge that |
| +// is not armed. |
| +func (e *Edge) ProxyCounters() (proxyproto.Counters, bool) { |
| + s, ok := e.ProxyStatus() |
| + if !ok { |
| + return proxyproto.Counters{}, false |
| + } |
| + return SumProxyCounters(s.Listeners), true |
| } |
| // writeBarrierFile writes the barrier file and syncs it, its directory and |
diff --git a/internal/edge/proxyingress_test.go b/internal/edge/proxyingress_test.go| index 1d513ca79..0e0a12ddf 100644 |
| --- a/internal/edge/proxyingress_test.go |
| +++ b/internal/edge/proxyingress_test.go |
| @@ -139,6 +139,8 @@ type rawResult struct { |
| status int |
| connClose bool |
| body string |
| + answer string // X-Carlos-Answer |
| + retry string // Retry-After |
| } |
| // dial opens a connection to :443 (secure) or :80 and writes prefix. |
| @@ -188,7 +190,8 @@ func (pe *proxyEdge) request(t *testing.T, c net.Conn, secure bool, method, host |
| if err != nil { |
| t.Fatal(err) |
| } |
| - return rawResult{status: resp.StatusCode, connClose: resp.Close, body: string(b)} |
| + return rawResult{status: resp.StatusCode, connClose: resp.Close, body: string(b), |
| + answer: resp.Header.Get(answerHeader), retry: resp.Header.Get("Retry-After")} |
| } |
| // exchange is one request on a fresh connection that starts with prefix. |
| @@ -250,6 +253,10 @@ func wantNoClientRefused(t *testing.T, res rawResult, what string) { |
| if res.status != http.StatusServiceUnavailable || !res.connClose { |
| t.Fatalf("%s: status %d, Connection: close %v, want 503 and close", what, res.status, res.connClose) |
| } |
| + // Through UnavailableHeader, as every edge 503 (#421 finding 1). |
| + if res.answer != "proxy-no-client" || res.retry != "2" { |
| + t.Fatalf("%s: X-Carlos-Answer %q Retry-After %q, want proxy-no-client and 2", what, res.answer, res.retry) |
| + } |
| } |
| // A trusted PROXY header's source is the client everywhere the edge reads |
| @@ -331,8 +338,10 @@ func TestNoClientHealthDispatchIgnoresHost(t *testing.T) { |
| } |
| // 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 res := pe.exchange(t, false, ppv2Local(), http.MethodGet, demoHost, lbhealth.Path); res.status != http.StatusServiceUnavailable || |
| + res.answer != "proxy-health-off" || res.retry != "10" || res.connClose { |
| + t.Fatalf("region HA off: %d %q answer %q retry %q close %v, want 503 proxy-health-off, Retry-After 10, kept open", |
| + res.status, res.body, res.answer, res.retry, res.connClose) |
| } |
| if n := hits.Load(); n != 0 { |
| t.Fatalf("upstream hits = %d, want 0", n) |
| @@ -809,8 +818,10 @@ func (l *closeSpy) closes() []closeSeen { |
| 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. |
| +// The barrier is up before the sweep closes anything: every connection |
| +// RaiseTrustBarrier closes, open or pending, sees the flag. The file is |
| +// written after the sweep (containment never waits on the disk) and is |
| +// there when RaiseTrustBarrier returns. |
| func TestRaiseTrustBarrierFlagBeforeSweep(t *testing.T) { |
| dataDir := t.TempDir() |
| e := ppEdge(t, rlRoute(func() string { a, _ := echoXFF(t); return a }(), "")) |
| @@ -843,14 +854,104 @@ func TestRaiseTrustBarrierFlagBeforeSweep(t *testing.T) { |
| 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) |
| + if !c.barrier { |
| + t.Fatalf("close %d: barrier up %v; want it up before the sweep", i, c.barrier) |
| + } |
| + if c.file { |
| + t.Fatalf("close %d: the barrier file was already written; the sweep must not wait for the disk", i) |
| } |
| } |
| + if _, err := os.Stat(barrierFile(dataDir)); err != nil { |
| + t.Fatalf("barrier file after RaiseTrustBarrier: %v", err) |
| + } |
| wantClosedWithin(t, open, 2*time.Second, "the open proxied connection") |
| wantClosedWithin(t, pending, 2*time.Second, "the pending connection") |
| } |
| +// A stalled data disk does not delay containment: while the barrier |
| +// file's write is blocked, the flag is already up, every trusted |
| +// connection (open or pending) is closed, and a new proxied request is |
| +// refused. Released, the write lands and RaiseTrustBarrier returns; a write |
| +// that then fails is ErrBarrierNotPersisted with the barrier still up. |
| +func TestRaiseTrustBarrierContainsWhilePersistBlocked(t *testing.T) { |
| + for _, fail := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "write succeeds", true: "write fails"}[fail], func(t *testing.T) { |
| + dataDir := t.TempDir() |
| + up, hits := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, "")) |
| + p := armed(t, e, ppLoopback, dataDir) |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + var releaseOnce sync.Once |
| + unblock := func() { releaseOnce.Do(func() { close(release) }) } |
| + t.Cleanup(unblock) // a failed assertion never leaves the raise blocked |
| + p.persist = func(path string) error { |
| + close(entered) |
| + <-release |
| + if fail { |
| + return errors.New("disk stalled, then failed") |
| + } |
| + return writeBarrierFile(path) |
| + } |
| + news, hook := connsNew() |
| + pe := newProxyEdge(t, e, proxyOpts{connState: hook}) |
| + openRaw := pe.dial(t, true, ppv2Proxy("203.0.113.7:51000")) |
| + waitNew(t, news, 1) |
| + open := tls.Client(openRaw, &tls.Config{RootCAs: pe.pool, ServerName: "127.0.0.1"}) |
| + if res := pe.request(t, open, false, http.MethodGet, rlHost, "/"); res.status != http.StatusOK || res.body != "203.0.113.7" { |
| + 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) |
| + |
| + type result struct { |
| + closed int |
| + err error |
| + } |
| + done := make(chan result, 1) |
| + go func() { |
| + closed, err := e.RaiseTrustBarrier() |
| + done <- result{closed, err} |
| + }() |
| + select { |
| + case <-entered: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("RaiseTrustBarrier never reached the barrier file's write") |
| + } |
| + // The write is held: containment must already be complete. |
| + if !e.TrustBarrierUp() { |
| + t.Fatal("barrier down while its file's write is blocked") |
| + } |
| + wantClosedWithin(t, openRaw, 2*time.Second, "the open proxied connection, write blocked") |
| + wantClosedWithin(t, pending, 2*time.Second, "the pending connection, write blocked") |
| + wantNoClientRefused(t, pe.exchange(t, true, ppv2Proxy("203.0.113.7:51002"), http.MethodGet, rlHost, "/"), "a proxied request while the write is blocked") |
| + select { |
| + case r := <-done: |
| + t.Fatalf("RaiseTrustBarrier returned (%d, %v) before its write was released", r.closed, r.err) |
| + default: |
| + } |
| + unblock() |
| + r := <-done |
| + if r.closed != 2 { |
| + t.Fatalf("closed %d, want 2", r.closed) |
| + } |
| + _, statErr := os.Stat(barrierFile(dataDir)) |
| + if fail { |
| + if !errors.Is(r.err, ErrBarrierNotPersisted) || statErr == nil { |
| + t.Fatalf("failed write: %v, file %v; want ErrBarrierNotPersisted and no file", r.err, statErr) |
| + } |
| + } else if r.err != nil || statErr != nil { |
| + t.Fatalf("RaiseTrustBarrier: %v, file %v", r.err, statErr) |
| + } |
| + if !e.TrustBarrierUp() { |
| + t.Fatal("barrier down after the raise") |
| + } |
| + if n := hits.Load(); n != 1 { |
| + t.Fatalf("upstream hits = %d, want 1 (before the raise only)", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| // 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. |
| @@ -925,3 +1026,110 @@ func TestBarrierRefusesOpenProxiedConnection(t *testing.T) { |
| t.Fatalf("NoClientRefused = %d, want 2", c.NoClientRefused) |
| } |
| } |
| + |
| +// ProxyStatus counts each public listener apart: a proxied request on :80 |
| +// moves only "80", one on :443 only "443", per node too; ProxyCounters is |
| +// their sum. The instance is set once when the edge arms: stable while it |
| +// counts, new for an edge armed again (a restart). |
| +func TestProxyStatusPerListener(t *testing.T) { |
| + up, _ := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, "")) |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + before, ok := e.ProxyStatus() |
| + if !ok || len(before.Instance) != 32 || len(before.Listeners) != 2 { |
| + t.Fatalf("before wrap: %+v %v, want a 32-hex instance and both listeners", before, ok) |
| + } |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + if res := pe.exchange(t, false, ppv2Proxy("203.0.113.7:51000"), http.MethodGet, rlHost, "/"); res.status != http.StatusFound { |
| + t.Fatalf(":80 proxied: %d %q", res.status, res.body) |
| + } |
| + for i := 0; i < 2; i++ { |
| + if res := pe.exchange(t, true, ppv2Proxy("203.0.113.7:51001"), http.MethodGet, rlHost, "/"); res.status != http.StatusOK { |
| + t.Fatalf(":443 proxied: %d %q", res.status, res.body) |
| + } |
| + } |
| + wantNoClientRefused(t, pe.exchange(t, true, ppv2Local(), http.MethodGet, rlHost, "/"), "LOCAL on :443") |
| + s, ok := e.ProxyStatus() |
| + if !ok || s.Instance != before.Instance { |
| + t.Fatalf("instance %q, want %q unchanged", s.Instance, before.Instance) |
| + } |
| + node := ppLoopback[0] |
| + if c := s.Listeners["80"]; c.Proxied != 1 || c.ProxiedByNode[node] != 1 || c.NoClient != 0 || c.NoClientRefused != 0 { |
| + t.Fatalf(":80 counters %+v, want proxied 1 from %s and nothing else", c, node) |
| + } |
| + if c := s.Listeners["443"]; c.Proxied != 2 || c.ProxiedByNode[node] != 2 || c.NoClient != 1 || c.NoClientRefused != 1 { |
| + t.Fatalf(":443 counters %+v, want proxied 2 from %s, one no-client refused", c, node) |
| + } |
| + if sum := counters(t, e); sum.Proxied != 3 || sum.ProxiedByNode[node] != 3 || sum.NoClientRefused != 1 { |
| + t.Fatalf("ProxyCounters %+v, want the sum of both listeners", sum) |
| + } |
| + again := ppEdge(t) |
| + armed(t, again, ppLoopback, t.TempDir()) |
| + if s2, _ := again.ProxyStatus(); s2.Instance == s.Instance || len(s2.Instance) != 32 { |
| + t.Fatalf("a second arm kept instance %q", s2.Instance) |
| + } |
| + var unarmed Edge |
| + if _, ok := unarmed.ProxyStatus(); ok { |
| + t.Fatal("ProxyStatus armed on an unarmed edge") |
| + } |
| +} |
| + |
| +// Production-wired: an armed edge believes no header from a peer outside |
| +// CARLOS_INGRESS_PROXY_SOURCES. The header is consumed and ignored, the |
| +// upstream's X-Forwarded-For is the socket peer, and Ignored rises. |
| +func TestArmedEdgeIgnoresUnlistedPeerHeader(t *testing.T) { |
| + up, hits := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, "")) |
| + // The node list names an address no loopback peer has. |
| + armed(t, e, []netip.Addr{netip.MustParseAddr("10.9.9.9")}, t.TempDir()) |
| + 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 != "127.0.0.1" { |
| + t.Fatalf("header from an unlisted peer: %d X-Forwarded-For %q, want 200 and the socket peer 127.0.0.1", res.status, res.body) |
| + } |
| + if n := hits.Load(); n != 1 { |
| + t.Fatalf("upstream hits = %d, want 1", n) |
| + } |
| + c := counters(t, e) |
| + if c.Ignored != 1 || c.Proxied != 0 || len(c.ProxiedByNode) != 0 || c.NoClient != 0 { |
| + t.Fatalf("counters %+v, want ignored 1 and nothing trusted", c) |
| + } |
| +} |
| + |
| +// Production-wired: a proxied request over HTTP/2 (TLS, h2) reaches the |
| +// upstream with the header's source in X-Forwarded-For. |
| +func TestProxiedHTTP2ReachesUpstreamWithHeaderSource(t *testing.T) { |
| + up, hits := echoXFF(t) |
| + e := ppEdge(t, rlRoute(up, "")) |
| + armed(t, e, ppLoopback, t.TempDir()) |
| + pe := newProxyEdge(t, e, proxyOpts{}) |
| + 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(ppv2Proxy("203.0.113.9:52000")) |
| + } |
| + 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) |
| + } |
| + b, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.ProtoMajor != 2 || resp.StatusCode != http.StatusOK || string(b) != "203.0.113.9" { |
| + t.Fatalf("HTTP/2: %s %d X-Forwarded-For %q, want HTTP/2 200 and 203.0.113.9", resp.Proto, resp.StatusCode, b) |
| + } |
| + if n := hits.Load(); n != 1 { |
| + t.Fatalf("upstream hits = %d, want 1", n) |
| + } |
| + if s, _ := e.ProxyStatus(); s.Listeners["443"].ProxiedByNode[ppLoopback[0]] != 1 { |
| + t.Fatalf(":443 counters %+v, want one proxied from 127.0.0.1", s.Listeners["443"]) |
| + } |
| +} |
diff --git a/internal/host/edgetrust.go b/internal/host/edgetrust.go| index c998bb345..580a1c9d0 100644 |
| --- a/internal/host/edgetrust.go |
| +++ b/internal/host/edgetrust.go |
| @@ -10,7 +10,14 @@ package host |
| // (plus "persisted":false and "error" when the |
| // edge raised it but could not write its file) |
| // POST /v1/edge/trust-resume lower it; {"barrier":false} |
| -// GET /v1/edge/trust {"armed","barrier","counters","proxied_by_node"} |
| +// GET /v1/edge/trust {"armed","barrier","edge_instance","counters", |
| +// "proxied_by_node","by_listener"} |
| +// |
| +// The status's counters and proxied_by_node are both listeners summed (the |
| +// metric's view); by_listener has each listener's own, keyed "80" and |
| +// "443", from the same snapshot. edge_instance is a random id the edge set |
| +// once when it armed: a step that sees it change knows the counters |
| +// started again (a restart), whatever they read. |
| // |
| // An edge not armed for PROXY protocol answers {"armed":false,...} on each. |
| // The root verbs `carlos system edge trust-barrier|trust-resume|trust-status` |
| @@ -29,6 +36,7 @@ import ( |
| "fmt" |
| "io" |
| "log" |
| + "maps" |
| "net/http" |
| "os" |
| "strings" |
| @@ -47,9 +55,12 @@ type trustEdge interface { |
| RaiseTrustBarrier() (closed int, err error) |
| ResumeTrust() error |
| TrustBarrierUp() bool |
| - ProxyCounters() (proxyproto.Counters, bool) |
| + ProxyStatus() (edge.ProxyStatus, bool) |
| } |
| +// trustListeners are the ports by_listener carries, exactly. |
| +var trustListeners = []string{"80", "443"} |
| + |
| // proxySourcesSet is whether host.env arms the edge for PROXY protocol: |
| // CARLOS_INGRESS_PROXY_SOURCES parses to a non-empty list. A value that |
| // does not parse is false here; the edge refuses to start on it. |
| @@ -102,11 +113,21 @@ type trustCounters struct { |
| Timeout uint64 `json:"timeout"` |
| } |
| -// trustStatus is GET /v1/edge/trust and trust-status's line. |
| +// trustStatus is GET /v1/edge/trust and trust-status's line. Counters and |
| +// ProxiedByNode sum ByListener's two entries. |
| type trustStatus struct { |
| - Armed bool `json:"armed"` |
| - Barrier bool `json:"barrier"` |
| - Counters trustCounters `json:"counters"` |
| + Armed bool `json:"armed"` |
| + Barrier bool `json:"barrier"` |
| + EdgeInstance string `json:"edge_instance"` |
| + Counters trustCounters `json:"counters"` |
| + ProxiedByNode map[string]uint64 `json:"proxied_by_node"` |
| + ByListener map[string]trustListener `json:"by_listener"` |
| +} |
| + |
| +// trustListener is one public listener's counters, flat, and its per-node |
| +// proxied counts. |
| +type trustListener struct { |
| + trustCounters |
| ProxiedByNode map[string]uint64 `json:"proxied_by_node"` |
| } |
| @@ -130,16 +151,25 @@ type trustOff struct { |
| // drain call child reads it from the socket and carries it to root |
| // (drainCallResult.Trust). Every field is presence-aware, so an answer |
| // missing what its op requires is refused (validTrust), never read as a |
| -// zero: a lost barrier field is not "down". ProxiedByNode is not omitted |
| -// when nil, so an empty object and an absent one stay apart. |
| +// zero: a lost barrier field is not "down". ProxiedByNode and ByListener |
| +// are not omitted when nil, so an empty object and an absent one stay |
| +// apart. |
| type trustResult struct { |
| - Armed *bool `json:"armed,omitempty"` |
| - Barrier *bool `json:"barrier,omitempty"` |
| - Closed *int `json:"closed,omitempty"` |
| - Persisted *bool `json:"persisted,omitempty"` |
| - Error string `json:"error,omitempty"` |
| - Counters *trustCountersWire `json:"counters,omitempty"` |
| - ProxiedByNode map[string]uint64 `json:"proxied_by_node"` |
| + Armed *bool `json:"armed,omitempty"` |
| + Barrier *bool `json:"barrier,omitempty"` |
| + Closed *int `json:"closed,omitempty"` |
| + Persisted *bool `json:"persisted,omitempty"` |
| + Error string `json:"error,omitempty"` |
| + EdgeInstance *string `json:"edge_instance,omitempty"` |
| + Counters *trustCountersWire `json:"counters,omitempty"` |
| + ProxiedByNode map[string]uint64 `json:"proxied_by_node"` |
| + ByListener map[string]*trustListenerWire `json:"by_listener"` |
| +} |
| + |
| +// trustListenerWire is trustListener with each counter's presence. |
| +type trustListenerWire struct { |
| + trustCountersWire |
| + ProxiedByNode map[string]uint64 `json:"proxied_by_node"` |
| } |
| // trustCountersWire is trustCounters with each counter's presence. |
| @@ -170,6 +200,57 @@ func (c *trustCountersWire) counters() (trustCounters, bool) { |
| }, true |
| } |
| +// add is c plus d, counter by counter. |
| +func (c trustCounters) add(d trustCounters) trustCounters { |
| + return trustCounters{ |
| + Proxied: c.Proxied + d.Proxied, NoClient: c.NoClient + d.NoClient, NoClientRefused: c.NoClientRefused + d.NoClientRefused, |
| + Ignored: c.Ignored + d.Ignored, IgnoredPrivate: c.IgnoredPrivate + d.IgnoredPrivate, MarkerTrusted: c.MarkerTrusted + d.MarkerTrusted, |
| + Malformed: c.Malformed + d.Malformed, Timeout: c.Timeout + d.Timeout, |
| + } |
| +} |
| + |
| +// statusShape is whether a status answer's instance and per-listener |
| +// counters are complete: armed, a non-empty instance and exactly the two |
| +// listeners, each with every counter and its per-node map, summing to the |
| +// answer's own counters and proxied_by_node; not armed, an empty instance |
| +// and no listener. |
| +func (t *trustResult) statusShape(armed bool, total trustCounters) bool { |
| + if t.EdgeInstance == nil || t.ByListener == nil { |
| + return false |
| + } |
| + if !armed { |
| + return *t.EdgeInstance == "" && len(t.ByListener) == 0 |
| + } |
| + if *t.EdgeInstance == "" || len(t.ByListener) != len(trustListeners) { |
| + return false |
| + } |
| + var sum trustCounters |
| + byNode := map[string]uint64{} |
| + for _, port := range trustListeners { |
| + l := t.ByListener[port] |
| + if l == nil || l.ProxiedByNode == nil { |
| + return false |
| + } |
| + c, ok := l.counters() |
| + if !ok { |
| + return false |
| + } |
| + sum = sum.add(c) |
| + for a, n := range l.ProxiedByNode { |
| + byNode[a] += n |
| + } |
| + } |
| + if sum != total || len(byNode) != len(t.ProxiedByNode) { |
| + return false |
| + } |
| + for a, n := range byNode { |
| + if t.ProxiedByNode[a] != n { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| // errTrustIncomplete is an agent's trust answer without what its op |
| // requires. |
| var errTrustIncomplete = errors.New("the agent answered nothing usable") |
| @@ -192,7 +273,7 @@ func validTrust(op string, t *trustResult) (trustAnswer, error) { |
| if t == nil { |
| return 0, errTrustIncomplete |
| } |
| - change := t.Counters == nil && t.ProxiedByNode == nil |
| + change := t.Counters == nil && t.ProxiedByNode == nil && t.ByListener == nil && t.EdgeInstance == nil |
| switch { |
| case t.Armed != nil && !*t.Armed: |
| // Not armed: the barrier and resume answer is exactly |
| @@ -201,7 +282,7 @@ func validTrust(op string, t *trustResult) (trustAnswer, error) { |
| return 0, errTrustIncomplete |
| } |
| if op == "trust-status" { |
| - if _, ok := t.Counters.counters(); !ok || t.ProxiedByNode == nil { |
| + if c, ok := t.Counters.counters(); !ok || t.ProxiedByNode == nil || !t.statusShape(false, c) { |
| return 0, errTrustIncomplete |
| } |
| } else if !change { |
| @@ -209,7 +290,8 @@ func validTrust(op string, t *trustResult) (trustAnswer, error) { |
| } |
| return trustAnswerNotArmed, nil |
| case op == "trust-status": |
| - if _, ok := t.Counters.counters(); t.Armed == nil || !ok || t.Barrier == nil || t.ProxiedByNode == nil || |
| + c, ok := t.Counters.counters() |
| + if t.Armed == nil || !ok || t.Barrier == nil || t.ProxiedByNode == nil || !t.statusShape(true, c) || |
| t.Closed != nil || t.Persisted != nil || t.Error != "" { |
| return 0, errTrustIncomplete |
| } |
| @@ -241,21 +323,42 @@ func barrierWord(up bool) string { |
| return "down" |
| } |
| -func trustStatusOf(e trustEdge) trustStatus { |
| - c, armed := e.ProxyCounters() |
| - s := trustStatus{ |
| - Armed: armed, |
| - Barrier: e.TrustBarrierUp(), |
| - Counters: trustCounters{ |
| - Proxied: c.Proxied, NoClient: c.NoClient, NoClientRefused: c.NoClientRefused, |
| - Ignored: c.Ignored, IgnoredPrivate: c.IgnoredPrivate, MarkerTrusted: c.MarkerTrusted, |
| - Malformed: c.Malformed, Timeout: c.Timeout, |
| - }, |
| - ProxiedByNode: make(map[string]uint64, len(c.ProxiedByNode)), |
| +// trustCountersOf is c's counters under the journal's names. |
| +func trustCountersOf(c proxyproto.Counters) trustCounters { |
| + return trustCounters{ |
| + Proxied: c.Proxied, NoClient: c.NoClient, NoClientRefused: c.NoClientRefused, |
| + Ignored: c.Ignored, IgnoredPrivate: c.IgnoredPrivate, MarkerTrusted: c.MarkerTrusted, |
| + Malformed: c.Malformed, Timeout: c.Timeout, |
| } |
| +} |
| + |
| +func byNodeOf(c proxyproto.Counters) map[string]uint64 { |
| + m := make(map[string]uint64, len(c.ProxiedByNode)) |
| for a, n := range c.ProxiedByNode { |
| - s.ProxiedByNode[a.String()] = n |
| + m[a.String()] = n |
| + } |
| + return m |
| +} |
| + |
| +// trustStatusOf is the status from one snapshot of e: the sums are made |
| +// from the very per-listener counters it carries. |
| +func trustStatusOf(e trustEdge) trustStatus { |
| + ps, armed := e.ProxyStatus() |
| + s := trustStatus{Armed: armed, Barrier: e.TrustBarrierUp(), EdgeInstance: ps.Instance, |
| + ByListener: map[string]trustListener{}} |
| + if !armed { |
| + s.EdgeInstance = "" |
| + s.ProxiedByNode = map[string]uint64{} |
| + return s |
| + } |
| + listeners := make(map[string]proxyproto.Counters, len(trustListeners)) |
| + for _, port := range trustListeners { |
| + c := ps.Listeners[port] |
| + listeners[port] = c |
| + s.ByListener[port] = trustListener{trustCounters: trustCountersOf(c), ProxiedByNode: byNodeOf(c)} |
| } |
| + sum := edge.SumProxyCounters(listeners) |
| + s.Counters, s.ProxiedByNode = trustCountersOf(sum), byNodeOf(sum) |
| return s |
| } |
| @@ -456,13 +559,15 @@ func (cmd edgeTrustCommand) run(ctx context.Context, args []string, out, stderr |
| } |
| // trustStatusLine is a status answer validTrust accepted, as trust-status |
| -// prints it: every field present, proxied_by_node an object even when |
| -// empty. |
| +// prints it: every field present, proxied_by_node and by_listener objects |
| +// even when empty. |
| func trustStatusLine(t *trustResult) trustStatus { |
| counters, _ := t.Counters.counters() |
| - s := trustStatus{Armed: *t.Armed, Barrier: *t.Barrier, Counters: counters, ProxiedByNode: map[string]uint64{}} |
| - for a, n := range t.ProxiedByNode { |
| - s.ProxiedByNode[a] = n |
| + s := trustStatus{Armed: *t.Armed, Barrier: *t.Barrier, EdgeInstance: *t.EdgeInstance, Counters: counters, |
| + ProxiedByNode: maps.Clone(t.ProxiedByNode), ByListener: map[string]trustListener{}} |
| + for port, l := range t.ByListener { |
| + c, _ := l.counters() |
| + s.ByListener[port] = trustListener{trustCounters: c, ProxiedByNode: maps.Clone(l.ProxiedByNode)} |
| } |
| return s |
| } |
diff --git a/internal/host/edgetrust_linux_test.go b/internal/host/edgetrust_linux_test.go| index 81d310e64..9aac46c0e 100644 |
| --- a/internal/host/edgetrust_linux_test.go |
| +++ b/internal/host/edgetrust_linux_test.go |
| @@ -107,6 +107,14 @@ func TestDrainCallTrustRefusesIncomplete(t *testing.T) { |
| t.Cleanup(func() { srv.Close() }) |
| call := socketDrainCall(newDrainClient(path)) |
| const counters = `{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0}` |
| + const zeroListener = `{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0,"proxied_by_node":{}}` |
| + const oneListener = `{"proxied":1,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0,"proxied_by_node":{"172.31.29.110":1}}` |
| + const one = `{"proxied":1,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0}` |
| + const inst = `"edge_instance":"` + fakeEdgeInstance + `"` |
| + listeners := `"by_listener":{"80":` + zeroListener + `,"443":` + zeroListener + `}` |
| + status := func(fields ...string) string { |
| + return `{"armed":true,"barrier":false,` + strings.Join(fields, ",") + `}` |
| + } |
| for _, tc := range []struct { |
| op, body string |
| ok bool |
| @@ -121,13 +129,30 @@ func TestDrainCallTrustRefusesIncomplete(t *testing.T) { |
| {"trust-barrier", `{"barrier":true,"closed":1,"persisted":false}`, false}, |
| {"trust-barrier", `{"barrier":true,"closed":1,"persisted":false,"error":"edge: not persisted"}`, true}, |
| {"trust-barrier", `{"armed":false,"barrier":false}`, true}, |
| - {"trust-status", `{"armed":true,"barrier":false,"counters":` + counters + `,"proxied_by_node":{}}`, true}, |
| - {"trust-status", `{"armed":true,"counters":` + counters + `,"proxied_by_node":{}}`, false}, |
| - {"trust-status", `{"armed":true,"barrier":false,"counters":{"proxied":1},"proxied_by_node":{}}`, false}, |
| - {"trust-status", `{"armed":true,"barrier":false,"counters":` + counters + `}`, false}, |
| - {"trust-status", `{"armed":true,"barrier":false,"counters":` + counters + `,"proxied_by_node":null}`, false}, |
| - {"trust-status", `{"barrier":false,"counters":` + counters + `,"proxied_by_node":{}}`, false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`, listeners), true}, |
| + {"trust-status", `{"armed":true,` + inst + `,"counters":` + counters + `,"proxied_by_node":{},` + listeners + `}`, false}, |
| + {"trust-status", status(inst, `"counters":{"proxied":1}`, `"proxied_by_node":{}`, listeners), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, listeners), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":null`, listeners), false}, |
| + {"trust-status", `{"barrier":false,` + inst + `,"counters":` + counters + `,"proxied_by_node":{},` + listeners + `}`, false}, |
| {"trust-status", `null`, false}, |
| + // The per-listener counters and the edge's instance (a restart |
| + // must be visible): every one present, summing to the totals. |
| + {"trust-status", status(`"counters":`+counters, `"proxied_by_node":{}`, listeners), false}, |
| + {"trust-status", status(`"edge_instance":""`, `"counters":`+counters, `"proxied_by_node":{}`, listeners), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`, `"by_listener":null`), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`, `"by_listener":{"80":`+zeroListener+`}`), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`, `"by_listener":{"80":`+zeroListener+`,"443":`+zeroListener+`,"8080":`+zeroListener+`}`), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`, `"by_listener":{"80":`+zeroListener+`,"443":{"proxied":0}}`), false}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`, `"by_listener":{"80":`+zeroListener+`,"443":`+counters+`}`), false}, |
| + {"trust-status", status(inst, `"counters":`+one, `"proxied_by_node":{"172.31.29.110":1}`, `"by_listener":{"80":`+zeroListener+`,"443":`+oneListener+`}`), true}, |
| + {"trust-status", status(inst, `"counters":`+counters, `"proxied_by_node":{}`, `"by_listener":{"80":`+zeroListener+`,"443":`+oneListener+`}`), false}, |
| + {"trust-status", status(inst, `"counters":`+one, `"proxied_by_node":{"172.31.11.189":1}`, `"by_listener":{"80":`+zeroListener+`,"443":`+oneListener+`}`), false}, |
| + {"trust-status", `{"armed":false,"barrier":false,"edge_instance":"","counters":` + counters + `,"proxied_by_node":{},"by_listener":{}}`, true}, |
| + {"trust-status", `{"armed":false,"barrier":false,"counters":` + counters + `,"proxied_by_node":{},"by_listener":{}}`, false}, |
| + {"trust-status", `{"armed":false,"barrier":false,"edge_instance":"","counters":` + counters + `,"proxied_by_node":{}}`, false}, |
| + {"trust-barrier", `{"barrier":true,"closed":0,` + inst + `}`, false}, |
| } { |
| body.Store(tc.body) |
| r, err := call(context.Background(), tc.op, "", nil) |
diff --git a/internal/host/edgetrust_test.go b/internal/host/edgetrust_test.go| index 931a3d3f1..a9fa77579 100644 |
| --- a/internal/host/edgetrust_test.go |
| +++ b/internal/host/edgetrust_test.go |
| @@ -28,8 +28,10 @@ type fakeTrustEdge struct { |
| closed int |
| raiseErr error |
| // raiseUp: a raise that fails still raises (an unpersisted barrier). |
| - raiseUp bool |
| - counters proxyproto.Counters |
| + raiseUp bool |
| + // counters by listener ("80", "443"); instance is the edge's. |
| + counters map[string]proxyproto.Counters |
| + instance string |
| raised int |
| resumed int |
| } |
| @@ -70,38 +72,76 @@ func (f *fakeTrustEdge) TrustBarrierUp() bool { |
| return f.armed && f.barrier |
| } |
| -func (f *fakeTrustEdge) ProxyCounters() (proxyproto.Counters, bool) { |
| +func (f *fakeTrustEdge) ProxyStatus() (edge.ProxyStatus, bool) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| if !f.armed { |
| - return proxyproto.Counters{}, false |
| + return edge.ProxyStatus{}, false |
| + } |
| + s := edge.ProxyStatus{Instance: f.instance, Listeners: map[string]proxyproto.Counters{}} |
| + if s.Instance == "" { |
| + s.Instance = fakeEdgeInstance |
| + } |
| + for _, port := range []string{"80", "443"} { |
| + c := f.counters[port] |
| + c.ProxiedByNode = map[netip.Addr]uint64{} |
| + for a, n := range f.counters[port].ProxiedByNode { |
| + c.ProxiedByNode[a] = n |
| + } |
| + s.Listeners[port] = c |
| } |
| - c := f.counters |
| - c.ProxiedByNode = map[netip.Addr]uint64{} |
| - for a, n := range f.counters.ProxiedByNode { |
| - c.ProxiedByNode[a] = n |
| + return s, true |
| +} |
| + |
| +// ProxyCounters is the metric's view: both listeners summed. |
| +func (f *fakeTrustEdge) ProxyCounters() (proxyproto.Counters, bool) { |
| + s, ok := f.ProxyStatus() |
| + if !ok { |
| + return proxyproto.Counters{}, false |
| } |
| - return c, true |
| + return edge.SumProxyCounters(s.Listeners), true |
| } |
| +// setCounters puts c on :443, :80 at zero. |
| func (f *fakeTrustEdge) setCounters(c proxyproto.Counters) { |
| f.mu.Lock() |
| defer f.mu.Unlock() |
| - f.counters = c |
| + f.counters = map[string]proxyproto.Counters{"443": c} |
| } |
| -func trustCountersFixture() proxyproto.Counters { |
| - return proxyproto.Counters{ |
| - Proxied: 10, NoClient: 2, NoClientRefused: 1, Ignored: 3, IgnoredPrivate: 4, |
| - MarkerTrusted: 5, Malformed: 6, Timeout: 7, |
| - ProxiedByNode: map[netip.Addr]uint64{ |
| - netip.MustParseAddr("172.31.29.110"): 6, |
| - netip.MustParseAddr("172.31.11.189"): 4, |
| +const fakeEdgeInstance = "0123456789abcdef0123456789abcdef" |
| + |
| +func trustCountersFixture() map[string]proxyproto.Counters { |
| + return map[string]proxyproto.Counters{ |
| + "80": { |
| + Proxied: 3, NoClient: 2, Ignored: 1, IgnoredPrivate: 4, Malformed: 2, Timeout: 3, |
| + ProxiedByNode: map[netip.Addr]uint64{ |
| + netip.MustParseAddr("172.31.29.110"): 2, |
| + netip.MustParseAddr("172.31.11.189"): 1, |
| + }, |
| + }, |
| + "443": { |
| + Proxied: 7, NoClientRefused: 1, Ignored: 2, MarkerTrusted: 5, Malformed: 4, Timeout: 4, |
| + ProxiedByNode: map[netip.Addr]uint64{ |
| + netip.MustParseAddr("172.31.29.110"): 4, |
| + netip.MustParseAddr("172.31.11.189"): 3, |
| + }, |
| }, |
| } |
| } |
| -const trustStatusFixtureJSON = `{"armed":true,"barrier":false,"counters":{"proxied":10,"no_client":2,"no_client_refused":1,"ignored":3,"ignored_private":4,"marker_trusted":5,"malformed":6,"timeout":7},"proxied_by_node":{"172.31.11.189":4,"172.31.29.110":6}}` |
| +const trustStatusFixtureJSON = `{"armed":true,"barrier":false,"edge_instance":"0123456789abcdef0123456789abcdef",` + |
| + `"counters":{"proxied":10,"no_client":2,"no_client_refused":1,"ignored":3,"ignored_private":4,"marker_trusted":5,"malformed":6,"timeout":7},` + |
| + `"proxied_by_node":{"172.31.11.189":4,"172.31.29.110":6},` + |
| + `"by_listener":{"443":{"proxied":7,"no_client":0,"no_client_refused":1,"ignored":2,"ignored_private":0,"marker_trusted":5,"malformed":4,"timeout":4,"proxied_by_node":{"172.31.11.189":3,"172.31.29.110":4}},` + |
| + `"80":{"proxied":3,"no_client":2,"no_client_refused":0,"ignored":1,"ignored_private":4,"marker_trusted":0,"malformed":2,"timeout":3,"proxied_by_node":{"172.31.11.189":1,"172.31.29.110":2}}}}` |
| + |
| +// unarmedStatusJSON is an unarmed edge's status line. |
| +const unarmedStatusJSON = `{"armed":false,"barrier":false,"edge_instance":"","counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{},"by_listener":{}}` |
| + |
| +// zeroStatusJSON is an armed edge's status line with nothing counted. |
| +const zeroStatusJSON = `{"armed":true,"barrier":false,"edge_instance":"0123456789abcdef0123456789abcdef","counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{},` + |
| + `"by_listener":{"443":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0,"proxied_by_node":{}},"80":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0,"proxied_by_node":{}}}}` |
| func serveTrust(t *testing.T, h http.Handler, method, target string) (int, string) { |
| t.Helper() |
| @@ -180,7 +220,7 @@ func TestEdgeTrustRoutes(t *testing.T) { |
| // edge refuses to start on a value it cannot read): armed false. |
| off := edgeTrustHandler(&fakeTrustEdge{}) |
| if code, body := serveTrust(t, off, http.MethodGet, "/v1/edge/trust"); code != 200 || |
| - body != `{"armed":false,"barrier":false,"counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{}}` { |
| + body != unarmedStatusJSON { |
| t.Fatalf("unarmed status: %d %s", code, body) |
| } |
| for _, p := range []string{"/v1/edge/trust-barrier", "/v1/edge/trust-resume"} { |
| @@ -352,7 +392,14 @@ func TestTrustMetricFromEnv(t *testing.T) { |
| // shape parseDrainCall checks strictly. |
| func TestDrainCallTrustRoundTrip(t *testing.T) { |
| armed, up, down, closed := true, true, false, 2 |
| - status := trustResult{Armed: &armed, Barrier: &up, Counters: zeroCountersWire(), ProxiedByNode: map[string]uint64{"172.31.29.110": 1}} |
| + instance := fakeEdgeInstance |
| + one := zeroCountersWire() |
| + *one.Proxied = 1 |
| + status := trustResult{Armed: &armed, Barrier: &up, EdgeInstance: &instance, Counters: one, ProxiedByNode: map[string]uint64{"172.31.29.110": 1}, |
| + ByListener: map[string]*trustListenerWire{ |
| + "80": {trustCountersWire: *zeroCountersWire(), ProxiedByNode: map[string]uint64{}}, |
| + "443": {trustCountersWire: *one, ProxiedByNode: map[string]uint64{"172.31.29.110": 1}}, |
| + }} |
| empty := status |
| empty.ProxiedByNode = map[string]uint64{} |
| for _, want := range []trustResult{ |
| @@ -375,8 +422,8 @@ func TestDrainCallTrustRoundTrip(t *testing.T) { |
| if !bytes.Equal(got, exp) { |
| t.Fatalf("round trip %s, want %s", got, exp) |
| } |
| - if want.Armed != nil && r.Trust.ProxiedByNode == nil { |
| - t.Fatalf("%s: proxied_by_node lost its presence", b) |
| + if want.Armed != nil && (r.Trust.ProxiedByNode == nil || r.Trust.ByListener == nil || r.Trust.EdgeInstance == nil) { |
| + t.Fatalf("%s: proxied_by_node, by_listener or edge_instance lost its presence", b) |
| } |
| } |
| if _, err := parseDrainCall([]byte(`{"v":1,"trust":{"barrier":true,"other":1}}`)); err == nil { |
| @@ -403,7 +450,8 @@ func TestDrainCallTrustRoundTrip(t *testing.T) { |
| // agent's failures as exit 1, and arguments and root checked first. |
| func TestEdgeTrustVerbAnswers(t *testing.T) { |
| armed, notArmed, up, down, closed := true, false, true, false, 4 |
| - status := &trustResult{Armed: &armed, Barrier: &down, Counters: zeroCountersWire(), ProxiedByNode: map[string]uint64{}} |
| + status := zeroStatusWire(true) |
| + unarmedStatus := zeroStatusWire(false) |
| run := func(r drainCallResult, callErr error, hostEnv string, euid int, args ...string) (int, string, string, []string) { |
| var asked []string |
| cmd := edgeTrustCommand{ |
| @@ -446,10 +494,8 @@ func TestEdgeTrustVerbAnswers(t *testing.T) { |
| {"status, no proxied_by_node", drainCallResult{V: 1, Trust: &trustResult{Armed: &armed, Barrier: &down, Counters: zeroCountersWire()}}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| {"status, a counter missing", drainCallResult{V: 1, Trust: &trustResult{Armed: &armed, Barrier: &down, Counters: &trustCountersWire{Proxied: new(uint64)}, ProxiedByNode: map[string]uint64{}}}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| {"barrier, no closed", drainCallResult{V: 1, Trust: &trustResult{Barrier: &up}}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent answered nothing usable\n"}, |
| - {"status", drainCallResult{V: 1, Trust: status}, nil, "", 0, []string{"trust-status"}, 0, |
| - `{"armed":true,"barrier":false,"counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{}}` + "\n", ""}, |
| - {"status unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed, Barrier: &down, Counters: zeroCountersWire(), ProxiedByNode: map[string]uint64{}}}, nil, "", 0, []string{"trust-status"}, 2, |
| - `{"armed":false,"barrier":false,"counters":{"proxied":0,"no_client":0,"no_client_refused":0,"ignored":0,"ignored_private":0,"marker_trusted":0,"malformed":0,"timeout":0},"proxied_by_node":{}}` + "\n", |
| + {"status", drainCallResult{V: 1, Trust: status}, nil, "", 0, []string{"trust-status"}, 0, zeroStatusJSON + "\n", ""}, |
| + {"status unarmed", drainCallResult{V: 1, Trust: unarmedStatus}, nil, "", 0, []string{"trust-status"}, 2, unarmedStatusJSON + "\n", |
| "edge: this box is not armed for PROXY protocol\n"}, |
| {"barrier unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed, Barrier: &down}}, nil, "", 0, []string{"trust-barrier"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| {"resume unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: ¬Armed, Barrier: &down}}, nil, "", 0, []string{"trust-resume"}, 2, "", "edge: this box is not armed for PROXY protocol\n"}, |
| @@ -487,6 +533,21 @@ func TestEdgeTrustVerbAnswers(t *testing.T) { |
| } |
| } |
| +// zeroStatusWire is a status answer with nothing counted, armed (both |
| +// listeners, an instance) or not (neither). |
| +func zeroStatusWire(armed bool) *trustResult { |
| + down, instance := false, "" |
| + t := &trustResult{Armed: &armed, Barrier: &down, EdgeInstance: &instance, Counters: zeroCountersWire(), |
| + ProxiedByNode: map[string]uint64{}, ByListener: map[string]*trustListenerWire{}} |
| + if armed { |
| + instance = fakeEdgeInstance |
| + for _, port := range []string{"80", "443"} { |
| + t.ByListener[port] = &trustListenerWire{trustCountersWire: *zeroCountersWire(), ProxiedByNode: map[string]uint64{}} |
| + } |
| + } |
| + return t |
| +} |
| + |
| // zeroCountersWire is a status answer's counters, every one present. |
| func zeroCountersWire() *trustCountersWire { |
| z := func() *uint64 { return new(uint64) } |
diff --git a/internal/host/edgetrust_wiring_test.go b/internal/host/edgetrust_wiring_test.go| index c54770eff..2b4d00f84 100644 |
| --- a/internal/host/edgetrust_wiring_test.go |
| +++ b/internal/host/edgetrust_wiring_test.go |
| @@ -2,6 +2,7 @@ package host |
| import ( |
| "context" |
| + "encoding/json" |
| "errors" |
| "net/http" |
| "net/netip" |
| @@ -65,9 +66,20 @@ func TestAgentTrustWiringWithARealEdge(t *testing.T) { |
| if _, err := os.Stat(file); err != nil || !e.TrustBarrierUp() { |
| t.Fatalf("after the raise: file %v, up %v", err, e.TrustBarrierUp()) |
| } |
| - if code, body := serveTrust(t, h, http.MethodGet, "/v1/edge/trust"); code != 200 || !strings.HasPrefix(body, `{"armed":true,"barrier":true,"counters":{`) || !strings.HasSuffix(body, `"proxied_by_node":{}}`) { |
| + code, body := serveTrust(t, h, http.MethodGet, "/v1/edge/trust") |
| + ps, _ := e.ProxyStatus() |
| + if code != 200 || len(ps.Instance) != 32 || |
| + body != strings.Replace(strings.Replace(zeroStatusJSON, `"barrier":false`, `"barrier":true`, 1), fakeEdgeInstance, ps.Instance, 1) { |
| t.Fatalf("status: %d %s", code, body) |
| } |
| + // What the verb would print: the child's and root's checks accept it. |
| + var r trustResult |
| + if err := json.Unmarshal([]byte(body), &r); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a, err := validTrust("trust-status", &r); err != nil || a != trustAnswerStatus { |
| + t.Fatalf("validTrust of the real edge's status: %v %v", a, err) |
| + } |
| if code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-resume"); code != 200 || body != `{"barrier":false}` { |
| t.Fatalf("resume: %d %s", code, body) |
| } |
diff --git a/internal/host/proxyfeature.go b/internal/host/proxyfeature.go| index 3d51d0a6c..c4976bf64 100644 |
| --- a/internal/host/proxyfeature.go |
| +++ b/internal/host/proxyfeature.go |
| @@ -4,9 +4,6 @@ import ( |
| "bytes" |
| "context" |
| "encoding/json" |
| - "errors" |
| - "fmt" |
| - "io" |
| "log" |
| "os" |
| "path/filepath" |
| @@ -32,9 +29,6 @@ import ( |
| // ingressProxyFeature is the feature the guard asks a binary for. |
| const ingressProxyFeature = version.FeatureIngressProxyV2 |
| -// proxyHostEnvLimit bounds the host.env read, as the exec-sandbox reader's. |
| -const proxyHostEnvLimit = 1 << 20 |
| - |
| // proxyFeatureRefusal is the guard's refusal of binary. |
| type proxyFeatureRefusal struct{ binary string } |
| @@ -94,11 +88,12 @@ func proxyGuardArmed(getenv func(string) string, readHostEnv func() (func(string |
| } |
| // productionProxyArmed is proxyGuardArmed for a root process outside an |
| -// applier: its own environment and /etc/carlos/host.env. |
| +// applier: its own environment and /etc/carlos/host.env, read through the |
| +// exec-sandbox reader's protected open (sandboxHostEnvironment): no symlink |
| +// at any component, non-blocking, a regular file only, bounded. Anything |
| +// else is an error, which arms the guard. |
| func productionProxyArmed() bool { |
| - return proxyGuardArmed(os.Getenv, func() (func(string) string, error) { |
| - return readProxyHostEnv("/etc/carlos/host.env") |
| - }) |
| + return proxyGuardArmed(os.Getenv, sandboxHostEnvironment) |
| } |
| // proxyPrevAllowed is the guard for a predecessor outside an applier (the |
| @@ -112,36 +107,15 @@ func proxyPrevAllowed(ctx context.Context, prev string, armed func() bool, run f |
| return &proxyFeatureRefusal{binary: prev} |
| } |
| -// readProxyHostEnv reads host.env at path into a getenv, with the |
| -// EnvironmentFile parser the exec-sandbox reader uses. A missing file is an |
| -// empty environment. |
| -func readProxyHostEnv(path string) (func(string) string, error) { |
| - f, err := os.Open(path) |
| - if errors.Is(err, os.ErrNotExist) { |
| - return func(string) string { return "" }, nil |
| - } |
| - if err != nil { |
| - return nil, err |
| - } |
| - defer f.Close() |
| - raw, err := io.ReadAll(io.LimitReader(f, proxyHostEnvLimit+1)) |
| - if err != nil { |
| - return nil, err |
| - } |
| - if len(raw) > proxyHostEnvLimit { |
| - return nil, fmt.Errorf("%s: larger than %d bytes", path, proxyHostEnvLimit) |
| - } |
| - return sandboxEnvironmentValues(raw), nil |
| -} |
| - |
| // proxyArmedHere is proxyGuardArmed for this applier: its process |
| // environment seam (os.Getenv in production, nil in tests) and the host.env |
| -// under its etcDir. |
| +// under its etcDir, through the same protected reader |
| +// (sandboxHostEnvironmentAt). |
| func (a *systemApplier) proxyArmedHere() bool { |
| var read func() (func(string) string, error) |
| if a.etcDir != "" { |
| read = func() (func(string) string, error) { |
| - return readProxyHostEnv(filepath.Join(a.etcDir, "carlos", "host.env")) |
| + return sandboxHostEnvironmentAt(filepath.Join(a.etcDir, "carlos", "host.env")) |
| } |
| } |
| return proxyGuardArmed(a.proxyEnv, read) |
| @@ -221,27 +195,48 @@ func (a *systemApplier) restoreCopyAllowed(restore string) error { |
| // RunSystemProxyAllowsPrev is `carlos system proxy-allows-prev |
| // /opt/carlos/carlos.prev`: the recovery unit's gate on running |
| // carlos.prev, the same shape as exec-sandbox-allows-prev. Exit 0 when the |
| -// box is not armed for PROXY protocol or carlos.prev reports |
| -// ingress-proxy-v2; 1 when it is armed and carlos.prev does not; 2 for |
| -// any other arguments. Any non-zero exit makes the unit run the current |
| -// binary's recovery, which refuses the same carlos.prev itself. |
| +// box is not armed for PROXY protocol, without running or reading anything |
| +// more, or when carlos.prev passes the exec-sandbox rule and reports |
| +// ingress-proxy-v2; 1 when it is armed and carlos.prev does not, or the |
| +// exec-sandbox rule refuses it (then it is never run); 2 for any other |
| +// arguments. Any non-zero exit makes the unit run the current binary's |
| +// recovery, which refuses the same carlos.prev itself. |
| func RunSystemProxyAllowsPrev(args []string) { |
| run := func(ctx context.Context, name string, args ...string) ([]byte, error) { |
| out, err := productionSysOps().run(ctx, systemVersionWait, name, args...) |
| return []byte(out), err |
| } |
| - os.Exit(proxyAllowsPrev(context.Background(), args, "/opt/carlos/carlos.prev", productionProxyArmed, run, log.Printf)) |
| + os.Exit(proxyAllowsPrevAt(context.Background(), args, "/opt/carlos/carlos.prev", "/etc/carlos/host.env", os.Getenv, run, log.Printf)) |
| +} |
| + |
| +// proxyAllowsPrevAt is the verb as production wires it, over the |
| +// predecessor and host.env paths: arming from the process environment and |
| +// host.env, and the exec-sandbox rule (sandboxAllowsPrev), both through the |
| +// protected host.env reader. |
| +func proxyAllowsPrevAt(ctx context.Context, args []string, prev, hostEnvPath string, getenv func(string) string, run func(ctx context.Context, binary string, args ...string) ([]byte, error), logf func(string, ...any)) int { |
| + hostEnv := func() (func(string) string, error) { return sandboxHostEnvironmentAt(hostEnvPath) } |
| + armed := func() bool { return proxyGuardArmed(getenv, hostEnv) } |
| + sandbox := func(path string) error { return sandboxAllowsPrev(hostEnv, path) } |
| + return proxyAllowsPrev(ctx, args, prev, armed, sandbox, run, logf) |
| } |
| // proxyAllowsPrev is the verb with its seams: the one path it accepts, |
| -// whether the box is armed, how a binary is run, and where a refusal is |
| -// logged. |
| -func proxyAllowsPrev(ctx context.Context, args []string, prev string, armed func() bool, run func(ctx context.Context, binary string, args ...string) ([]byte, error), logf func(string, ...any)) int { |
| +// whether the box is armed, the exec-sandbox rule, how a binary is run, |
| +// and where a refusal is logged. On an armed box the exec-sandbox rule |
| +// comes first, so a predecessor it refuses is never run. |
| +func proxyAllowsPrev(ctx context.Context, args []string, prev string, armed func() bool, sandbox func(string) error, run func(ctx context.Context, binary string, args ...string) ([]byte, error), logf func(string, ...any)) int { |
| if len(args) != 1 || args[0] != prev { |
| logf("usage: carlos system proxy-allows-prev %s", prev) |
| return 2 |
| } |
| - if err := proxyPrevAllowed(ctx, prev, armed, run); err != nil { |
| + if !armed() { |
| + return 0 |
| + } |
| + if err := sandbox(prev); err != nil { |
| + logf("%s: %v; not running it", prev, err) |
| + return 1 |
| + } |
| + if err := proxyPrevAllowed(ctx, prev, func() bool { return true }, run); err != nil { |
| logf("%v", err) |
| return 1 |
| } |
diff --git a/internal/host/proxyfeature_linux_test.go b/internal/host/proxyfeature_linux_test.go| index 048c492db..35b644207 100644 |
| --- a/internal/host/proxyfeature_linux_test.go |
| +++ b/internal/host/proxyfeature_linux_test.go |
| @@ -6,10 +6,13 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "fmt" |
| "os" |
| "path/filepath" |
| "strings" |
| + "syscall" |
| "testing" |
| + "time" |
| ) |
| // TestRollbackRefusedBeforeDisruption: the operator's rollback of a |
| @@ -173,3 +176,135 @@ func TestGroupRecoveryRefusedBeforePermit(t *testing.T) { |
| } |
| assertGroupUntouched(t, f, p, *clears, binary) |
| } |
| + |
| +// TestProxyHostEnvReadIsProtected: the activation guard reads host.env |
| +// through the exec-sandbox reader's protected open, on the applier's path |
| +// and the standalone verb's. A plain file is read; no file is no key; a |
| +// symlinked host.env (even to a file without the key) or a FIFO is refused |
| +// at once, without blocking, and the refusal arms the guard. |
| +func TestProxyHostEnvReadIsProtected(t *testing.T) { |
| + plain := t.TempDir() |
| + armProxy(t, plain) |
| + if !(&systemApplier{etcDir: plain}).proxyArmedHere() { |
| + t.Fatal("an applier over an armed host.env is not armed") |
| + } |
| + if (&systemApplier{etcDir: t.TempDir()}).proxyArmedHere() { |
| + t.Fatal("an applier over no host.env is armed") |
| + } |
| + unarmed := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(unarmed, "carlos"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(unarmed, "carlos", "host.env"), []byte("CARLOS_REGION=ie\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + if (&systemApplier{etcDir: unarmed}).proxyArmedHere() { |
| + t.Fatal("an applier over a host.env without the key is armed") |
| + } |
| + |
| + // A symlinked host.env pointing at a file without the key: a plain |
| + // open follows it and reads "unarmed" from another pathname. |
| + link := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(link, "carlos"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.Symlink(filepath.Join(unarmed, "carlos", "host.env"), filepath.Join(link, "carlos", "host.env")); err != nil { |
| + t.Fatal(err) |
| + } |
| + // A FIFO: a plain open blocks until a writer appears. |
| + fifo := t.TempDir() |
| + if err := os.MkdirAll(filepath.Join(fifo, "carlos"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + fifoPath := filepath.Join(fifo, "carlos", "host.env") |
| + if err := syscall.Mkfifo(fifoPath, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Whatever happens, never leave a reader blocked on the FIFO. |
| + t.Cleanup(func() { |
| + if w, err := os.OpenFile(fifoPath, os.O_WRONLY|syscall.O_NONBLOCK, 0); err == nil { |
| + w.Close() |
| + } |
| + }) |
| + within := func(what string, f func() bool) bool { |
| + t.Helper() |
| + ch := make(chan bool, 1) |
| + go func() { ch <- f() }() |
| + select { |
| + case v := <-ch: |
| + return v |
| + case <-time.After(3 * time.Second): |
| + t.Fatalf("%s: blocked", what) |
| + return false |
| + } |
| + } |
| + prevRan := false |
| + run := func(context.Context, string, ...string) ([]byte, error) { |
| + prevRan = true |
| + return []byte(proxyFeatureLine), nil |
| + } |
| + for _, tc := range []struct{ name, etc string }{{"symlink", link}, {"fifo", fifo}} { |
| + if !within(tc.name+" applier", func() bool { return (&systemApplier{etcDir: tc.etc}).proxyArmedHere() }) { |
| + t.Fatalf("%s host.env: the applier's guard is not armed", tc.name) |
| + } |
| + hostEnv := filepath.Join(tc.etc, "carlos", "host.env") |
| + if !within(tc.name+" production arming", func() bool { |
| + return proxyGuardArmed(envOf(nil), func() (func(string) string, error) { return sandboxHostEnvironmentAt(hostEnv) }) |
| + }) { |
| + t.Fatalf("%s host.env: the production reader did not arm the guard", tc.name) |
| + } |
| + // The standalone verb, as production wires it: armed, and the |
| + // exec-sandbox rule cannot be read either, so carlos.prev is |
| + // refused without being run. |
| + prev := filepath.Join(t.TempDir(), "carlos.prev") |
| + code := 0 |
| + within(tc.name+" verb", func() bool { |
| + code = proxyAllowsPrevAt(context.Background(), []string{prev}, prev, hostEnv, envOf(nil), run, func(string, ...any) {}) |
| + return true |
| + }) |
| + if code != 1 || prevRan { |
| + t.Fatalf("%s host.env: proxy-allows-prev exit %d, ran carlos.prev %v; want 1, never run", tc.name, code, prevRan) |
| + } |
| + } |
| +} |
| + |
| +// TestProxyAllowsPrevChecksSandboxFirst: the standalone verb, wired as |
| +// RunSystemProxyAllowsPrev wires it, on an armed box whose exec-sandbox |
| +// rule refuses carlos.prev (gVisor, a predecessor below the protocol), |
| +// exits 1 without running it. The same predecessor under systemd is asked |
| +// for the feature; an unarmed box runs nothing. |
| +func TestProxyAllowsPrevChecksSandboxFirst(t *testing.T) { |
| + prev := filepath.Join(t.TempDir(), "carlos.prev") |
| + if err := os.WriteFile(prev, []byte("#!/bin/sh\necho carlos v1\n"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, tc := range []struct { |
| + name, hostEnv string |
| + want int |
| + ran bool |
| + }{ |
| + {"armed, gvisor refuses prev", "CARLOS_INGRESS_PROXY_SOURCES=10.0.1.5\nCARLOS_EXEC_SANDBOX=gvisor\n", 1, false}, |
| + {"armed, systemd, feature", "CARLOS_INGRESS_PROXY_SOURCES=10.0.1.5\nCARLOS_EXEC_SANDBOX=systemd\n", 0, true}, |
| + {"unarmed, gvisor", "CARLOS_EXEC_SANDBOX=gvisor\n", 0, false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + hostEnv := filepath.Join(t.TempDir(), "host.env") |
| + if err := os.WriteFile(hostEnv, []byte(tc.hostEnv), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + ran := false |
| + run := func(_ context.Context, binary string, args ...string) ([]byte, error) { |
| + ran = true |
| + return []byte(proxyFeatureLine), nil |
| + } |
| + var logged []string |
| + logf := func(format string, args ...any) { logged = append(logged, fmt.Sprintf(format, args...)) } |
| + if code := proxyAllowsPrevAt(context.Background(), []string{prev}, prev, hostEnv, envOf(nil), run, logf); code != tc.want || ran != tc.ran { |
| + t.Fatalf("exit %d, ran %v; want %d, %v (logged %q)", code, ran, tc.want, tc.ran, logged) |
| + } |
| + if tc.want == 1 && (len(logged) != 1 || !strings.Contains(logged[0], "exec-sandbox floor") || !strings.Contains(logged[0], "not running it")) { |
| + t.Fatalf("logged %q", logged) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/proxyfeature_test.go b/internal/host/proxyfeature_test.go| index de555a5fc..0863d1e83 100644 |
| --- a/internal/host/proxyfeature_test.go |
| +++ b/internal/host/proxyfeature_test.go |
| @@ -125,22 +125,8 @@ func TestProxyGuardArmed(t *testing.T) { |
| } |
| }) |
| } |
| - dir := t.TempDir() |
| - if getenv, err := readProxyHostEnv(filepath.Join(dir, "absent")); err != nil || getenv("CARLOS_INGRESS_PROXY_SOURCES") != "" { |
| - t.Fatalf("a missing host.env: %v", err) |
| - } |
| - armProxy(t, dir) |
| - getenv, err := readProxyHostEnv(filepath.Join(dir, "carlos", "host.env")) |
| - if err != nil || getenv("CARLOS_INGRESS_PROXY_SOURCES") != "10.0.1.5,10.0.2.6" { |
| - t.Fatalf("host.env read: %v", err) |
| - } |
| - a := &systemApplier{etcDir: dir} |
| - if !a.proxyArmedHere() { |
| - t.Fatal("an applier over an armed host.env is not armed") |
| - } |
| - if (&systemApplier{etcDir: t.TempDir()}).proxyArmedHere() { |
| - t.Fatal("an applier over no host.env is armed") |
| - } |
| + // The applier's own host.env read is TestProxyHostEnvReadIsProtected |
| + // (linux: the protected open is linux-only). |
| } |
| // TestStageRefusesBinaryWithoutFeature: on an armed box, apply refuses a |
| @@ -443,7 +429,13 @@ func TestProxyAllowsPrevVerb(t *testing.T) { |
| } |
| var logged []string |
| logf := func(format string, args ...any) { logged = append(logged, fmt.Sprintf(format, args...)) } |
| - if got := proxyAllowsPrev(context.Background(), tc.args, prev, func() bool { return tc.armed }, run, logf); got != tc.want { |
| + sandbox := func(path string) error { |
| + if path != prev { |
| + t.Fatalf("sandbox asked about %s", path) |
| + } |
| + return nil |
| + } |
| + if got := proxyAllowsPrev(context.Background(), tc.args, prev, func() bool { return tc.armed }, sandbox, run, logf); got != tc.want { |
| t.Fatalf("exit %d, want %d", got, tc.want) |
| } |
| if ran != tc.ran { |
diff --git a/internal/proxyproto/conn.go b/internal/proxyproto/conn.go| index 22dcd8d39..85f70a1eb 100644 |
| --- a/internal/proxyproto/conn.go |
| +++ b/internal/proxyproto/conn.go |
| @@ -141,6 +141,19 @@ func (c *Conn) Read(p []byte) (int, error) { |
| func (c *Conn) Write(p []byte) (int, error) { return c.inner.Write(p) } |
| +// CloseWrite half-closes the inner connection when it can (a *net.TCPConn |
| +// can), so net/http keeps its half-close before closing an early error |
| +// reply to a client still sending. It reads nothing and does not resolve |
| +// the parse. An inner connection without one is an error, left open. |
| +func (c *Conn) CloseWrite() error { |
| + if cw, ok := c.inner.(interface{ CloseWrite() error }); ok { |
| + return cw.CloseWrite() |
| + } |
| + return errNoCloseWrite |
| +} |
| + |
| +var errNoCloseWrite = errors.New("proxyproto: the connection has no CloseWrite") |
| + |
| func (c *Conn) LocalAddr() net.Addr { return c.inner.LocalAddr() } |
| // Close closes the connection without waiting for a pending parse: closing |
diff --git a/internal/proxyproto/listener_test.go b/internal/proxyproto/listener_test.go| index 766810bfc..bbe243cef 100644 |
| --- a/internal/proxyproto/listener_test.go |
| +++ b/internal/proxyproto/listener_test.go |
| @@ -701,3 +701,63 @@ func TestTrustedIPv4MappedPeer(t *testing.T) { |
| }) |
| } |
| } |
| + |
| +// closeWriter is the interface net/http asserts on its connection before |
| +// it half-closes an early error reply (net/http's closeWriteAndWait). |
| +type closeWriter interface{ CloseWrite() error } |
| + |
| +// A *Conn keeps the inner TCP connection's half-close: CloseWrite ends the |
| +// server's writes (the client reads EOF) while the client can still send, |
| +// trusted or not. Over a connection without one it is an error, not a |
| +// full close. |
| +func TestConnCloseWrite(t *testing.T) { |
| + for _, trusted := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("trusted=%v", trusted), func(t *testing.T) { |
| + cfg := Config{} |
| + if trusted { |
| + cfg.Trusted = loopback |
| + } |
| + l := listen(t, cfg) |
| + client, server := pair(t, l) |
| + if trusted { |
| + write(t, client, proxyHeader("203.0.113.7:51000")) |
| + if s := stateWithin(t, server, time.Second); s != StateProxied { |
| + t.Fatalf("State = %v, want proxied", s) |
| + } |
| + } |
| + var c net.Conn = server |
| + cw, ok := c.(closeWriter) |
| + if !ok { |
| + t.Fatal("*Conn has no CloseWrite: net/http cannot half-close an armed listener's connection") |
| + } |
| + write(t, server, []byte("bye")) |
| + if err := cw.CloseWrite(); err != nil { |
| + t.Fatalf("CloseWrite: %v", err) |
| + } |
| + readExactly(t, client, []byte("bye")) |
| + client.SetReadDeadline(time.Now().Add(time.Second)) |
| + if n, err := client.Read(make([]byte, 1)); n != 0 || err != io.EOF { |
| + t.Fatalf("client read after CloseWrite = %d, %v; want EOF", n, err) |
| + } |
| + // The read side is still open: the client's bytes arrive. |
| + write(t, client, []byte("still here")) |
| + readExactly(t, server, []byte("still here")) |
| + }) |
| + } |
| + // An inner connection without a half-close: an error, and the |
| + // connection is not closed. |
| + a, b := net.Pipe() |
| + t.Cleanup(func() { a.Close(); b.Close() }) |
| + var pc net.Conn = &Conn{inner: a} |
| + cw, ok := pc.(closeWriter) |
| + if !ok { |
| + t.Fatal("*Conn has no CloseWrite") |
| + } |
| + if err := cw.CloseWrite(); err == nil { |
| + t.Fatal("CloseWrite over a net.Pipe returned nil") |
| + } |
| + go func() { _, _ = b.Write([]byte("x")) }() |
| + if _, err := io.ReadFull(a, make([]byte, 1)); err != nil { |
| + t.Fatalf("the pipe was closed by CloseWrite: %v", err) |
| + } |
| +} |