carlos / platform Public

host: trust barrier verbs and the trust-violation metric

Root verbs carlos system edge trust-barrier|trust-resume|trust-status
reach the in-process edge through the drain-call child and new
/v1/edge/ routes on the agent's drain socket, served also on boxes
armed for PROXY protocol (proxySourcesSet). A barrier raised but not
persisted is reported as up with persisted:false and fails the verb.
memwatch publishes IngressProxyTrustViolations (no_client_refused +
marker_trusted increase) with Deployment/Region on armed boxes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c6113bd82488d5964c4651688f17273fc0225f2d parent 45bfd14
9 files changed, +1,031 −14
  • internal/host/agent.go +12 −5
  • internal/host/edgetrust.go +395 −0
  • internal/host/edgetrust_linux_test.go +87 −0
  • internal/host/edgetrust_test.go +442 −0
  • internal/host/hadrain_call.go +16 −6
  • internal/host/hadrain_socket.go +19 −2
  • internal/host/memwatch.go +26 −1
  • system.go +22 −0
  • testdata/clireg-golden.jsonl +12 −0
diff --git a/internal/host/agent.go b/internal/host/agent.go
index cffde18c8..01dbac446 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -203,6 +203,7 @@ import (
"github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/proxyproto"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/replicas"
@@ -1084,7 +1085,12 @@ func runAgent(args []string, buildClaims ClaimFactory) {
go statusLoop(reg, svc, collectBuildStates, egressStatus, boxJudge, func() bool { return demoEdge.Load().DemoMovedReady() })
// The memory early-warning (memory-pressure spec §2.4): per box, gated
// by CARLOS_HOST_METRICS — one log line and nothing else where unset.
- go memwatchLoop()
+ go memwatchLoop(func() (proxyproto.Counters, bool) {
+ if e := demoEdge.Load(); e != nil {
+ return e.ProxyCounters()
+ }
+ return proxyproto.Counters{}, false
+ })
go domainsLoop(reg, peekAcmeCache(args), claims.Writes.Enabled)
go instancesLoop(reg, claims.Writes, bs, boxJudge, claims.Providers.Provision)
// The deployment-global election, armed BEFORE the loops it gates so a
@@ -1255,7 +1261,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
// The agent-user-only drain socket's routes (hadrain_socket.go):
// the group drain's, set below on a group member, and the ingress
// drain's.
- driver := &haDrainSocket{ingress: ingress}
+ driver := &haDrainSocket{ingress: ingress, edge: e}
e.SetHAIngressLookup(boxHAIngress.lookup)
armedGroupReaders.Store(&groupReaderSource{snapshot: e.GroupReaderSnapshot})
// Read the current hub view on each private socket request.
@@ -1294,10 +1300,11 @@ func runAgent(args []string, buildClaims ClaimFactory) {
armDutyView(dutyView(e, boxLifetimes), setDutyView, groupReferenced(os.Getenv), func(view dutyViewFunc) {
go verifyAssignLoop(agentCtx, reg.List, view, dd, log.Printf)
})
- // The drain socket: on a group member for its drain verbs, and on a
+ // The drain socket: on a group member for its drain verbs, on a
// fixed box whose ingress drain is configured, for the drain unit
- // and the root verbs (W6 §5.2).
- if driver.group != nil || ingressDrainServed(os.Getenv, admission) {
+ // and the root verbs (W6 §5.2), and on a box armed for PROXY
+ // protocol, for the trust barrier verbs (edge PPv2 §4.7).
+ if drainSocketServed(driver.group != nil, os.Getenv, admission) {
healthWG.Add(1)
go func() {
defer healthWG.Done()
diff --git a/internal/host/edgetrust.go b/internal/host/edgetrust.go
new file mode 100644
index 000000000..82bc1046c
--- /dev/null
+++ b/internal/host/edgetrust.go
@@ -0,0 +1,395 @@
+package host
+
+// The edge's trust barrier, reached from root (edge PPv2 spec §4.7), and
+// the trust-violation metric (§4.5).
+//
+// The agent runs the edge in-process, so the agent's drain socket
+// (hadrain_socket.go) carries three routes to it:
+//
+// POST /v1/edge/trust-barrier raise the barrier; {"barrier":true,"closed":N}
+// (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"}
+//
+// An edge not armed for PROXY protocol answers {"armed":false,...} on each.
+// The root verbs `carlos system edge trust-barrier|trust-resume|trust-status`
+// reach them the way the drain verbs do: a child that drops to the agent's
+// user and makes the call (hadrain_call.go). Root prints the answer and
+// acts on nothing else.
+//
+// The metric is the per-minute increase of no_client_refused plus
+// marker_trusted, published by memwatch on every armed box with
+// CARLOS_HOST_METRICS=cloudwatch, fixed boxes and group members alike.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hostenv"
+ "github.com/carlosframework/platform/internal/proxyproto"
+)
+
+// trustEdge is what the socket's routes need of the edge: *edge.Edge.
+type trustEdge interface {
+ RaiseTrustBarrier() (closed int, err error)
+ ResumeTrust() error
+ TrustBarrierUp() bool
+ ProxyCounters() (proxyproto.Counters, bool)
+}
+
+// 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.
+func proxySourcesSet(getenv func(string) string) bool {
+ addrs, err := hostenv.ParseProxySources(getenv("CARLOS_INGRESS_PROXY_SOURCES"))
+ return err == nil && len(addrs) > 0
+}
+
+// drainSocketServed is whether the agent serves its drain socket: on a
+// group member for its drain verbs, on a fixed box whose ingress drain is
+// configured (W6 §5.2), and on a box armed for PROXY protocol, for the
+// trust barrier verbs.
+func drainSocketServed(groupMember bool, getenv func(string) string, admission *fixedAdmission) bool {
+ return groupMember || ingressDrainServed(getenv, admission) || proxySourcesSet(getenv)
+}
+
+// trustCounters is proxyproto.Counters without the per-node map, under the
+// names the journal line uses (spec §4.5).
+type trustCounters struct {
+ Proxied uint64 `json:"proxied"`
+ NoClient uint64 `json:"no_client"`
+ NoClientRefused uint64 `json:"no_client_refused"`
+ Ignored uint64 `json:"ignored"`
+ IgnoredPrivate uint64 `json:"ignored_private"`
+ MarkerTrusted uint64 `json:"marker_trusted"`
+ Malformed uint64 `json:"malformed"`
+ Timeout uint64 `json:"timeout"`
+}
+
+// trustStatus is GET /v1/edge/trust and trust-status's line.
+type trustStatus struct {
+ Armed bool `json:"armed"`
+ Barrier bool `json:"barrier"`
+ Counters trustCounters `json:"counters"`
+ ProxiedByNode map[string]uint64 `json:"proxied_by_node"`
+}
+
+// trustResult is any of the three routes' answers, as the drain call child
+// carries it to root (drainCallResult.Trust). Armed is absent from an armed
+// edge's barrier and resume answers. Persisted (false) and Error are set
+// only on a barrier the edge raised but could not write to its file: up in
+// the running edge, down after a restart.
+type trustResult struct {
+ Armed *bool `json:"armed,omitempty"`
+ Barrier bool `json:"barrier"`
+ Closed *int `json:"closed,omitempty"`
+ Persisted *bool `json:"persisted,omitempty"`
+ Error string `json:"error,omitempty"`
+ Counters *trustCounters `json:"counters,omitempty"`
+ ProxiedByNode map[string]uint64 `json:"proxied_by_node,omitempty"`
+}
+
+func barrierWord(up bool) string {
+ if up {
+ return "up"
+ }
+ return "down"
+}
+
+// trustNotArmed is the barrier and resume answer of an edge not armed.
+func trustNotArmed() trustResult {
+ armed := false
+ return trustResult{Armed: &armed}
+}
+
+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)),
+ }
+ for a, n := range c.ProxiedByNode {
+ s.ProxiedByNode[a.String()] = n
+ }
+ return s
+}
+
+// edgeTrustHandler is the socket's /v1/edge/ surface over e.
+func edgeTrustHandler(e trustEdge) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.RawQuery != "" || r.URL.ForceQuery {
+ http.NotFound(w, r)
+ return
+ }
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/v1/edge/trust":
+ _ = json.NewEncoder(w).Encode(trustStatusOf(e))
+ case r.Method == http.MethodPost && r.URL.Path == "/v1/edge/trust-barrier":
+ closed, err := e.RaiseTrustBarrier()
+ switch {
+ case errors.Is(err, edge.ErrProxyProtocolOff):
+ _ = json.NewEncoder(w).Encode(trustNotArmed())
+ case errors.Is(err, edge.ErrBarrierNotPersisted):
+ // The edge raised the flag and swept all the same: the
+ // barrier is up, and the answer says it, with why a
+ // restart would lower it. The verb fails on it.
+ log.Printf("agent: edge trust barrier raised by the root verb, NOT persisted; %d trusted connections closed: %v", closed, err)
+ persisted := false
+ _ = json.NewEncoder(w).Encode(trustResult{Barrier: true, Closed: &closed, Persisted: &persisted, Error: err.Error()})
+ case err != nil:
+ // Whether the flag went up despite the error is the edge's
+ // to say; report it with the error rather than guess.
+ msg := fmt.Sprintf("%v (barrier %s in the running edge, %d trusted connections closed)", err, barrierWord(e.TrustBarrierUp()), closed)
+ log.Printf("agent: edge trust barrier: %s", msg)
+ w.WriteHeader(http.StatusInternalServerError)
+ _ = json.NewEncoder(w).Encode(drainError{Error: msg})
+ default:
+ log.Printf("agent: edge trust barrier raised by the root verb; %d trusted connections closed", closed)
+ _ = json.NewEncoder(w).Encode(trustResult{Barrier: true, Closed: &closed})
+ }
+ case r.Method == http.MethodPost && r.URL.Path == "/v1/edge/trust-resume":
+ err := e.ResumeTrust()
+ switch {
+ case errors.Is(err, edge.ErrProxyProtocolOff):
+ _ = json.NewEncoder(w).Encode(trustNotArmed())
+ case err != nil:
+ msg := fmt.Sprintf("%v (barrier %s in the running edge)", err, barrierWord(e.TrustBarrierUp()))
+ log.Printf("agent: edge trust barrier: %s", msg)
+ w.WriteHeader(http.StatusInternalServerError)
+ _ = json.NewEncoder(w).Encode(drainError{Error: msg})
+ default:
+ log.Print("agent: edge trust barrier lowered by the root verb")
+ _ = json.NewEncoder(w).Encode(trustResult{Barrier: false})
+ }
+ default:
+ http.NotFound(w, r)
+ }
+ })
+}
+
+// edgeTrustCallBound bounds one trust verb's call: the agent writes a file
+// and closes connections, which takes well under this.
+const edgeTrustCallBound = time.Minute
+
+// edgeTrustVerb is whether verb is one of the trust verbs, which are also
+// the drain call child's ops for them.
+func edgeTrustVerb(verb string) bool {
+ return verb == "trust-barrier" || verb == "trust-resume" || verb == "trust-status"
+}
+
+// trust asks the agent's edge for one trust op.
+func (c *drainClient) trust(ctx context.Context, op string) (*trustResult, error) {
+ method, path := http.MethodPost, "/v1/edge/"+op
+ if op == "trust-status" {
+ method, path = http.MethodGet, "/v1/edge/trust"
+ }
+ var r trustResult
+ if err := c.call(ctx, method, path, nil, &r); err != nil {
+ return nil, err
+ }
+ return &r, nil
+}
+
+const edgeTrustHelp = `Usage: carlos system edge {trust-barrier|trust-resume|trust-status}
+Root only, on a box whose edge reads PROXY protocol from its load balancer.
+ trust-barrier Raise the trust barrier: no load balancer header grants a
+ client address until trust-resume, across restarts. Close
+ every open connection from a load balancer node.
+ trust-resume Lower the trust barrier.
+ trust-status Print whether the edge is armed, the barrier, and the
+ PROXY protocol counters since the edge started.
+Each prints one JSON line.
+Exit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or
+a box not armed for PROXY protocol.
+`
+
+// errEdgeNotArmed is the verbs' answer on a box not armed for PROXY
+// protocol (exit 2).
+var errEdgeNotArmed = errors.New("this box is not armed for PROXY protocol")
+
+// edgeTrustCommand is the root verbs; zero fields are never used.
+type edgeTrustCommand struct {
+ euid func() int
+ call drainCaller
+ // hostEnv reads /etc/carlos/host.env, to tell a box with no socket
+ // because it is not armed from one whose agent is down.
+ hostEnv func() (func(string) string, error)
+}
+
+// RunSystemEdge is `carlos system edge <verb>`, args starting at the verb.
+// It returns the exit code.
+func RunSystemEdge(args []string, out, stderr io.Writer) int {
+ cmd := edgeTrustCommand{euid: os.Geteuid, call: execDrainCall, hostEnv: sandboxHostEnvironment}
+ return cmd.run(context.Background(), args, out, stderr)
+}
+
+func (cmd edgeTrustCommand) run(ctx context.Context, args []string, out, stderr io.Writer) int {
+ if len(args) == 1 && (args[0] == "help" || args[0] == "-h" || args[0] == "--help") {
+ if _, err := io.WriteString(out, edgeTrustHelp); err != nil {
+ return 1
+ }
+ return 0
+ }
+ if len(args) != 1 || !edgeTrustVerb(args[0]) {
+ fmt.Fprint(stderr, edgeTrustHelp)
+ return 2
+ }
+ verb := args[0]
+ fail := func(code int, msg string) int {
+ fmt.Fprintf(stderr, "edge: %s\n", msg)
+ return code
+ }
+ if cmd.euid() != 0 {
+ return fail(1, "root required")
+ }
+ ctx, cancel := context.WithTimeout(ctx, edgeTrustCallBound+5*time.Second)
+ defer cancel()
+ r, err := cmd.call(ctx, verb, "", nil)
+ switch {
+ case err != nil:
+ return fail(1, oneLine(err.Error()))
+ case r.AgentDown:
+ // No socket: an agent that is down, or one that serves none
+ // because nothing arms it. Only host.env tells which.
+ if getenv, err := cmd.hostEnv(); err == nil && !proxySourcesSet(getenv) {
+ return fail(2, errEdgeNotArmed.Error())
+ }
+ return fail(1, errDrainAgentDown.Error())
+ case r.NoRoute:
+ return fail(1, "the agent has no trust barrier (an older release)")
+ case r.Error != "":
+ return fail(1, oneLine(r.Error))
+ }
+ t := r.Trust
+ if t == nil {
+ return fail(1, "the agent answered nothing usable")
+ }
+ var line any
+ switch {
+ case t.Armed != nil && !*t.Armed:
+ if verb == "trust-status" {
+ if err := json.NewEncoder(out).Encode(trustStatusLine(t)); err != nil {
+ return 1
+ }
+ }
+ return fail(2, errEdgeNotArmed.Error())
+ case verb == "trust-status" && t.Armed != nil && t.Counters != nil:
+ line = trustStatusLine(t)
+ case verb == "trust-barrier" && t.Armed == nil && t.Barrier && t.Closed != nil && t.Persisted != nil && !*t.Persisted && t.Error != "":
+ // Up in the running edge, not on disk: print it as it is and fail,
+ // so the operator sees the barrier is up and will not survive a
+ // restart.
+ if err := json.NewEncoder(out).Encode(trustResult{Barrier: true, Closed: t.Closed, Persisted: t.Persisted, Error: t.Error}); err != nil {
+ return 1
+ }
+ return fail(1, "the trust barrier is up in the running edge but not persisted, so a restart would come up without it: "+oneLine(t.Error))
+ case verb == "trust-barrier" && t.Armed == nil && t.Barrier && t.Closed != nil && t.Persisted == nil && t.Error == "":
+ line = trustResult{Barrier: true, Closed: t.Closed}
+ case verb == "trust-resume" && t.Armed == nil && !t.Barrier && t.Closed == nil && t.Persisted == nil && t.Error == "":
+ line = trustResult{Barrier: false}
+ default:
+ return fail(1, "the agent answered nothing usable")
+ }
+ if err := json.NewEncoder(out).Encode(line); err != nil {
+ return 1
+ }
+ return 0
+}
+
+// trustStatusLine is a status answer as trust-status prints it: every
+// field present, proxied_by_node an object even when empty.
+func trustStatusLine(t *trustResult) trustStatus {
+ s := trustStatus{Armed: t.Armed != nil && *t.Armed, Barrier: t.Barrier, ProxiedByNode: map[string]uint64{}}
+ if t.Counters != nil {
+ s.Counters = *t.Counters
+ }
+ for a, n := range t.ProxiedByNode {
+ s.ProxiedByNode[a] = n
+ }
+ return s
+}
+
+// trustMetric is memwatch's trust-violation datum on an armed box.
+type trustMetric struct {
+ dims []types.Dimension
+ counters func() (proxyproto.Counters, bool)
+ // sent is the violation sum the last successful put covered. The edge
+ // counts from its start, in this process, so it starts at zero.
+ sent uint64
+}
+
+// trustMetricDimensions are the admission metrics' dimensions
+// (admissionMetricData), which the ingress alarm reads.
+func trustMetricDimensions(deployment, region string) []types.Dimension {
+ return []types.Dimension{
+ {Name: aws.String("Deployment"), Value: aws.String(deployment)},
+ {Name: aws.String("Region"), Value: aws.String(region)},
+ }
+}
+
+// trustMetricFromEnv is the metric on a box armed for PROXY protocol with a
+// deployment bucket and region configuration, fixed box or group member,
+// whatever CARLOS_GROUP_ADMISSION says; nil otherwise. counters reads the
+// running edge's (false until it runs, or when it is not armed).
+func trustMetricFromEnv(getenv func(string) string, readRegion func(string, string) (roleRegionConfig, error), counters func() (proxyproto.Counters, bool)) *trustMetric {
+ if !proxySourcesSet(getenv) {
+ return nil
+ }
+ deployment := strings.TrimSpace(getenv("CARLOS_DEPLOYMENT_BUCKET"))
+ region, err := readRegion(roleRegionConfigPath, strings.TrimSpace(getenv("CARLOS_REGION")))
+ if deployment == "" || err != nil || region.RegionCode == "" {
+ return nil
+ }
+ return &trustMetric{dims: trustMetricDimensions(deployment, region.RegionCode), counters: counters}
+}
+
+// pending is the datum for the violations since the last successful put,
+// and the sum to record once this one succeeds; ok is false when there is
+// nothing to publish (no increase, or no armed edge).
+func (m *trustMetric) pending(now time.Time) (d types.MetricDatum, sum uint64, ok bool) {
+ c, armed := m.counters()
+ if !armed {
+ return types.MetricDatum{}, 0, false
+ }
+ sum = c.NoClientRefused + c.MarkerTrusted
+ if sum < m.sent {
+ // A new edge counting from zero.
+ m.sent = 0
+ }
+ if sum == m.sent {
+ return types.MetricDatum{}, sum, false
+ }
+ return trustViolationDatum(m.dims, sum-m.sent, now), sum, true
+}
+
+// trustViolationDatum is IngressProxyTrustViolations: delta violations
+// (no_client_refused plus marker_trusted) in the minute.
+func trustViolationDatum(dims []types.Dimension, delta uint64, now time.Time) types.MetricDatum {
+ return types.MetricDatum{
+ MetricName: aws.String("IngressProxyTrustViolations"),
+ Dimensions: dims,
+ Timestamp: aws.Time(now),
+ Unit: types.StandardUnitCount,
+ Value: aws.Float64(float64(delta)),
+ }
+}
diff --git a/internal/host/edgetrust_linux_test.go b/internal/host/edgetrust_linux_test.go
new file mode 100644
index 000000000..e5b23c90a
--- /dev/null
+++ b/internal/host/edgetrust_linux_test.go
@@ -0,0 +1,87 @@
+//go:build linux
+
+package host
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+// TestEdgeTrustVerbsOverTheSocket: the root verbs through the real drain
+// call child, which dials the agent's socket served with an edge, end to
+// end: raise, status with the barrier up, resume; a socket nobody serves
+// is agent_down.
+func TestEdgeTrustVerbsOverTheSocket(t *testing.T) {
+ f := &fakeTrustEdge{armed: true, closed: 2, counters: trustCountersFixture()}
+ dir, err := os.MkdirTemp("", "et")
+ must(t, err)
+ t.Cleanup(func() { os.RemoveAll(dir) })
+ path := filepath.Join(dir, "s", "drain.sock")
+ setDrainPeer(t, func(uint32) bool { return true })
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() { defer close(done); serveHADrainSocket(ctx, path, &haDrainSocket{edge: f}) }()
+ t.Cleanup(func() { cancel(); <-done })
+ waitSocket(t, path)
+
+ child := func(sock string) drainCaller {
+ return func(ctx context.Context, op, txn string, peers []string) (drainCallResult, error) {
+ c, err := drainCallExec(op, txn, peers)
+ if err != nil {
+ return drainCallResult{}, err
+ }
+ c.Env = []string{"HADRAIN_CALL_TEST_SOCKET=" + sock}
+ return runDrainCallChild(ctx, c)
+ }
+ }
+ verb := func(call drainCaller, args ...string) (int, string, string) {
+ cmd := edgeTrustCommand{euid: func() int { return 0 }, call: call,
+ hostEnv: func() (func(string) string, error) {
+ return func(k string) string {
+ if k == "CARLOS_INGRESS_PROXY_SOURCES" {
+ return "172.31.29.110"
+ }
+ return ""
+ }, nil
+ }}
+ var out, errOut bytes.Buffer
+ code := cmd.run(context.Background(), args, &out, &errOut)
+ return code, out.String(), errOut.String()
+ }
+ if code, out, errOut := verb(child(path), "trust-barrier"); code != 0 || out != `{"barrier":true,"closed":2}`+"\n" || errOut != "" {
+ t.Fatalf("barrier: %d %q %q", code, out, errOut)
+ }
+ want := strings.Replace(trustStatusFixtureJSON, `"barrier":false`, `"barrier":true`, 1) + "\n"
+ if code, out, errOut := verb(child(path), "trust-status"); code != 0 || out != want || errOut != "" {
+ t.Fatalf("status: %d %q %q", code, out, errOut)
+ }
+ if code, out, errOut := verb(socketDrainCall(newDrainClient(path)), "trust-resume"); code != 0 || out != `{"barrier":false}`+"\n" || errOut != "" {
+ t.Fatalf("resume: %d %q %q", code, out, errOut)
+ }
+ if f.TrustBarrierUp() {
+ t.Fatal("the barrier is still up after the resume")
+ }
+ // Raised but not persisted: the line says so, and the verb fails.
+ f.mu.Lock()
+ f.raiseErr, f.raiseUp = fmt.Errorf("%w: %w", edge.ErrBarrierNotPersisted, errors.New("read-only file system")), true
+ f.mu.Unlock()
+ if code, out, errOut := verb(child(path), "trust-barrier"); code != 1 ||
+ out != `{"barrier":true,"closed":2,"persisted":false,"error":"edge: trust barrier raised in the running edge, not persisted: read-only file system"}`+"\n" ||
+ !strings.HasPrefix(errOut, "edge: the trust barrier is up in the running edge but not persisted") {
+ t.Fatalf("unpersisted barrier: %d %q %q", code, out, errOut)
+ }
+ if !f.TrustBarrierUp() {
+ t.Fatal("the barrier is down after an unpersisted raise")
+ }
+ if code, _, errOut := verb(child(filepath.Join(dir, "s", "none.sock")), "trust-status"); code != 1 || errOut != "edge: the agent's drain socket is not answering\n" {
+ t.Fatalf("no agent: %d %q", code, errOut)
+ }
+}
diff --git a/internal/host/edgetrust_test.go b/internal/host/edgetrust_test.go
new file mode 100644
index 000000000..4cfc56041
--- /dev/null
+++ b/internal/host/edgetrust_test.go
@@ -0,0 +1,442 @@
+package host
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/netip"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch"
+ "github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/proxyproto"
+)
+
+// fakeTrustEdge stands in for *edge.Edge behind the socket and the metric.
+type fakeTrustEdge struct {
+ mu sync.Mutex
+ armed bool
+ barrier bool
+ closed int
+ raiseErr error
+ // raiseUp: a raise that fails still raises (an unpersisted barrier).
+ raiseUp bool
+ counters proxyproto.Counters
+ raised int
+ resumed int
+}
+
+func (f *fakeTrustEdge) RaiseTrustBarrier() (int, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if !f.armed {
+ return 0, edge.ErrProxyProtocolOff
+ }
+ if f.raiseErr != nil {
+ if f.raiseUp {
+ f.raised++
+ f.barrier = true
+ return f.closed, f.raiseErr
+ }
+ return 0, f.raiseErr
+ }
+ f.raised++
+ f.barrier = true
+ return f.closed, nil
+}
+
+func (f *fakeTrustEdge) ResumeTrust() error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if !f.armed {
+ return edge.ErrProxyProtocolOff
+ }
+ f.resumed++
+ f.barrier = false
+ return nil
+}
+
+func (f *fakeTrustEdge) TrustBarrierUp() bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.armed && f.barrier
+}
+
+func (f *fakeTrustEdge) ProxyCounters() (proxyproto.Counters, bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if !f.armed {
+ return proxyproto.Counters{}, false
+ }
+ c := f.counters
+ c.ProxiedByNode = map[netip.Addr]uint64{}
+ for a, n := range f.counters.ProxiedByNode {
+ c.ProxiedByNode[a] = n
+ }
+ return c, true
+}
+
+func (f *fakeTrustEdge) setCounters(c proxyproto.Counters) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.counters = 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 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}}`
+
+func serveTrust(t *testing.T, h http.Handler, method, target string) (int, string) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest(method, target, nil))
+ return rec.Code, strings.TrimSpace(rec.Body.String())
+}
+
+// TestEdgeTrustRoutes: the three /v1/edge/ routes on the drain socket
+// answer the barrier, the resume and the status, an unarmed edge answers
+// armed false, and a query string or another method is 404.
+func TestEdgeTrustRoutes(t *testing.T) {
+ f := &fakeTrustEdge{armed: true, closed: 3, counters: trustCountersFixture()}
+ h := (&haDrainSocket{edge: f}).handler()
+
+ if code, body := serveTrust(t, h, http.MethodGet, "/v1/edge/trust"); code != 200 || body != trustStatusFixtureJSON {
+ t.Fatalf("status: %d %s", code, body)
+ }
+ if code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-barrier"); code != 200 || body != `{"barrier":true,"closed":3}` {
+ t.Fatalf("barrier: %d %s", code, body)
+ }
+ if code, body := serveTrust(t, h, http.MethodGet, "/v1/edge/trust"); code != 200 || !strings.Contains(body, `"barrier":true`) {
+ t.Fatalf("status after the barrier: %d %s", code, body)
+ }
+ if code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-resume"); code != 200 || body != `{"barrier":false}` {
+ t.Fatalf("resume: %d %s", code, body)
+ }
+ for _, tc := range []struct{ method, target string }{
+ {http.MethodGet, "/v1/edge/trust?x=1"},
+ {http.MethodPost, "/v1/edge/trust-barrier?x=1"},
+ {http.MethodPost, "/v1/edge/trust-resume?"},
+ {http.MethodGet, "/v1/edge/trust-barrier"},
+ {http.MethodPost, "/v1/edge/trust"},
+ {http.MethodPost, "/v1/edge/close-trusted"},
+ } {
+ if code, _ := serveTrust(t, h, tc.method, tc.target); code != http.StatusNotFound {
+ t.Fatalf("%s %s: %d, want 404", tc.method, tc.target, code)
+ }
+ }
+ if f.raised != 1 || f.resumed != 1 {
+ t.Fatalf("raised %d resumed %d after the refused requests", f.raised, f.resumed)
+ }
+
+ // A barrier raised in the running edge but not persisted is up, and
+ // says so: never "nothing happened".
+ f.raiseErr = fmt.Errorf("%w: %w", edge.ErrBarrierNotPersisted, errors.New("disk full"))
+ f.raiseUp = true
+ if code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-barrier"); code != 200 ||
+ body != `{"barrier":true,"closed":3,"persisted":false,"error":"edge: trust barrier raised in the running edge, not persisted: disk full"}` {
+ t.Fatalf("unpersisted raise: %d %s", code, body)
+ }
+ // Any other failed raise is the edge's error.
+ f.raiseErr, f.raiseUp = errors.New("edge: something else"), false
+ if code, body := serveTrust(t, h, http.MethodPost, "/v1/edge/trust-barrier"); code != http.StatusInternalServerError || !strings.Contains(body, "something else") {
+ t.Fatalf("failed raise: %d %s", code, body)
+ }
+
+ off := (&haDrainSocket{edge: &fakeTrustEdge{}}).handler()
+ 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":{}}` {
+ t.Fatalf("unarmed status: %d %s", code, body)
+ }
+ for _, p := range []string{"/v1/edge/trust-barrier", "/v1/edge/trust-resume"} {
+ if code, body := serveTrust(t, off, http.MethodPost, p); code != 200 || body != `{"armed":false,"barrier":false}` {
+ t.Fatalf("unarmed %s: %d %s", p, code, body)
+ }
+ }
+
+ // Without an edge the prefix is not served.
+ if code, _ := serveTrust(t, (&haDrainSocket{}).handler(), http.MethodGet, "/v1/edge/trust"); code != http.StatusNotFound {
+ t.Fatalf("no edge: %d, want 404", code)
+ }
+}
+
+// TestDrainSocketServedWhenArmed: a fixed box with only
+// CARLOS_INGRESS_PROXY_SOURCES serves the socket; nothing set, it does not.
+func TestDrainSocketServedWhenArmed(t *testing.T) {
+ env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
+ fixed := &fixedAdmission{}
+ if !drainSocketServed(false, env(map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110,172.31.11.189"}), fixed) {
+ t.Fatal("an armed fixed box does not serve the drain socket")
+ }
+ if drainSocketServed(false, env(nil), fixed) || drainSocketServed(false, env(nil), nil) {
+ t.Fatal("a box with nothing set serves the drain socket")
+ }
+ if drainSocketServed(false, env(map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "8.8.8.8"}), fixed) {
+ t.Fatal("a value the edge refuses arms the socket")
+ }
+ if !drainSocketServed(true, env(nil), nil) {
+ t.Fatal("a group member does not serve the drain socket")
+ }
+ if !proxySourcesSet(env(map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": " 172.31.29.110 "})) || proxySourcesSet(env(map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": " "})) {
+ t.Fatal("proxySourcesSet")
+ }
+}
+
+// TestTrustViolationDatum: name, unit, dimensions and value.
+func TestTrustViolationDatum(t *testing.T) {
+ now := time.Unix(1700000000, 0)
+ dims := trustMetricDimensions("deploy-bucket", "euw1")
+ d := trustViolationDatum(dims, 3, now)
+ if *d.MetricName != "IngressProxyTrustViolations" || d.Unit != types.StandardUnitCount || *d.Value != 3 || !d.Timestamp.Equal(now) {
+ t.Fatalf("datum %+v", d)
+ }
+ if len(d.Dimensions) != 2 || *d.Dimensions[0].Name != "Deployment" || *d.Dimensions[0].Value != "deploy-bucket" ||
+ *d.Dimensions[1].Name != "Region" || *d.Dimensions[1].Value != "euw1" {
+ t.Fatalf("dimensions %+v", d.Dimensions)
+ }
+}
+
+func trustMemwatch(f *fakePutter, counters func() (proxyproto.Counters, bool)) memwatch {
+ return memwatch{
+ put: f,
+ instanceID: "i-0123",
+ mem: func() (*int64, *int64) { tot, av := int64(4000), int64(1000); return &tot, &av },
+ pressure: func() (string, error) { return "", errors.New("no psi") },
+ logf: func(string, ...any) {},
+ trust: &trustMetric{dims: trustMetricDimensions("deploy-bucket", "euw1"), counters: counters},
+ }
+}
+
+func trustData(calls []*cloudwatch.PutMetricDataInput) []types.MetricDatum {
+ var out []types.MetricDatum
+ for _, in := range calls {
+ for _, d := range in.MetricData {
+ if *d.MetricName == "IngressProxyTrustViolations" {
+ out = append(out, d)
+ }
+ }
+ }
+ return out
+}
+
+// TestMemwatchPublishesTrustDelta: two ticks with the violation sum at 0
+// then 5 put one datum, 5; a failed put keeps the increase for the next
+// tick; an unarmed edge puts none.
+func TestMemwatchPublishesTrustDelta(t *testing.T) {
+ f := &fakeTrustEdge{armed: true}
+ put := &fakePutter{}
+ w := trustMemwatch(put, f.ProxyCounters)
+ now := time.Unix(1700000000, 0)
+ w.tick(context.Background(), now)
+ f.setCounters(proxyproto.Counters{NoClientRefused: 2, MarkerTrusted: 3, Proxied: 100})
+ w.tick(context.Background(), now.Add(time.Minute))
+ got := trustData(put.calls)
+ if len(put.calls) != 2 || len(got) != 1 || *got[0].Value != 5 {
+ t.Fatalf("calls %d, trust data %+v", len(put.calls), got)
+ }
+ w.tick(context.Background(), now.Add(2*time.Minute))
+ if got = trustData(put.calls); len(got) != 1 {
+ t.Fatalf("no increase put a datum: %+v", got)
+ }
+
+ // A failed put does not lose the increase.
+ f.setCounters(proxyproto.Counters{NoClientRefused: 4, MarkerTrusted: 3})
+ w.put = &failPutter{err: errors.New("throttled")}
+ w.tick(context.Background(), now.Add(3*time.Minute))
+ f.setCounters(proxyproto.Counters{NoClientRefused: 5, MarkerTrusted: 3})
+ put2 := &fakePutter{}
+ w.put = put2
+ w.tick(context.Background(), now.Add(4*time.Minute))
+ if got = trustData(put2.calls); len(got) != 1 || *got[0].Value != 3 {
+ t.Fatalf("after a failed put: %+v", got)
+ }
+
+ // An unarmed edge, or none yet, puts none.
+ for _, counters := range []func() (proxyproto.Counters, bool){
+ (&fakeTrustEdge{}).ProxyCounters,
+ func() (proxyproto.Counters, bool) { return proxyproto.Counters{}, false },
+ } {
+ put := &fakePutter{}
+ w := trustMemwatch(put, counters)
+ w.tick(context.Background(), now)
+ w.tick(context.Background(), now.Add(time.Minute))
+ if len(put.calls) != 2 || len(trustData(put.calls)) != 0 {
+ t.Fatalf("unarmed: calls %d, trust data %+v", len(put.calls), trustData(put.calls))
+ }
+ }
+}
+
+// TestTrustMetricFromEnv: built on an armed box with a deployment and a
+// region, on fixed boxes and members alike; nil otherwise.
+func TestTrustMetricFromEnv(t *testing.T) {
+ env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
+ region := func(path, placement string) (roleRegionConfig, error) {
+ if path != roleRegionConfigPath || placement != "eu-west-1" {
+ t.Fatalf("region read %q %q", path, placement)
+ }
+ return roleRegionConfig{RegionCode: "euw1"}, nil
+ }
+ none := func() (proxyproto.Counters, bool) { return proxyproto.Counters{}, false }
+ armed := map[string]string{"CARLOS_INGRESS_PROXY_SOURCES": "172.31.29.110", "CARLOS_DEPLOYMENT_BUCKET": "deploy-bucket", "CARLOS_REGION": "eu-west-1"}
+ m := trustMetricFromEnv(env(armed), region, none)
+ if m == nil || *m.dims[0].Value != "deploy-bucket" || *m.dims[1].Value != "euw1" {
+ t.Fatalf("armed: %+v", m)
+ }
+ for _, drop := range []string{"CARLOS_INGRESS_PROXY_SOURCES", "CARLOS_DEPLOYMENT_BUCKET"} {
+ e := map[string]string{}
+ for k, v := range armed {
+ if k != drop {
+ e[k] = v
+ }
+ }
+ if trustMetricFromEnv(env(e), region, none) != nil {
+ t.Fatalf("without %s: built", drop)
+ }
+ }
+ bad := func(string, string) (roleRegionConfig, error) { return roleRegionConfig{}, errors.New("no config") }
+ if trustMetricFromEnv(env(armed), bad, none) != nil {
+ t.Fatal("without region config: built")
+ }
+}
+
+// TestDrainCallTrustRoundTrip: root reads the child's trust answer, whose
+// shape parseDrainCall checks strictly.
+func TestDrainCallTrustRoundTrip(t *testing.T) {
+ armed, closed := true, 2
+ for _, want := range []trustResult{
+ {Barrier: true, Closed: &closed},
+ {Barrier: false},
+ {Barrier: true, Closed: &closed, Persisted: new(bool), Error: "edge: not persisted"},
+ {Armed: &armed, Barrier: true, Counters: &trustCounters{Proxied: 1, MarkerTrusted: 2}, ProxiedByNode: map[string]uint64{"172.31.29.110": 1}},
+ } {
+ b, err := json.Marshal(drainCallResult{V: 1, Trust: &want})
+ if err != nil {
+ t.Fatal(err)
+ }
+ r, err := parseDrainCall(b)
+ if err != nil || r.Trust == nil {
+ t.Fatalf("%s: %+v %v", b, r, err)
+ }
+ got, _ := json.Marshal(r.Trust)
+ exp, _ := json.Marshal(want)
+ if !bytes.Equal(got, exp) {
+ t.Fatalf("round trip %s, want %s", got, exp)
+ }
+ }
+ if _, err := parseDrainCall([]byte(`{"v":1,"trust":{"barrier":true,"other":1}}`)); err == nil {
+ t.Fatal("an unknown trust field was accepted")
+ }
+ for _, op := range []string{"trust-barrier", "trust-resume", "trust-status"} {
+ if !drainCallOp(op) || !drainCallTxnless(op) {
+ t.Fatalf("%s is not a txnless drain call op", op)
+ }
+ if a := drainCallChildArgs(op, "t1", nil); len(a) != 2 || a[0] != op || a[1] != "-" {
+ t.Fatalf("%s child args %q", op, a)
+ }
+ if gotOp, txn, _, err := drainCallArgs([]string{op, "-"}); err != nil || gotOp != op || txn != "" {
+ t.Fatalf("%s args: %q %q %v", op, gotOp, txn, err)
+ }
+ if _, _, _, err := drainCallArgs([]string{op, "t1"}); err == nil {
+ t.Fatalf("%s with a transaction was accepted", op)
+ }
+ }
+}
+
+// TestEdgeTrustVerbAnswers: the root verbs over a caller standing in for
+// the child: the one JSON line each prints, not-armed as exit 2, the
+// agent's failures as exit 1, and arguments and root checked first.
+func TestEdgeTrustVerbAnswers(t *testing.T) {
+ armed, notArmed, closed := true, false, 4
+ status := &trustResult{Armed: &armed, Counters: &trustCounters{}, ProxiedByNode: nil}
+ run := func(r drainCallResult, callErr error, hostEnv string, euid int, args ...string) (int, string, string, []string) {
+ var asked []string
+ cmd := edgeTrustCommand{
+ euid: func() int { return euid },
+ call: func(_ context.Context, op, txn string, peers []string) (drainCallResult, error) {
+ asked = append(asked, op)
+ if txn != "" || peers != nil {
+ t.Fatalf("%s asked with %q %v", op, txn, peers)
+ }
+ return r, callErr
+ },
+ hostEnv: func() (func(string) string, error) {
+ return func(k string) string {
+ if k == "CARLOS_INGRESS_PROXY_SOURCES" {
+ return hostEnv
+ }
+ return ""
+ }, nil
+ },
+ }
+ var out, errOut bytes.Buffer
+ code := cmd.run(context.Background(), args, &out, &errOut)
+ return code, out.String(), errOut.String(), asked
+ }
+ for _, tc := range []struct {
+ name string
+ r drainCallResult
+ callErr error
+ hostEnv string
+ euid int
+ args []string
+ code int
+ out string
+ errOut string
+ }{
+ {"barrier", drainCallResult{V: 1, Trust: &trustResult{Barrier: true, Closed: &closed}}, nil, "", 0, []string{"trust-barrier"}, 0, `{"barrier":true,"closed":4}` + "\n", ""},
+ {"resume", drainCallResult{V: 1, Trust: &trustResult{}}, nil, "", 0, []string{"trust-resume"}, 0, `{"barrier":false}` + "\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: &notArmed, Counters: &trustCounters{}}}, 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",
+ "edge: this box is not armed for PROXY protocol\n"},
+ {"barrier unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: &notArmed}}, nil, "", 0, []string{"trust-barrier"}, 2, "", "edge: this box is not armed for PROXY protocol\n"},
+ {"resume unarmed", drainCallResult{V: 1, Trust: &trustResult{Armed: &notArmed}}, nil, "", 0, []string{"trust-resume"}, 2, "", "edge: this box is not armed for PROXY protocol\n"},
+ {"no socket, host.env unarmed", drainCallResult{V: 1, AgentDown: true, Error: "dial"}, nil, "", 0, []string{"trust-status"}, 2, "", "edge: this box is not armed for PROXY protocol\n"},
+ {"no socket, host.env armed", drainCallResult{V: 1, AgentDown: true, Error: "dial"}, nil, "172.31.29.110", 0, []string{"trust-barrier"}, 1, "", "edge: the agent's drain socket is not answering\n"},
+ {"older agent", drainCallResult{V: 1, NoRoute: true, Error: "404"}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent has no trust barrier (an older release)\n"},
+ {"agent error", drainCallResult{V: 1, Error: "edge: write trust barrier: disk\nfull"}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: edge: write trust barrier: disk full\n"},
+ {"child failed", drainCallResult{}, errors.New("the drain call failed"), "", 0, []string{"trust-barrier"}, 1, "", "edge: the drain call failed\n"},
+ {"no answer", drainCallResult{V: 1}, nil, "", 0, []string{"trust-status"}, 1, "", "edge: the agent answered nothing usable\n"},
+ {"barrier not persisted", drainCallResult{V: 1, Trust: &trustResult{Barrier: true, Closed: &closed, Persisted: &notArmed, Error: "edge: trust barrier raised in the running edge, not persisted: disk\nfull"}}, nil, "", 0, []string{"trust-barrier"}, 1,
+ `{"barrier":true,"closed":4,"persisted":false,"error":"edge: trust barrier raised in the running edge, not persisted: disk\nfull"}` + "\n",
+ "edge: the trust barrier is up in the running edge but not persisted, so a restart would come up without it: edge: trust barrier raised in the running edge, not persisted: disk full\n"},
+ {"persisted on resume", drainCallResult{V: 1, Trust: &trustResult{Persisted: &notArmed, Error: "x"}}, nil, "", 0, []string{"trust-resume"}, 1, "", "edge: the agent answered nothing usable\n"},
+ {"wrong shape", drainCallResult{V: 1, Trust: &trustResult{}}, nil, "", 0, []string{"trust-barrier"}, 1, "", "edge: the agent answered nothing usable\n"},
+ } {
+ code, out, errOut, asked := run(tc.r, tc.callErr, tc.hostEnv, tc.euid, tc.args...)
+ if code != tc.code || out != tc.out || errOut != tc.errOut || len(asked) != 1 || asked[0] != tc.args[0] {
+ t.Errorf("%s: code %d out %q err %q asked %q", tc.name, code, out, errOut, asked)
+ }
+ }
+ // Root first, then arguments; neither asks the agent.
+ if code, out, errOut, asked := run(drainCallResult{}, nil, "", 1000, "trust-barrier"); code != 1 || out != "" || errOut != "edge: root required\n" || asked != nil {
+ t.Errorf("not root: %d %q %q %q", code, out, errOut, asked)
+ }
+ for _, args := range [][]string{nil, {"trust-barrier", "now"}, {"close-trusted"}, {"--force", "trust-barrier"}} {
+ if code, out, errOut, asked := run(drainCallResult{}, nil, "", 0, args...); code != 2 || out != "" || !strings.HasPrefix(errOut, "Usage: carlos system edge") || asked != nil {
+ t.Errorf("%q: %d %q %q %q", args, code, out, errOut, asked)
+ }
+ }
+ for _, h := range []string{"help", "-h", "--help"} {
+ if code, out, errOut, asked := run(drainCallResult{}, nil, "", 1000, h); code != 0 || !strings.HasPrefix(out, "Usage: carlos system edge") || errOut != "" || asked != nil {
+ t.Errorf("%s: %d %q %q %q", h, code, out, errOut, asked)
+ }
+ }
+}
diff --git a/internal/host/hadrain_call.go b/internal/host/hadrain_call.go
index 1540f5bcc..0566367de 100644
--- a/internal/host/hadrain_call.go
+++ b/internal/host/hadrain_call.go
@@ -31,6 +31,10 @@ package host
// agent's ingress report. The drain unit's ExecStop reaches the same route
// without root, already as the agent's user (__ingress-drain,
// ingressDrainEntry below).
+//
+// It also carries the edge's trust barrier verbs (edge PPv2 spec §4.7,
+// edgetrust.go): ops trust-barrier, trust-resume and trust-status,
+// transaction "-", answered with the edge's trustResult. Root prints it.
import (
"bytes"
@@ -116,6 +120,7 @@ type drainCallResult struct {
Report *drainReport `json:"report,omitempty"`
Status *drainStatus `json:"status,omitempty"`
Ingress *ingressReport `json:"ingress,omitempty"`
+ Trust *trustResult `json:"trust,omitempty"`
}
// err is the call's failure as an error.
@@ -130,7 +135,7 @@ func (r drainCallResult) err() error {
}
// drainCaller makes one call of the agent's drain socket: op is withdraw,
-// move, cancel, status or ingress. peers is withdraw's and move's acknowledgement
+// move, cancel, status, ingress or a trust verb (edgeTrustVerb). peers is withdraw's and move's acknowledgement
// population as the verb passed it, nil when it passed none (the agent
// then refuses the step). A transport failure of the caller itself (the
// child did not run or answered nothing usable) is the error; the agent's
@@ -139,13 +144,13 @@ type drainCaller func(ctx context.Context, op, txn string, peers []string) (drai
// drainCallOp is whether op is a call the child makes.
func drainCallOp(op string) bool {
- return op == "withdraw" || op == "move" || op == "cancel" || op == "status" || op == "ingress"
+ return op == "withdraw" || op == "move" || op == "cancel" || op == "status" || op == "ingress" || edgeTrustVerb(op)
}
// drainCallTxnless is whether op takes no transaction ("-" on the child's
// command line).
func drainCallTxnless(op string) bool {
- return op == "status" || op == "ingress"
+ return op == "status" || op == "ingress" || edgeTrustVerb(op)
}
// socketDrainCall is the call itself over c: the child's body, and the
@@ -166,6 +171,8 @@ func socketDrainCall(c *drainClient) drainCaller {
}
case "ingress":
r.Ingress, err = c.ingressDrain(ctx)
+ case "trust-barrier", "trust-resume", "trust-status":
+ r.Trust, err = c.trust(ctx, op)
default:
return r, errGroupMaintenance
}
@@ -179,7 +186,7 @@ func socketDrainCall(c *drainClient) drainCaller {
}
// drainCallArgs reads the child's arguments: an op and a transaction ("-"
-// for status and ingress), then for withdraw and move a --peers= list when root was
+// for status, ingress and the trust ops), then for withdraw and move a --peers= list when root was
// given one (peers nil when not).
func drainCallArgs(args []string) (op, txn string, peers []string, err error) {
if (len(args) != 2 && len(args) != 3) || !drainCallOp(args[0]) {
@@ -215,8 +222,11 @@ func runDrainCallBody(ctx context.Context, args []string, path string, out io.Wr
return err
}
bound := haDrainCallBound
- if op == "ingress" {
+ switch {
+ case op == "ingress":
bound = ingressAskBound
+ case edgeTrustVerb(op):
+ bound = edgeTrustCallBound
}
ctx, cancel := context.WithTimeout(ctx, bound)
defer cancel()
@@ -228,7 +238,7 @@ func runDrainCallBody(ctx context.Context, args []string, path string, out io.Wr
}
// drainCallChildArgs is the child's argument list after the command: the
-// transaction is "-" for status and ingress; withdraw and move add
+// transaction is "-" for status, ingress and the trust ops; withdraw and move add
// --peers= when root was given a list.
func drainCallChildArgs(op, txn string, peers []string) []string {
if drainCallTxnless(op) {
diff --git a/internal/host/hadrain_socket.go b/internal/host/hadrain_socket.go
index 4b36679e2..4c6315a4d 100644
--- a/internal/host/hadrain_socket.go
+++ b/internal/host/hadrain_socket.go
@@ -29,6 +29,14 @@ package host
// GET /v1/ingress/status arming and the report so far
//
// On a fixed box the /v1/drain/* routes answer 404.
+//
+// It also carries the edge's trust barrier (edge PPv2 spec §4.7,
+// edgetrust.go), on every box that serves the socket, which a box armed
+// for PROXY protocol always does:
+//
+// POST /v1/edge/trust-barrier raise the barrier
+// POST /v1/edge/trust-resume lower it
+// GET /v1/edge/trust arming, barrier and counters
import (
"bytes"
@@ -69,11 +77,12 @@ type drainSocketServer interface {
}
// haDrainSocket is the socket's whole surface: the group drain's routes
-// when group is set (a group member), 404 otherwise, and the ingress
-// drain's routes when ingress is set.
+// when group is set (a group member), 404 otherwise, the ingress drain's
+// routes when ingress is set, and the trust barrier's when edge is set.
type haDrainSocket struct {
group *drainDriver
ingress *ingressDrain
+ edge trustEdge
}
func (s *haDrainSocket) handler() http.Handler {
@@ -85,11 +94,19 @@ func (s *haDrainSocket) handler() http.Handler {
if s.ingress != nil {
ingress = s.ingress.handler()
}
+ var trust http.Handler
+ if s.edge != nil {
+ trust = edgeTrustHandler(s.edge)
+ }
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ingress != nil && strings.HasPrefix(r.URL.Path, "/v1/ingress/") {
ingress.ServeHTTP(w, r)
return
}
+ if trust != nil && strings.HasPrefix(r.URL.Path, "/v1/edge/") {
+ trust.ServeHTTP(w, r)
+ return
+ }
group.ServeHTTP(w, r)
})
}
diff --git a/internal/host/memwatch.go b/internal/host/memwatch.go
index c7153a9c0..5631d7414 100644
--- a/internal/host/memwatch.go
+++ b/internal/host/memwatch.go
@@ -14,6 +14,7 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
+ "github.com/carlosframework/platform/internal/proxyproto"
"github.com/carlosframework/platform/internal/rootaws"
)
@@ -31,6 +32,10 @@ import (
// first; the second is the early warning — it climbs minutes before
// MemAvailable hits the floor.
//
+// On a box armed for PROXY protocol it also publishes
+// IngressProxyTrustViolations (edge PPv2 spec §4.5, edgetrust.go), keyed by
+// Deployment and Region, in a minute with any.
+//
// Per-box, not a housekeeper duty: every box reports itself. Armed only by
// CARLOS_HOST_METRICS=cloudwatch in host.env, so a Pi or a customer fleet
// box never tries to reach an API it has no credentials for.
@@ -57,6 +62,7 @@ func (f putMetricFunc) PutMetricData(ctx context.Context, in *cloudwatch.PutMetr
type memwatch struct {
admission *admissionMetrics
+ trust *trustMetric
put metricPutter
instanceID string
mem func() (*int64, *int64) // MemTotal, MemAvailable in bytes
@@ -89,7 +95,9 @@ func memwatchArmed(getenv func(string) string) (armed bool, why string) {
// and stays quiet rather than retrying — the operator set the env, so a
// silent duty is a bug they'd want to see at arm time, in the journal.
// Process-lifetime, like statusLoop: nothing stops the ticker.
-func memwatchLoop() {
+// trustCounters reads the running edge's PROXY protocol counters for the
+// trust-violation metric (false before the edge runs, or unarmed).
+func memwatchLoop(trustCounters func() (proxyproto.Counters, bool)) {
if armed, why := memwatchArmed(os.Getenv); !armed {
log.Printf("agent: memwatch disabled (%s)", why)
return
@@ -131,6 +139,10 @@ func memwatchLoop() {
if os.Getenv("CARLOS_GROUP_ADMISSION") == "1" && w.admission == nil {
log.Print("memwatch: admission metrics are disabled; group boxes require admission state, a deployment bucket, region configuration, and a verified launch binding")
}
+ w.trust = trustMetricFromEnv(os.Getenv, readRoleRegionConfig, trustCounters)
+ if w.trust == nil && proxySourcesSet(os.Getenv) {
+ log.Print("memwatch: the trust-violation metric is disabled; a box armed for PROXY protocol requires a deployment bucket and region configuration")
+ }
log.Printf("agent: memwatch armed (%s in %s, every %s, instance %s)", memwatchNamespace, cfg.Region, memwatchPeriod, id)
for now := range time.Tick(memwatchPeriod) {
w.tick(ctx, now)
@@ -164,7 +176,20 @@ func (w *memwatch) tick(ctx context.Context, now time.Time) {
input.MetricData = append(input.MetricData, groupMetricData(observation, w.admission.group, w.instanceID, availPct)...)
}
}
+ var trustSum uint64
+ trustPending := false
+ if w.trust != nil {
+ var d types.MetricDatum
+ if d, trustSum, trustPending = w.trust.pending(now); trustPending {
+ input.MetricData = append(input.MetricData, d)
+ }
+ }
_, err := w.put.PutMetricData(ctx, input)
+ if err == nil && trustPending {
+ // Advanced only on a put that landed: a failed one carries the
+ // increase into the next minute.
+ w.trust.sent = trustSum
+ }
switch {
case err != nil && err.Error() != w.lastPutErr:
w.lastPutErr = err.Error()
diff --git a/system.go b/system.go
index 4aeb6a64d..432372106 100644
--- a/system.go
+++ b/system.go
@@ -62,6 +62,7 @@ func systemCommand() *clireg.Node {
raw("group-maintenance", box, func(args []string) {
os.Exit(host.RunGroupMaintenance(args, os.Stdin, os.Stdout, os.Stderr))
}),
+ systemEdgeCommand(),
systemDemosCommand(),
systemManagedFleetsCommand(),
raw("files", box, host.RunSystemFiles),
@@ -149,6 +150,27 @@ func runSystem(args []string) {
clireg.Dispatch(systemCommand(), args)
}
+// systemEdgeCommand is `carlos system edge trust-barrier|trust-resume|
+// trust-status` (edge PPv2 spec §4.7): root verbs on the box that reach
+// the agent's edge the way group-maintenance's drain verbs do. Any other
+// word, or none, is host.RunSystemEdge's usage.
+func systemEdgeCommand() *clireg.Node {
+ const box = clireg.BoxLocal
+ verb := func(name string) *clireg.Node {
+ return raw(name, box, func(args []string) {
+ os.Exit(host.RunSystemEdge(append([]string{name}, args...), os.Stdout, os.Stderr))
+ })
+ }
+ return noHint(&clireg.Node{
+ Name: "edge",
+ Audience: box,
+ Children: []*clireg.Node{verb("trust-barrier"), verb("trust-resume"), verb("trust-status")},
+ Fallback: func(args, _ []string) {
+ os.Exit(host.RunSystemEdge(args, os.Stdout, os.Stderr))
+ },
+ })
+}
+
// systemOneVerbCommand is a family with a single sub-verb (seeds-floor
// publish, legacy-routes assign, lifetimes cutover, hosts-used status):
// any other word, or none, is the usage and exit 2.
diff --git a/testdata/clireg-golden.jsonl b/testdata/clireg-golden.jsonl
index 8e612d783..5d0a369d7 100644
--- a/testdata/clireg-golden.jsonl
+++ b/testdata/clireg-golden.jsonl
@@ -827,6 +827,18 @@
{"case":"system demos | bare","argv":["system","demos"],"exit":2,"stdout":"","stderr":"Check the command arguments. Run carlos system demos help.\n"}
{"case":"system demos | help","argv":["system","demos","help"],"exit":0,"stdout":"Manage anonymous demos: status, serving on or off, takedown, takedown-status, and reports. Commands use your configured console.\n","stderr":""}
{"case":"system demos | zz-unknown","argv":["system","demos","zz-unknown"],"exit":2,"stdout":"","stderr":"Check the command arguments. Run carlos system demos help.\n"}
+{"case":"system edge trust-barrier | --zz-unknown-flag","argv":["system","edge","trust-barrier","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge trust-barrier | -h","argv":["system","edge","trust-barrier","-h"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge trust-resume | --zz-unknown-flag","argv":["system","edge","trust-resume","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge trust-resume | -h","argv":["system","edge","trust-resume","-h"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge trust-status | --zz-unknown-flag","argv":["system","edge","trust-status","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge trust-status | -h","argv":["system","edge","trust-status","-h"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge | --help","argv":["system","edge","--help"],"exit":0,"stdout":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n","stderr":""}
+{"case":"system edge | --zz-unknown-flag","argv":["system","edge","--zz-unknown-flag"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge | -h","argv":["system","edge","-h"],"exit":0,"stdout":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n","stderr":""}
+{"case":"system edge | bare","argv":["system","edge"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
+{"case":"system edge | help","argv":["system","edge","help"],"exit":0,"stdout":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n","stderr":""}
+{"case":"system edge | zz-unknown","argv":["system","edge","zz-unknown"],"exit":2,"stdout":"","stderr":"Usage: carlos system edge {trust-barrier|trust-resume|trust-status}\nRoot only, on a box whose edge reads PROXY protocol from its load balancer.\n trust-barrier Raise the trust barrier: no load balancer header grants a\n client address until trust-resume, across restarts. Close\n every open connection from a load balancer node.\n trust-resume Lower the trust barrier.\n trust-status Print whether the edge is armed, the barrier, and the\n PROXY protocol counters since the edge started.\nEach prints one JSON line.\nExit codes: 0 success or help, 1 refused or failed, 2 invalid arguments or\na box not armed for PROXY protocol.\n"}
{"case":"system exec-sandbox-allows-prev | --zz-unknown-flag","argv":["system","exec-sandbox-allows-prev","--zz-unknown-flag"],"exit":1,"stdout":"","stderr":"EXEC-SANDBOX-CONFIG\n"}
{"case":"system exec-sandbox-allows-prev | -h","argv":["system","exec-sandbox-allows-prev","-h"],"exit":1,"stdout":"","stderr":"EXEC-SANDBOX-CONFIG\n"}
{"case":"system files | --zz-unknown-flag","argv":["system","files","--zz-unknown-flag"],"exit":1,"stdout":"","stderr":"Files seed failed: hostbox: unresolved lifecycle contract.\n"}