carlos / platform Public

region HA P3b-2: clear group hairpin once, on first consumption

claude agent, operated by paul@keymail.dev c1282519e3e6dd4dc949d9572ba85e665b439a70 parent 5867ae6
6 files changed, +401 −17
  • internal/host/group_hairpin.go +3 −0
  • internal/host/group_hairpin_rootrunner_linux_test.go +157 −2
  • internal/host/group_maintenance.go +5 −1
  • internal/host/group_maintenance_test.go +52 −0
  • internal/instancectl/hairpin.go +82 −14
  • internal/instancectl/hairpin_test.go +102 −0
diff --git a/internal/host/group_hairpin.go b/internal/host/group_hairpin.go
index ea3ad27dc..cbb93dacc 100644
--- a/internal/host/group_hairpin.go
+++ b/internal/host/group_hairpin.go
@@ -49,6 +49,9 @@ func configureGroupHairpin(a *fixedAdmission) error {
// Task 4 calls this only after consuming its root maintenance permit, before
// any edge stop or replacement. Staging trees have no live host interfaces.
func (a *systemApplier) clearGroupHairpin() error {
+ if g := a.groupMaintenance; g != nil && g.clearHairpin != nil {
+ return g.clearHairpin()
+ }
if a.etcDir != "/etc" {
return nil
}
diff --git a/internal/host/group_hairpin_rootrunner_linux_test.go b/internal/host/group_hairpin_rootrunner_linux_test.go
index f30e4d5ac..dca1b460e 100644
--- a/internal/host/group_hairpin_rootrunner_linux_test.go
+++ b/internal/host/group_hairpin_rootrunner_linux_test.go
@@ -8,6 +8,7 @@ import (
"context"
"crypto/rand"
"crypto/rsa"
+ "crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
@@ -21,6 +22,7 @@ import (
"net"
"net/http"
"net/netip"
+ "net/url"
"os"
"os/exec"
"path/filepath"
@@ -40,7 +42,9 @@ import (
"golang.org/x/sys/unix"
)
-func TestHairpinKernelAgentTenantSidecar(t *testing.T) { hairpinKernelWitness(t) }
+func TestHairpinKernelAgentTenantSidecar(t *testing.T) { hairpinKernelWitness(t, false) }
+
+func TestGroupHairpinMaintenanceRestart(t *testing.T) { hairpinKernelWitness(t, true) }
// This witness permits IMDSv2 reads and traffic only to its own fixture. The
// public-shaped EIPs have blackhole fallback routes, so closed-state probes
@@ -48,7 +52,7 @@ func TestHairpinKernelAgentTenantSidecar(t *testing.T) { hairpinKernelWitness(t)
// than skips when root, systemd, nft or cgroup v2 is missing. The agent process
// uses production edge, admission and authenticated root operations; lifecycle
// completion and the app backend are local fixtures, with no ASG/S3/SSM calls.
-func hairpinKernelWitness(t *testing.T) {
+func hairpinKernelWitness(t *testing.T, maintenance bool) {
egressRootPrereqs(t)
for _, tool := range []string{"nft", "ip", "ss", "systemctl"} {
if _, err := exec.LookPath(tool); err != nil {
@@ -248,7 +252,12 @@ func hairpinKernelWitness(t *testing.T) {
hairpinRunnerUnit(t, agentUnit, unit)
hairpinCmd(t, "systemctl", "start", agentUnit)
control := hairpinAgentClient()
+ t.Cleanup(control.CloseIdleConnections)
hairpinAgentWait(t, control)
+ if maintenance {
+ hairpinMaintenanceRestart(t, control, scratch)
+ return
+ }
pid, err := strconv.Atoi(egressShow(t, agentUnit, "MainPID"))
if err != nil {
t.Fatal(err)
@@ -367,6 +376,132 @@ func hairpinKernelWitness(t *testing.T) {
t.Log("PASS: agent, root, tenant, sidecar and rootfs; both EIPs; HTTP/TLS/POST/upgrade; actual listeners fenced; metadata/private/UDP denied for sandbox callers; closure and replacement")
}
+func hairpinMaintenanceRestart(t *testing.T, control *http.Client, scratch string) {
+ t.Helper()
+ if err := os.Mkdir(groupMaintenanceDir, 0700); err != nil {
+ t.Fatal("fixture maintenance directory must not exist", err)
+ }
+ t.Cleanup(func() { os.RemoveAll(groupMaintenanceDir) })
+ artifact := []byte("maintenance fixture artifact")
+ if err := os.WriteFile(systemBinaryPath(scratch), artifact, 0755); err != nil {
+ t.Fatal(err)
+ }
+ a := &systemApplier{etcDir: "/etc", optDir: scratch, ops: productionSysOps()}
+ c, err := a.maintenanceConfig()
+ if err != nil || c == nil {
+ t.Fatal("real maintenance marker", err)
+ }
+ digest := fmt.Sprintf("%x", sha256.Sum256(artifact))
+ p := groupMaintenancePermit{V: 1, Account: c.Account, Region: c.AWSRegion, Group: c.Group, Instance: c.InstanceID, BootID: c.BootID, ConfigDigest: c.ConfigDigest, Transaction: "hairpin-restart", Phase: "mutation", Action: "apply", OldSHA256: digest, NewSHA256: digest, Expires: time.Now().Add(time.Hour).Unix(), AllowRollback: true}
+ raw, err := json.Marshal(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(groupMaintenanceDir, "permit.json"), raw, 0600); err != nil {
+ t.Fatal(err)
+ }
+ identity := func() hairpin.Process {
+ t.Helper()
+ p, err := hairpin.MainProcess(t.Context())
+ if err != nil || p.PID == 0 {
+ t.Fatal("agent MainPID", p, err)
+ }
+ return p
+ }
+ assertState := func(p hairpin.Process, active bool) {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
+ defer cancel()
+ l, err := hairpin.Acquire(ctx)
+ if err != nil || l == nil {
+ t.Fatal("state readback", err)
+ }
+ defer l.Close()
+ if l.State.Process != p || l.State.Active != active || l.State.Closed == active {
+ t.Fatalf("state=%+v want process=%+v active=%v closed=%v", l.State, p, active, !active)
+ }
+ if err := l.CheckAddresses(ctx, active); err != nil {
+ t.Fatal("EIP readback", err)
+ }
+ }
+ refused := func(p hairpin.Process, status int, code string) {
+ t.Helper()
+ raw, err := json.Marshal(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := control.Get("http://fixture/hairpin-enable?process=" + url.QueryEscape(string(raw)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ body, err := io.ReadAll(resp.Body)
+ if err != nil || resp.StatusCode != status || strings.TrimSpace(string(body)) != code {
+ t.Fatalf("enable refusal: status=%d body=%s err=%v; want %d %s", resp.StatusCode, body, err, status, code)
+ }
+ }
+
+ p1 := identity()
+ hairpinAgentCall(t, control, "/admit")
+ assertState(p1, true)
+ if err := a.requireGroupMaintenance("apply"); err != nil {
+ t.Fatal("first consumption", err)
+ }
+ assertState(p1, false)
+ if err := a.restartEdge(); err != nil {
+ t.Fatal("guarded restart", err)
+ }
+ hairpinAgentWait(t, control)
+ p2 := identity()
+ if p2 == p1 {
+ t.Fatal("restart did not replace agent", p1)
+ }
+ // restartRelay, activationGuard and arm all use this exact guard call.
+ for range 3 {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
+ t.Fatal("successor guard", err)
+ }
+ }
+ hairpinAgentCall(t, control, "/admit")
+ assertState(p2, true)
+ refused(p1, http.StatusForbidden, "group_hairpin_peer")
+ assertState(p2, true)
+
+ // A failed forward gate consumes rollback before stopping P2. This first
+ // consumption must still close P2, including its future enable requests.
+ if err := a.requireGroupMaintenance("rollback"); err != nil {
+ t.Fatal("first rollback consumption", err)
+ }
+ assertState(p2, false)
+ refused(p2, http.StatusConflict, "group_hairpin_closed")
+ for deadline := time.Now().Add(5 * time.Second); ; {
+ journal := egressJournal("carlos-instance-control.service")
+ if strings.Contains(journal, fmt.Sprintf("step=closed code=group_hairpin_closed status=409: pid=%d:", p2.PID)) {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatal("closed refusal did not log the process", journal)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if err := a.restartEdge(); err != nil {
+ t.Fatal("rollback restart", err)
+ }
+ hairpinAgentWait(t, control)
+ p3 := identity()
+ if p3 == p2 || p3 == p1 {
+ t.Fatal("rollback did not replace agent", p3)
+ }
+ for range 3 {
+ if err := a.requireGroupMaintenance("apply", "rollback"); err != nil {
+ t.Fatal("rollback successor guard", err)
+ }
+ }
+ hairpinAgentCall(t, control, "/admit")
+ assertState(p3, true)
+ t.Logf("guarded apply and rollback admitted successors: P1=%+v P2=%+v P3=%+v", p1, p2, p3)
+}
+
func hairpinCmd(t *testing.T, args ...string) string {
t.Helper()
ctx, cancel := context.WithTimeout(t.Context(), 70*time.Second)
@@ -622,6 +757,26 @@ func TestHairpinAgentPayload(t *testing.T) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/ping":
+ case "/hairpin-enable":
+ var p hairpin.Process
+ if err := json.Unmarshal([]byte(r.URL.Query().Get("process")), &p); err != nil {
+ http.Error(w, "invalid fixture identity", 400)
+ return
+ }
+ err := instancectl.NewClient(controlsock.Path).GroupHairpin(r.Context(), true, p)
+ if err != nil {
+ var failure *instancectl.GroupHairpinError
+ if errors.As(err, &failure) {
+ if failure.Code == "group_hairpin_closed" && !errors.Is(err, instancectl.ErrGroupHairpinClosed) {
+ http.Error(w, "closed sentinel missing", 500)
+ return
+ }
+ http.Error(w, failure.Code, failure.StatusCode)
+ } else {
+ http.Error(w, err.Error(), 500)
+ }
+ return
+ }
case "/admit":
admission.tick(context.Background())
if !admission.startAllowed() {
diff --git a/internal/host/group_maintenance.go b/internal/host/group_maintenance.go
index 081506c8b..52aa2d1f0 100644
--- a/internal/host/group_maintenance.go
+++ b/internal/host/group_maintenance.go
@@ -49,6 +49,8 @@ type groupMaintenance struct {
permit *groupMaintenancePermit
used map[string]bool
initial bool
+ // Tests can count clears without changing the host's network state.
+ clearHairpin func() error
}
func (a *systemApplier) maintenance() *groupMaintenance {
@@ -117,7 +119,7 @@ func (a *systemApplier) requireGroupMaintenance(action string, alternatives ...s
return a.maintenanceUnconsumed(p)
}
if g.used[action] {
- return a.clearGroupHairpin()
+ return nil
}
if err := consumeGroupAction(g.dir, "used-"+p.Transaction+"-"+action, g.owner); err != nil {
return errors.Join(errGroupMaintenance, err)
@@ -127,6 +129,8 @@ func (a *systemApplier) requireGroupMaintenance(action string, alternatives ...s
}
g.used[action] = true
g.permit = &p
+ // Tombstone the process maintenance is about to stop, never its successor.
+ // Later guards only revalidate authority; unit reset hooks cover restarts.
return a.clearGroupHairpin()
}
diff --git a/internal/host/group_maintenance_test.go b/internal/host/group_maintenance_test.go
index 18504fa91..43a49f103 100644
--- a/internal/host/group_maintenance_test.go
+++ b/internal/host/group_maintenance_test.go
@@ -113,6 +113,58 @@ func writeMaintenancePermit(t *testing.T, f *applyFixture, p groupMaintenancePer
t.Fatal(err)
}
}
+
+func TestGroupMaintenanceClearsHairpinOnce(t *testing.T) {
+ for _, action := range []string{"apply", "rollback"} {
+ t.Run(action, func(t *testing.T) {
+ f, p := maintenanceFixture(t)
+ p.Action = action
+ p.AllowRollback = true
+ writeMaintenancePermit(t, f, p)
+ clears := 0
+ f.a.maintenance().clearHairpin = func() error { clears++; return nil }
+ if err := f.a.requireGroupMaintenance("check"); err != nil || clears != 0 {
+ t.Fatalf("check: clears=%d err=%v", clears, err)
+ }
+ if err := f.a.requireGroupMaintenance(action); err != nil || clears != 1 {
+ t.Fatalf("first consumption: clears=%d err=%v", clears, err)
+ }
+ // These are the real restart entry and the guard used by the relay,
+ // activation finish and arm after it. None may tombstone the successor.
+ if err := f.a.restartEdge(); err != nil {
+ t.Fatal(err)
+ }
+ f.a.restartRelay()
+ for range 3 {
+ if err := f.a.requireGroupMaintenance("apply", "rollback"); err != nil || clears != 1 {
+ t.Fatalf("post-restart guard: clears=%d err=%v", clears, err)
+ }
+ }
+ if action == "apply" {
+ // A failed forward gate consumes rollback while the failed process
+ // still runs. Helpers continue selecting the permit's apply action.
+ if err := f.a.requireGroupMaintenance("rollback"); err != nil || clears != 2 {
+ t.Fatalf("rollback consumption: clears=%d err=%v", clears, err)
+ }
+ if err := f.a.restartEdge(); err != nil {
+ t.Fatal(err)
+ }
+ f.a.restartRelay()
+ for _, guard := range [][]string{{"rollback"}, {"apply", "rollback"}, {"apply", "rollback"}} {
+ if err := f.a.requireGroupMaintenance(guard[0], guard[1:]...); err != nil || clears != 2 {
+ t.Fatalf("rollback successor guard: clears=%d err=%v", clears, err)
+ }
+ }
+ }
+ before := clears
+ p.Expires = f.now.Unix()
+ writeMaintenancePermit(t, f, p)
+ if err := f.a.requireGroupMaintenance("apply", "rollback"); !errors.Is(err, errGroupMaintenance) || clears != before {
+ t.Fatalf("expired consumed permit: clears=%d err=%v", clears, err)
+ }
+ })
+ }
+}
func TestGroupMaintenancePermit(t *testing.T) {
for _, bad := range []string{"valid", "missing", "account", "region", "group", "iid", "boot", "transaction", "old", "new", "digest", "expiry", "verify", "return", "revoked", "mode", "symlink", "hardlink", "directory", "oversize", "unknown", "trailing", "parent-mode", "marker-mode", "marker-corrupt", "agent-receipt"} {
t.Run(bad, func(t *testing.T) {
diff --git a/internal/instancectl/hairpin.go b/internal/instancectl/hairpin.go
index f22fe2c08..964e42722 100644
--- a/internal/instancectl/hairpin.go
+++ b/internal/instancectl/hairpin.go
@@ -12,6 +12,7 @@ import (
"os"
"os/exec"
"slices"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/hairpin"
@@ -23,6 +24,33 @@ type hairpinRequest struct {
Process hairpin.Process `json:"process"`
}
+// Operator diagnostics are kept together for the later copy pass.
+const (
+ groupHairpinErrorText = "%s (HTTP %d)"
+ groupHairpinFailureText = "group hairpin: step=%s code=%s status=%d: %v"
+ groupHairpinClosedText = "pid=%d: %w"
+ groupHairpinMissingPeerText = "missing peer connection"
+ groupHairpinMissingLeaseText = "missing group lease"
+ groupHairpinTrailingValueText = "trailing request value"
+ groupHairpinMissingEnableText = "missing enable field"
+)
+
+var ErrGroupHairpinClosed = errors.New("group_hairpin_closed")
+
+// GroupHairpinError preserves the control service's refusal for callers and logs.
+type GroupHairpinError struct {
+ StatusCode int
+ Code string
+}
+
+func (e *GroupHairpinError) Error() string {
+ return fmt.Sprintf(groupHairpinErrorText, e.Code, e.StatusCode)
+}
+
+func (e *GroupHairpinError) Is(target error) bool {
+ return target == ErrGroupHairpinClosed && e.StatusCode == http.StatusConflict && e.Code == ErrGroupHairpinClosed.Error()
+}
+
// All group operations, the ordinary deny refresh and the entire binary/rootfs
// probe share this root lock. No second per-box polling loop is introduced.
func hairpinLocked(ctx context.Context) (context.Context, func(), error) {
@@ -77,41 +105,70 @@ func (s *Server) hairpinOperations(ctx context.Context, l *hairpin.Lease, p hair
func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
defer cancel()
+ refuse := func(step, code string, status int, err error) {
+ s.logf(groupHairpinFailureText, step, code, status, err)
+ http.Error(w, code, status)
+ }
conn := RequestConn(r.Context())
- if conn == nil || conn.SetReadDeadline(time.Now().Add(5*time.Second)) != nil || conn.SetWriteDeadline(time.Now().Add(75*time.Second)) != nil {
- http.Error(w, "group_hairpin_peer", 403)
+ if conn == nil {
+ refuse("peer", "group_hairpin_peer", 403, errors.New(groupHairpinMissingPeerText))
+ return
+ }
+ if err := conn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
+ refuse("peer", "group_hairpin_peer", 403, err)
+ return
+ }
+ if err := conn.SetWriteDeadline(time.Now().Add(75 * time.Second)); err != nil {
+ refuse("peer", "group_hairpin_peer", 403, err)
return
}
var req hairpinRequest
d := json.NewDecoder(io.LimitReader(r.Body, 1025))
d.DisallowUnknownFields()
- if d.Decode(&req) != nil || d.Decode(new(any)) != io.EOF || req.Enable == nil {
- http.Error(w, "group_hairpin_request", 400)
+ if err := d.Decode(&req); err != nil {
+ refuse("request", "group_hairpin_request", 400, err)
+ return
+ }
+ if err := d.Decode(new(any)); err != io.EOF {
+ if err == nil {
+ err = errors.New(groupHairpinTrailingValueText)
+ }
+ refuse("request", "group_hairpin_request", 400, err)
+ return
+ }
+ if req.Enable == nil {
+ refuse("request", "group_hairpin_request", 400, errors.New(groupHairpinMissingEnableText))
return
}
// Revalidate the exact kernel peer and live MainPID after taking the lock;
// a delayed connection from an earlier process cannot alter its successor.
ctx, unlock, err := hairpinLocked(ctx)
if err != nil {
- http.Error(w, "group_hairpin_unavailable", 503)
+ refuse("lock", "group_hairpin_unavailable", 503, err)
return
}
defer unlock()
l, ok := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease)
- if !ok || hairpin.Authenticate(ctx, conn, req.Process) != nil {
- http.Error(w, "group_hairpin_peer", 403)
+ if !ok {
+ refuse("peer", "group_hairpin_peer", 403, errors.New(groupHairpinMissingLeaseText))
+ return
+ }
+ if err := hairpin.Authenticate(ctx, conn, req.Process); err != nil {
+ refuse("peer", "group_hairpin_peer", 403, err)
return
}
op := s.hairpinOperations(ctx, l, req.Process)
if *req.Enable {
if l.State.Process == req.Process && l.State.Closed {
- http.Error(w, "group_hairpin_closed", 409)
+ refuse("closed", "group_hairpin_closed", 409, fmt.Errorf(groupHairpinClosedText, req.Process.PID, ErrGroupHairpinClosed))
return
}
if l.State.Active && l.State.Process == req.Process {
if err := errors.Join(l.Verify(ctx), l.CheckAddresses(ctx, true)); err != nil {
- _ = op.Disable(ctx)
- http.Error(w, "group_hairpin_unavailable", 503)
+ if disableErr := op.Disable(ctx); disableErr != nil {
+ s.logf(groupHairpinFailureText, "disable", "group_hairpin_unavailable", 503, disableErr)
+ }
+ refuse("verify", "group_hairpin_unavailable", 503, err)
return
}
w.WriteHeader(http.StatusNoContent)
@@ -119,7 +176,7 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
}
if l.State.Active {
if err := op.Disable(ctx); err != nil {
- http.Error(w, "group_hairpin_unavailable", 503)
+ refuse("disable", "group_hairpin_unavailable", 503, err)
return
}
}
@@ -127,7 +184,7 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
// checks the saved identity, so an old exit cannot close a new process.
stop, watchErr := hairpin.WatchExit(req.Process, func() { s.hairpinExited(req.Process) })
if watchErr != nil {
- http.Error(w, "group_hairpin_peer", 403)
+ refuse("watch", "group_hairpin_peer", 403, watchErr)
return
}
err = op.Enable(ctx)
@@ -138,7 +195,11 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
err = op.Disable(ctx)
}
if err != nil {
- http.Error(w, "group_hairpin_unavailable", 503)
+ step := "disable"
+ if *req.Enable {
+ step = "enable"
+ }
+ refuse(step, "group_hairpin_unavailable", 503, err)
return
}
w.WriteHeader(http.StatusNoContent)
@@ -209,7 +270,14 @@ func (c *Client) GroupHairpin(ctx context.Context, enable bool, p hairpin.Proces
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
- return errors.New("group_hairpin_unavailable")
+ body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1025))
+ code := strings.TrimSpace(string(body))
+ switch code {
+ case "group_hairpin_closed", "group_hairpin_peer", "group_hairpin_request", "group_hairpin_unavailable":
+ default:
+ code = "group_hairpin_unavailable"
+ }
+ return errors.Join(&GroupHairpinError{StatusCode: resp.StatusCode, Code: code}, readErr)
}
return nil
}
diff --git a/internal/instancectl/hairpin_test.go b/internal/instancectl/hairpin_test.go
new file mode 100644
index 000000000..327ad26a4
--- /dev/null
+++ b/internal/instancectl/hairpin_test.go
@@ -0,0 +1,102 @@
+package instancectl
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hairpin"
+)
+
+func TestGroupHairpinClientRefusal(t *testing.T) {
+ for _, tc := range []struct {
+ status int
+ body string
+ code string
+ closed bool
+ }{
+ {204, "", "", false},
+ {409, "group_hairpin_closed\n", "group_hairpin_closed", true},
+ {403, "group_hairpin_peer\n", "group_hairpin_peer", false},
+ {400, "group_hairpin_request\n", "group_hairpin_request", false},
+ {503, "group_hairpin_unavailable\n", "group_hairpin_unavailable", false},
+ {503, "group_hairpin_closed\n", "group_hairpin_closed", false},
+ {502, "unexpected response with private detail", "group_hairpin_unavailable", false},
+ } {
+ t.Run(fmt.Sprintf("%d/%s", tc.status, tc.code), func(t *testing.T) {
+ client := &Client{Dial: func(context.Context, string) (net.Conn, error) {
+ local, remote := net.Pipe()
+ t.Cleanup(func() { local.Close(); remote.Close() })
+ go func() {
+ defer remote.Close()
+ req, err := http.ReadRequest(bufio.NewReader(remote))
+ if err != nil {
+ return
+ }
+ io.Copy(io.Discard, req.Body)
+ req.Body.Close()
+ fmt.Fprintf(remote, "HTTP/1.1 %d %s\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s", tc.status, http.StatusText(tc.status), len(tc.body), tc.body)
+ }()
+ return local, nil
+ }}
+ err := client.GroupHairpin(t.Context(), true, hairpin.Process{})
+ if tc.status == 204 {
+ if err != nil {
+ t.Fatal(err)
+ }
+ return
+ }
+ var failure *GroupHairpinError
+ if !errors.As(err, &failure) || failure.StatusCode != tc.status || failure.Code != tc.code {
+ t.Fatalf("refusal=%#v err=%v", failure, err)
+ }
+ wrapped := fmt.Errorf("activation: %w", err)
+ if errors.Is(wrapped, ErrGroupHairpinClosed) != tc.closed {
+ t.Fatalf("closed=%v error=%v", tc.closed, wrapped)
+ }
+ if !strings.Contains(err.Error(), tc.code) || !strings.Contains(err.Error(), fmt.Sprint(tc.status)) || strings.Contains(err.Error(), "private detail") {
+ t.Fatalf("log message=%s", err)
+ }
+ })
+ }
+}
+
+func TestGroupHairpinRefusalLogs(t *testing.T) {
+ for _, tc := range []struct {
+ name, body, step, code string
+ peer bool
+ status int
+ }{
+ {"missing-peer", `{}`, "peer", "group_hairpin_peer", false, 403},
+ {"malformed", `{`, "request", "group_hairpin_request", true, 400},
+ {"missing-enable", `{}`, "request", "group_hairpin_request", true, 400},
+ {"trailing", `{"enable":true} {}`, "request", "group_hairpin_request", true, 400},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var logs []string
+ s := &Server{Logf: func(format string, args ...any) { logs = append(logs, fmt.Sprintf(format, args...)) }}
+ r := httptest.NewRequest("POST", "/group-hairpin", strings.NewReader(tc.body))
+ if tc.peer {
+ local, remote := net.Pipe()
+ defer local.Close()
+ defer remote.Close()
+ r = r.WithContext(requestConnContext(r.Context(), local))
+ }
+ w := httptest.NewRecorder()
+ s.handleHairpin(w, r)
+ if w.Code != tc.status || strings.TrimSpace(w.Body.String()) != tc.code {
+ t.Fatalf("response=%d %s", w.Code, w.Body.String())
+ }
+ if len(logs) != 1 || !strings.Contains(logs[0], "step="+tc.step) || !strings.Contains(logs[0], "code="+tc.code) || strings.Contains(logs[0], "<nil>") {
+ t.Fatalf("logs=%q", logs)
+ }
+ })
+ }
+}