carlos / platform Public

region HA P3b-2: a failed hairpin enable no longer tombstones its process

claude agent, operated by paul@keymail.dev abbdac18451a918c2c93df087c9913fe5ffdf57e parent 30489c1
9 files changed, +491 −23
  • internal/hairpin/lifecycle.go +12 −4
  • internal/hairpin/lifecycle_test.go +8 −3
  • internal/host/group_admission.go +10 −0
  • internal/host/group_hairpin.go +12 −3
  • internal/host/group_hairpin_retry.go +2 −0
  • internal/host/group_hairpin_retry_test.go +112 −0
  • internal/host/group_hairpin_rootrunner_linux_test.go +25 −2
  • internal/instancectl/hairpin.go +37 −11
  • internal/instancectl/hairpin_retry_linux_test.go +273 −0
diff --git a/internal/hairpin/lifecycle.go b/internal/hairpin/lifecycle.go
index a617aaf20..3eca94090 100644
--- a/internal/hairpin/lifecycle.go
+++ b/internal/hairpin/lifecycle.go
@@ -15,7 +15,7 @@ type Operations struct {
Verify func(context.Context) error
Addresses func(context.Context, bool) error
Exempt func(context.Context, bool) error
- Save func(bool) error
+ Save func(active, closed bool) error
}
func (o Operations) Enable(ctx context.Context) (err error) {
@@ -23,7 +23,7 @@ func (o Operations) Enable(ctx context.Context) (err error) {
if err != nil {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)
defer cancel()
- err = errors.Join(err, o.Disable(cleanup))
+ err = errors.Join(err, o.Rollback(cleanup))
}
}()
if err = o.Install(ctx); err != nil {
@@ -38,14 +38,22 @@ func (o Operations) Enable(ctx context.Context) (err error) {
if err = o.Exempt(ctx, true); err != nil {
return err
}
- return o.Save(true)
+ return o.Save(true, false)
}
// The dormant fence stays installed. Removal of a fence is reserved for root
// reseeding under maintenance, after removal of all addresses and exemptions.
// Even a failed address removal attempts to restore the full #367 deny.
func (o Operations) Disable(ctx context.Context) error {
- saved := o.Save(false)
+ return o.deactivate(ctx, true)
+}
+
+func (o Operations) Rollback(ctx context.Context) error {
+ return o.deactivate(ctx, false)
+}
+
+func (o Operations) deactivate(ctx context.Context, closed bool) error {
+ saved := o.Save(false, closed)
removed := o.Addresses(ctx, false)
denied := o.Exempt(ctx, false)
return errors.Join(saved, removed, denied)
diff --git a/internal/hairpin/lifecycle_test.go b/internal/hairpin/lifecycle_test.go
index 38af57d86..e7dac4cb7 100644
--- a/internal/hairpin/lifecycle_test.go
+++ b/internal/hairpin/lifecycle_test.go
@@ -19,6 +19,7 @@ func TestHairpinAdmissionLifecycle(t *testing.T) {
return nil
}
fence, addresses, exempt := false, false, false
+ var savedActive, savedClosed bool
ops := Operations{
Install: func(context.Context) error {
err := op("install")
@@ -61,7 +62,8 @@ func TestHairpinAdmissionLifecycle(t *testing.T) {
}
return err
},
- Save: func(on bool) error {
+ Save: func(on, closed bool) error {
+ savedActive, savedClosed = on, closed
n := "save-off"
if on {
n = "save-on"
@@ -81,17 +83,20 @@ func TestHairpinAdmissionLifecycle(t *testing.T) {
if err := ops.Disable(context.Background()); err != nil {
t.Fatal(err)
}
+ if savedActive || !savedClosed {
+ t.Fatal("disable did not tombstone")
+ }
if !reflect.DeepEqual(calls, []string{"save-off", "addresses-off", "exempt-off"}) {
t.Fatal(calls)
}
- } else if err == nil || addresses || exempt {
+ } else if err == nil || addresses || exempt || savedActive || savedClosed {
t.Fatalf("rollback: %v %v addresses=%v exempt=%v", err, calls, addresses, exempt)
}
})
}
t.Run("failed-removal-keeps-fence-and-restores-deny", func(t *testing.T) {
var calls []string
- ops := Operations{Save: func(bool) error { calls = append(calls, "save"); return nil }, Addresses: func(context.Context, bool) error { calls = append(calls, "remove"); return errors.New("ip") }, Exempt: func(context.Context, bool) error { calls = append(calls, "deny"); return nil }}
+ ops := Operations{Save: func(bool, bool) error { calls = append(calls, "save"); return nil }, Addresses: func(context.Context, bool) error { calls = append(calls, "remove"); return errors.New("ip") }, Exempt: func(context.Context, bool) error { calls = append(calls, "deny"); return nil }}
if ops.Disable(context.Background()) == nil || !reflect.DeepEqual(calls, []string{"save", "remove", "deny"}) {
t.Fatal(calls)
}
diff --git a/internal/host/group_admission.go b/internal/host/group_admission.go
index 98b7bd22c..ced0d9a05 100644
--- a/internal/host/group_admission.go
+++ b/internal/host/group_admission.go
@@ -25,6 +25,7 @@ var armedFixedAdmission atomic.Pointer[fixedAdmission]
type fixedAdmission struct {
hairpinRetryState
hairpin func(bool) error
+ hairpinCancel context.CancelFunc
hairpinMu sync.Mutex
hairpinReady atomic.Bool
launchFailure string
@@ -223,6 +224,9 @@ func (a *fixedAdmission) Close() {
a.workCancel()
}
a.workMu.Unlock()
+ if a.hairpinCancel != nil {
+ a.hairpinCancel()
+ }
a.hairpinMu.Lock()
if a.hairpin != nil {
if err := a.hairpin(false); err != nil {
@@ -348,8 +352,14 @@ func (a *fixedAdmission) logWaitingLocked(now time.Time) {
missing = append(missing, "GroupReadersReady")
}
for _, failure := range a.health.Failing(now) {
+ if failure == lbhealth.CondHosting && a.hairpin != nil {
+ continue
+ }
missing = append(missing, string(failure))
}
+ if a.hairpin != nil && !a.hairpinReady.Load() {
+ missing = append(missing, groupHairpinWaitText)
+ }
log.Printf("tenant admission is still closed. waiting for: %s", strings.Join(missing, ", "))
}
diff --git a/internal/host/group_hairpin.go b/internal/host/group_hairpin.go
index cbb93dacc..893d07b8e 100644
--- a/internal/host/group_hairpin.go
+++ b/internal/host/group_hairpin.go
@@ -37,13 +37,22 @@ func configureGroupHairpin(a *fixedAdmission) error {
if err != nil {
return err
}
- client := instancectl.NewClient(controlsock.Path)
+ configureGroupHairpinClient(a, instancectl.NewClient(controlsock.Path), p)
+ return nil
+}
+
+func configureGroupHairpinClient(a *fixedAdmission, client *instancectl.Client, p hairpin.Process) {
+ enableCtx, cancelEnable := context.WithCancel(context.Background())
+ a.hairpinCancel = cancelEnable
a.hairpin = func(enable bool) error {
- ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
+ parent := context.Background()
+ if enable {
+ parent = enableCtx
+ }
+ ctx, cancel := context.WithTimeout(parent, 60*time.Second)
defer cancel()
return client.GroupHairpin(ctx, enable, p)
}
- return nil
}
// Task 4 calls this only after consuming its root maintenance permit, before
diff --git a/internal/host/group_hairpin_retry.go b/internal/host/group_hairpin_retry.go
index 7516a9222..5b453fb9a 100644
--- a/internal/host/group_hairpin_retry.go
+++ b/internal/host/group_hairpin_retry.go
@@ -20,6 +20,7 @@ const (
// Operator text stays together for the controller's copy pass.
const (
+ groupHairpinWaitText = "hairpin"
groupHairpinRetryFailureText = "group hairpin activation failed: code=%s; retry in %s"
groupHairpinAlertSubjectText = "Group hairpin enable needs attention"
groupHairpinAlertBodyText = "Box %s cannot enable hairpin. Failure code: %s. Admission has stayed closed for 15 minutes. Local retries continue."
@@ -62,6 +63,7 @@ func (a *fixedAdmission) enableGroupHairpin() {
a.pageHairpinLocked(false)
}
if now.Before(a.hairpinNext) || !a.known || a.role != boxroles.Serve || !a.initialHealthy() {
+ a.logWaitingLocked(now)
a.mu.Unlock()
return
}
diff --git a/internal/host/group_hairpin_retry_test.go b/internal/host/group_hairpin_retry_test.go
index 87ed0187d..b41fffc1f 100644
--- a/internal/host/group_hairpin_retry_test.go
+++ b/internal/host/group_hairpin_retry_test.go
@@ -1,12 +1,16 @@
package host
import (
+ "bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
+ "io"
"log"
+ "net"
+ "net/http"
"slices"
"strings"
"sync/atomic"
@@ -16,6 +20,7 @@ import (
"github.com/carlosframework/platform/internal/boxroles"
"github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/groupadmission"
+ "github.com/carlosframework/platform/internal/hairpin"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/lbhealth"
)
@@ -392,3 +397,110 @@ func TestGroupHairpinAdmissionFixedUnchanged(t *testing.T) {
})
}
}
+
+func TestGroupHairpinAdmissionWaitingAfterAdmit(t *testing.T) {
+ f := newHairpinRetryFixture(t)
+ a := f.a
+ a.hairpin = func(bool) error { t.Fatal("enable while readers unready"); return nil }
+ if err := a.state.Admit(t.Context(), nil, nil, func() bool { return true }); err != nil {
+ t.Fatal(err)
+ }
+ f.readers.Store(false)
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ for _, step := range []struct {
+ at time.Duration
+ logs int
+ }{{0, 1}, {59 * time.Second, 1}, {time.Minute, 2}} {
+ f.at(step.at)
+ a.tick(t.Context())
+ if got := strings.Count(output.String(), "tenant admission is still closed."); got != step.logs {
+ t.Fatalf("at %s: logs=%d want %d: %s", step.at, got, step.logs, output.String())
+ }
+ if !strings.Contains(output.String(), "GroupReadersReady") || !strings.Contains(output.String(), "hairpin") || strings.Contains(output.String(), "hosting") {
+ t.Fatalf("wrong waits: %s", output.String())
+ }
+ if !a.hairpinFailedAt.IsZero() {
+ t.Fatal("predicate failure counted as enable failure")
+ }
+ assertHairpinWaiting(t, a)
+ }
+}
+
+func TestGroupHairpinAdmissionWaitingNamesRealGate(t *testing.T) {
+ for _, group := range []bool{false, true} {
+ t.Run(fmt.Sprint(group), func(t *testing.T) {
+ a := newFixedAdmission(admissionEnv, admissionHealth())
+ if group {
+ a.hairpin = func(bool) error { return nil }
+ a.group = true
+ }
+ var output bytes.Buffer
+ old := log.Writer()
+ log.SetOutput(&output)
+ defer log.SetOutput(old)
+ a.tick(t.Context())
+ if strings.Contains(output.String(), "hosting") == group || strings.Contains(output.String(), "hairpin") != group {
+ t.Fatalf("wrong gate: %s", output.String())
+ }
+ })
+ }
+}
+
+func TestGroupHairpinAdmissionCloseCancelsEnableBeforeDisable(t *testing.T) {
+ f := newHairpinRetryFixture(t)
+ a := f.a
+ entered, disabled := make(chan struct{}), make(chan struct{})
+ client := &instancectl.Client{Dial: func(context.Context, string) (net.Conn, error) {
+ local, remote := net.Pipe()
+ done := make(chan struct{})
+ t.Cleanup(func() { local.Close(); remote.Close(); <-done })
+ go func() {
+ defer close(done)
+ defer remote.Close()
+ r, err := http.ReadRequest(bufio.NewReader(remote))
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ var req struct{ Enable bool }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ t.Error(err)
+ return
+ }
+ r.Body.Close()
+ if req.Enable {
+ close(entered)
+ io.Copy(io.Discard, remote)
+ return
+ }
+ close(disabled)
+ fmt.Fprint(remote, "HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
+ }()
+ return local, nil
+ }}
+ configureGroupHairpinClient(a, client, hairpin.Process{PID: 1, Start: "1", Boot: "fixture"})
+ defer a.hairpinCancel()
+ ticked := make(chan struct{})
+ go func() { a.tick(t.Context()); close(ticked) }()
+ <-entered
+ closed := make(chan struct{})
+ go func() { a.Close(); close(closed) }()
+ select {
+ case <-closed:
+ case <-time.After(5 * time.Second):
+ t.Fatal("Close waited for the enable deadline instead of cancelling it")
+ }
+ <-ticked
+ select {
+ case <-disabled:
+ default:
+ t.Fatal("Close did not attempt disable with a fresh context")
+ }
+ assertHairpinWaiting(t, a)
+ if !a.closed {
+ t.Fatal("Close reopened admission")
+ }
+}
diff --git a/internal/host/group_hairpin_rootrunner_linux_test.go b/internal/host/group_hairpin_rootrunner_linux_test.go
index dca1b460e..932b1147a 100644
--- a/internal/host/group_hairpin_rootrunner_linux_test.go
+++ b/internal/host/group_hairpin_rootrunner_linux_test.go
@@ -442,6 +442,29 @@ func hairpinMaintenanceRestart(t *testing.T, control *http.Client, scratch strin
}
p1 := identity()
+ arpPath := "/proc/sys/net/ipv4/conf/all/arp_ignore"
+ if err := os.WriteFile(arpPath, []byte("0"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.WriteFile(arpPath, []byte("1"), 0644) })
+ refused(p1, http.StatusServiceUnavailable, "group_hairpin_unavailable")
+ ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
+ defer cancel()
+ l, err := hairpin.Acquire(ctx)
+ if err != nil || l == nil {
+ t.Fatal("failed enable state", err)
+ }
+ failedState := l.State
+ addressErr := l.CheckAddresses(ctx, false)
+ l.Close()
+ if failedState != (hairpin.State{Process: p1}) || addressErr != nil {
+ t.Fatal("failed enable did not roll back to retryable state", failedState, addressErr)
+ }
+ if err := os.WriteFile(arpPath, []byte("1"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ refused(p1, http.StatusOK, "")
+ assertState(p1, true)
hairpinAgentCall(t, control, "/admit")
assertState(p1, true)
if err := a.requireGroupMaintenance("apply"); err != nil {
@@ -1166,11 +1189,11 @@ func TestHairpinRollbackPayload(t *testing.T) {
return err
}
injected := errors.New("injected post-assignment save failure")
- ops := hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses, Exempt: plainDeny, Save: func(on bool) error {
+ ops := hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses, Exempt: plainDeny, Save: func(on, closed bool) error {
if on {
return injected
}
- return l.Save(hairpin.State{Process: l.State.Process, Closed: true})
+ return l.Save(hairpin.State{Process: l.State.Process, Closed: closed})
}}
rollbackErr := ops.Enable(ctx)
l.Close()
diff --git a/internal/instancectl/hairpin.go b/internal/instancectl/hairpin.go
index 964e42722..2a77be9c2 100644
--- a/internal/instancectl/hairpin.go
+++ b/internal/instancectl/hairpin.go
@@ -18,6 +18,14 @@ import (
"github.com/carlosframework/platform/internal/hairpin"
)
+var (
+ hairpinAuthenticate = hairpin.Authenticate
+ hairpinWatchExit = hairpin.WatchExit
+ hairpinSave = (*hairpin.Lease).Save
+ hairpinAddresses = (*hairpin.Lease).Addresses
+ hairpinEUID = os.Geteuid
+)
+
type hairpinLeaseKey struct{}
type hairpinRequest struct {
Enable *bool `json:"enable"`
@@ -79,8 +87,8 @@ func (s *Server) hairpinDeny(ctx context.Context, local []netip.Prefix) ([]netip
// address removal fails, the caller still applies the complete local deny.
l.State.Active = false
l.State.Closed = true
- saved := l.Save(l.State)
- removed := l.Addresses(ctx, false)
+ saved := hairpinSave(l, l.State)
+ removed := hairpinAddresses(l, ctx, false)
current, readErr := s.localPrefixes()
if readErr == nil && len(current) > 0 {
local = current
@@ -97,9 +105,27 @@ func (s *Server) hairpinDeny(ctx context.Context, local []netip.Prefix) ([]netip
return out, nil
}
func (s *Server) hairpinOperations(ctx context.Context, l *hairpin.Lease, p hairpin.Process) hairpin.Operations {
- return hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses,
- Exempt: func(ctx context.Context, on bool) error { l.State.Active = on; return s.denyLocalAddrs(ctx) },
- Save: func(on bool) error { return l.Save(hairpin.State{Process: p, Active: on, Closed: !on}) },
+ revoked := false
+ return hairpin.Operations{Install: l.Install, Verify: l.Verify,
+ Addresses: func(ctx context.Context, on bool) error { return hairpinAddresses(l, ctx, on) },
+ Exempt: func(ctx context.Context, on bool) error {
+ if on {
+ l.State = hairpin.State{Process: p, Active: true}
+ } else {
+ l.State.Active = false
+ }
+ err := s.denyLocalAddrs(ctx)
+ if on {
+ revoked = !l.State.Active && l.State.Closed
+ }
+ return err
+ },
+ Save: func(on, closed bool) error {
+ if !on && revoked {
+ closed = true
+ }
+ return hairpinSave(l, hairpin.State{Process: p, Active: on, Closed: closed})
+ },
}
}
func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
@@ -153,7 +179,7 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
refuse("peer", "group_hairpin_peer", 403, errors.New(groupHairpinMissingLeaseText))
return
}
- if err := hairpin.Authenticate(ctx, conn, req.Process); err != nil {
+ if err := hairpinAuthenticate(ctx, conn, req.Process); err != nil {
refuse("peer", "group_hairpin_peer", 403, err)
return
}
@@ -165,7 +191,7 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
}
if l.State.Active && l.State.Process == req.Process {
if err := errors.Join(l.Verify(ctx), l.CheckAddresses(ctx, true)); err != nil {
- if disableErr := op.Disable(ctx); disableErr != nil {
+ if disableErr := op.Rollback(ctx); disableErr != nil {
s.logf(groupHairpinFailureText, "disable", "group_hairpin_unavailable", 503, disableErr)
}
refuse("verify", "group_hairpin_unavailable", 503, err)
@@ -182,7 +208,7 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) {
}
// Open the descriptor before making the first EIP local. The callback also
// checks the saved identity, so an old exit cannot close a new process.
- stop, watchErr := hairpin.WatchExit(req.Process, func() { s.hairpinExited(req.Process) })
+ stop, watchErr := hairpinWatchExit(req.Process, func() { s.hairpinExited(req.Process) })
if watchErr != nil {
refuse("watch", "group_hairpin_peer", 403, watchErr)
return
@@ -226,7 +252,7 @@ func (s *Server) hairpinExited(p hairpin.Process) {
// state remains closed for the old process. Only a different current MainPID
// may subsequently enable. The group-only reset unit also runs after a crash.
func ClearGroupHairpin(ctx context.Context) error {
- if os.Geteuid() != 0 {
+ if hairpinEUID() != 0 {
return fmt.Errorf("%w: hairpin reset requires root", hairpin.ErrConfig)
}
s := &Server{LocalAddrs: LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) {
@@ -299,7 +325,7 @@ func (s *Server) resumeGroupHairpin(ctx context.Context) error {
if !l.State.Active || hairpin.Current(ctx, p) != nil || l.Verify(ctx) != nil || l.CheckAddresses(ctx, true) != nil {
return s.hairpinOperations(ctx, l, p).Disable(ctx)
}
- _, err = hairpin.WatchExit(p, func() { s.hairpinExited(p) })
+ _, err = hairpinWatchExit(p, func() { s.hairpinExited(p) })
return err
}
@@ -331,5 +357,5 @@ func InstallDormantGroupHairpin(ctx context.Context) error {
if err := l.CheckAddresses(ctx, false); err != nil {
return err
}
- return l.Save(hairpin.State{Closed: true})
+ return hairpinSave(l, hairpin.State{Closed: true})
}
diff --git a/internal/instancectl/hairpin_retry_linux_test.go b/internal/instancectl/hairpin_retry_linux_test.go
new file mode 100644
index 000000000..77b43fef6
--- /dev/null
+++ b/internal/instancectl/hairpin_retry_linux_test.go
@@ -0,0 +1,273 @@
+//go:build linux
+
+package instancectl
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/http/httptest"
+ "net/netip"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hairpin"
+)
+
+type hairpinHandlerFixture struct {
+ s *Server
+ l *hairpin.Lease
+ p hairpin.Process
+ dir string
+ ctx context.Context
+ addresses bool
+ failAdd, failRemove bool
+ watches int
+ saved hairpin.State
+}
+
+func newHairpinHandlerFixture(t *testing.T) *hairpinHandlerFixture {
+ t.Helper()
+ f := &hairpinHandlerFixture{dir: t.TempDir()}
+ var err error
+ f.p, err = hairpin.Identity(os.Getpid())
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.l = &hairpin.Lease{Config: hairpin.Config{V: 1, Region: "ie", PublicIPs: []string{"8.8.8.8", "9.9.9.9"}, PublicIPv4: "1.1.1.1", PrimaryIPv4: "172.31.7.19", PrivateCIDR: "172.31.0.0/16", BootID: f.p.Boot, Account: "123456789012", InstanceID: "i-0123456789abcdef0"}}
+ f.ctx = context.WithValue(t.Context(), hairpinLeaseKey{}, f.l)
+ auth, watch, save, addresses, euid := hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID
+ t.Cleanup(func() {
+ hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID = auth, watch, save, addresses, euid
+ })
+ hairpinAuthenticate = func(_ context.Context, _ net.Conn, p hairpin.Process) error {
+ if p != f.p {
+ return errors.New("stale process")
+ }
+ return nil
+ }
+ hairpinWatchExit = func(hairpin.Process, func()) (func(), error) { f.watches++; return func() {}, nil }
+ hairpinSave = func(l *hairpin.Lease, state hairpin.State) error { l.State = state; f.saved = state; return nil }
+ hairpinAddresses = func(_ *hairpin.Lease, _ context.Context, on bool) error {
+ if on && f.failAdd {
+ f.failAdd = false
+ return errors.New("address add failed")
+ }
+ if !on && f.failRemove {
+ return errors.New("address removal failed")
+ }
+ f.addresses = on
+ body := `[]`
+ if on {
+ body = `[{"addr_info":[{"local":"8.8.8.8","prefixlen":32},{"local":"9.9.9.9","prefixlen":32}]}]`
+ }
+ return os.WriteFile(filepath.Join(f.dir, "addresses"), []byte(body), 0600)
+ }
+ hairpinEUID = func() int { return 0 }
+ t.Setenv("PATH", f.dir)
+ rules, err := f.l.Config.Rules()
+ if err != nil {
+ t.Fatal(err)
+ }
+ f.write(t, "rules", rules)
+ f.write(t, "addresses", "[]")
+ f.write(t, "nft", "#!/bin/sh\ncase \"$*\" in\n '-f -') /bin/cat >/dev/null; echo installed >> '"+f.dir+"/installs';;\n *) /bin/cat '"+f.dir+"/rules';;\nesac\n")
+ f.write(t, "ip", "#!/bin/sh\ncase \"$*\" in\n '-j -4 addr show dev carlos-hairpin') /bin/cat '"+f.dir+"/addresses';;\n '-j -d link show') echo '[{\"ifname\":\"carlos-hairpin\",\"linkinfo\":{\"info_kind\":\"dummy\"}}]';;\n 'link set dev carlos-hairpin up') ;;\n *) exit 2;;\nesac\n")
+ f.write(t, "systemctl", fmt.Sprintf("#!/bin/sh\necho MainPID=%d\necho LoadState=loaded\n", f.p.PID))
+ f.s = &Server{Logf: t.Logf, LocalAddrs: func() ([]netip.Prefix, error) {
+ return parsePrefixes("172.31.7.19/32", "8.8.8.8/32", "9.9.9.9/32"), nil
+ }, Systemctl: func(context.Context, ...string) (string, error) { return "", nil }}
+ return f
+}
+
+func (f *hairpinHandlerFixture) write(t *testing.T, name, body string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(f.dir, name), []byte(body), 0700); err != nil {
+ t.Fatal(err)
+ }
+}
+func (f *hairpinHandlerFixture) request(t *testing.T, on bool, p hairpin.Process) int {
+ t.Helper()
+ raw, err := json.Marshal(hairpinRequest{Enable: &on, Process: p})
+ if err != nil {
+ t.Fatal(err)
+ }
+ local, remote := net.Pipe()
+ defer local.Close()
+ defer remote.Close()
+ r := httptest.NewRequest("POST", "/group-hairpin", strings.NewReader(string(raw)))
+ r = r.WithContext(requestConnContext(f.ctx, local))
+ w := httptest.NewRecorder()
+ f.s.handleHairpin(w, r)
+ return w.Code
+}
+func (f *hairpinHandlerFixture) state(t *testing.T, active, closed bool) {
+ t.Helper()
+ want := hairpin.State{Process: f.p, Active: active, Closed: closed}
+ if f.l.State != want || f.saved != want {
+ t.Fatalf("state=%+v saved=%+v want=%+v", f.l.State, f.saved, want)
+ }
+}
+func (f *hairpinHandlerFixture) fullDeny(t *testing.T) {
+ t.Helper()
+ for _, ip := range f.l.Config.PublicIPs {
+ if !strings.Contains(fmt.Sprint(f.s.lastDeny), ip+"/32") {
+ t.Fatalf("missing deny for %s: %v", ip, f.s.lastDeny)
+ }
+ }
+}
+
+func TestGroupHairpinHandlerFailedEnableRetry(t *testing.T) {
+ f := newHairpinHandlerFixture(t)
+ f.failAdd = true
+ if got := f.request(t, true, f.p); got != 503 {
+ t.Fatalf("failed enable=%d", got)
+ }
+ f.state(t, false, false)
+ stale := f.p
+ stale.Start += "0"
+ if got := f.request(t, true, stale); got != 403 {
+ t.Fatalf("stale retry=%d", got)
+ }
+ f.state(t, false, false)
+ f.fullDeny(t)
+ if f.addresses {
+ t.Fatal("rollback retained addresses")
+ }
+ if got := f.request(t, true, f.p); got != 204 {
+ t.Fatalf("retry=%d, want 204; state=%+v", got, f.l.State)
+ }
+ f.state(t, true, false)
+}
+
+func TestGroupHairpinHandlerVerifyFailureRetry(t *testing.T) {
+ f := newHairpinHandlerFixture(t)
+ if got := f.request(t, true, f.p); got != 204 {
+ t.Fatal(got)
+ }
+ f.write(t, "rules", "invalid")
+ if got := f.request(t, true, f.p); got != 503 {
+ t.Fatal(got)
+ }
+ f.state(t, false, false)
+ f.fullDeny(t)
+ if f.addresses {
+ t.Fatal("verify rollback retained addresses")
+ }
+ rules, _ := f.l.Config.Rules()
+ f.write(t, "rules", rules)
+ if got := f.request(t, true, f.p); got != 204 {
+ t.Fatalf("retry=%d", got)
+ }
+ f.state(t, true, false)
+}
+
+func TestGroupHairpinHandlerTombstones(t *testing.T) {
+ for _, mode := range []string{"disable", "clear", "deny", "resume"} {
+ t.Run(mode, func(t *testing.T) {
+ f := newHairpinHandlerFixture(t)
+ if got := f.request(t, true, f.p); got != 204 {
+ t.Fatal(got)
+ }
+ switch mode {
+ case "disable":
+ if got := f.request(t, false, f.p); got != 204 {
+ t.Fatal(got)
+ }
+ case "clear":
+ if err := ClearGroupHairpin(f.ctx); err != nil {
+ t.Fatal(err)
+ }
+ case "deny":
+ f.write(t, "rules", "invalid")
+ if err := f.s.denyLocalAddrs(f.ctx); err == nil {
+ t.Fatal("revocation accepted")
+ }
+ case "resume":
+ f.write(t, "rules", "invalid")
+ if err := f.s.resumeGroupHairpin(f.ctx); err != nil {
+ t.Fatal(err)
+ }
+ }
+ f.state(t, false, true)
+ before, _ := os.ReadFile(filepath.Join(f.dir, "installs"))
+ watches := f.watches
+ if got := f.request(t, true, f.p); got != 409 {
+ t.Fatalf("retry=%d", got)
+ }
+ after, _ := os.ReadFile(filepath.Join(f.dir, "installs"))
+ if string(after) != string(before) || f.watches != watches {
+ t.Fatal("tombstone checked after enable")
+ }
+ stale := f.p
+ stale.Start += "0"
+ if got := f.request(t, true, stale); got != 403 {
+ t.Fatalf("stale identity=%d", got)
+ }
+ f.state(t, false, true)
+ })
+ }
+}
+
+func TestGroupHairpinHandlerRollbackFailedRemovalRestoresDeny(t *testing.T) {
+ f := newHairpinHandlerFixture(t)
+ if got := f.request(t, true, f.p); got != 204 {
+ t.Fatal(got)
+ }
+ f.write(t, "rules", "invalid")
+ f.failRemove = true
+ if got := f.request(t, true, f.p); got != 503 {
+ t.Fatal(got)
+ }
+ f.state(t, false, false)
+ if !f.addresses {
+ t.Fatal("fixture did not retain addresses on failed removal")
+ }
+ f.fullDeny(t)
+ f.failRemove = false
+ rules, _ := f.l.Config.Rules()
+ f.write(t, "rules", rules)
+ if got := f.request(t, true, f.p); got != 204 {
+ t.Fatalf("retry=%d", got)
+ }
+ f.state(t, true, false)
+}
+
+func TestGroupHairpinHandlerEnableRevocationKeepsTombstone(t *testing.T) {
+ f := newHairpinHandlerFixture(t)
+ // Exemption refresh verifies again after address assignment. This refusal is
+ // a security revocation even when it happens during the first enable.
+ local := f.s.LocalAddrs
+ f.s.LocalAddrs = func() ([]netip.Prefix, error) {
+ if f.addresses {
+ f.write(t, "rules", "invalid")
+ }
+ return local()
+ }
+ if got := f.request(t, true, f.p); got != 503 {
+ t.Fatal(got)
+ }
+ f.state(t, false, true)
+ f.fullDeny(t)
+ if got := f.request(t, true, f.p); got != 409 {
+ t.Fatalf("revocation retry=%d", got)
+ }
+}
+
+func TestGroupHairpinHandlerSuccessorFailedEnableRetry(t *testing.T) {
+ f := newHairpinHandlerFixture(t)
+ f.l.State = hairpin.State{Process: hairpin.Process{PID: 123, Start: "old", Boot: f.p.Boot}, Active: true}
+ f.failAdd = true
+ if got := f.request(t, true, f.p); got != 503 {
+ t.Fatal(got)
+ }
+ f.state(t, false, false)
+ if got := f.request(t, true, f.p); got != 204 {
+ t.Fatalf("successor retry=%d", got)
+ }
+ f.state(t, true, false)
+}