region HA P3b-2: only a named revoke tombstones a hairpin process
6 files changed,
+723
−55
internal/hairpin/lifecycle.go+13 −4internal/hairpin/lifecycle_test.go+57 −2internal/instancectl/hairpin.go+116 −47internal/instancectl/hairpin_invariant_test.go+525 −0internal/instancectl/hardening.go+11 −2internal/instancectl/server.go+1 −0
diff --git a/internal/hairpin/lifecycle.go b/internal/hairpin/lifecycle.go| index 3eca94090..c028b355a 100644 |
| --- a/internal/hairpin/lifecycle.go |
| +++ b/internal/hairpin/lifecycle.go |
| @@ -21,9 +21,7 @@ type Operations struct { |
| func (o Operations) Enable(ctx context.Context) (err error) { |
| defer func() { |
| if err != nil { |
| - cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) |
| - defer cancel() |
| - err = errors.Join(err, o.Rollback(cleanup)) |
| + err = errors.Join(err, o.Rollback(ctx)) |
| } |
| }() |
| if err = o.Install(ctx); err != nil { |
| @@ -44,7 +42,11 @@ func (o Operations) Enable(ctx context.Context) (err error) { |
| // 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 { |
| +// Revocation invariant: a live process is tombstoned only by an act of |
| +// revocation: explicit disable, maintenance clear, exit cleanup, or a genuine |
| +// non-context readback failure of an active exemption. Only Revoke grants that |
| +// authority; all other deactivation uses Rollback and leaves retries open. |
| +func (o Operations) Revoke(ctx context.Context) error { |
| return o.deactivate(ctx, true) |
| } |
| @@ -53,9 +55,16 @@ func (o Operations) Rollback(ctx context.Context) error { |
| } |
| func (o Operations) deactivate(ctx context.Context, closed bool) error { |
| + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) |
| + defer cancel() |
| saved := o.Save(false, closed) |
| removed := o.Addresses(ctx, false) |
| denied := o.Exempt(ctx, false) |
| + if saved != nil { |
| + // A transient write failure must not leave the preceding active state |
| + // on disk for the next lease or a restarted control service to adopt. |
| + saved = errors.Join(saved, o.Save(false, closed)) |
| + } |
| return errors.Join(saved, removed, denied) |
| } |
diff --git a/internal/hairpin/lifecycle_test.go b/internal/hairpin/lifecycle_test.go| index e7dac4cb7..d90eed02b 100644 |
| --- a/internal/hairpin/lifecycle_test.go |
| +++ b/internal/hairpin/lifecycle_test.go |
| @@ -3,8 +3,10 @@ package hairpin |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "reflect" |
| "testing" |
| + "time" |
| ) |
| func TestHairpinAdmissionLifecycle(t *testing.T) { |
| @@ -80,7 +82,7 @@ func TestHairpinAdmissionLifecycle(t *testing.T) { |
| t.Fatal(calls) |
| } |
| calls = nil |
| - if err := ops.Disable(context.Background()); err != nil { |
| + if err := ops.Revoke(context.Background()); err != nil { |
| t.Fatal(err) |
| } |
| if savedActive || !savedClosed { |
| @@ -97,8 +99,61 @@ func TestHairpinAdmissionLifecycle(t *testing.T) { |
| t.Run("failed-removal-keeps-fence-and-restores-deny", func(t *testing.T) { |
| var calls []string |
| 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"}) { |
| + if ops.Revoke(context.Background()) == nil || !reflect.DeepEqual(calls, []string{"save", "remove", "deny"}) { |
| t.Fatal(calls) |
| } |
| }) |
| } |
| + |
| +func TestHairpinDeactivationDetached(t *testing.T) { |
| + for _, revoke := range []bool{false, true} { |
| + for _, expired := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("revoke=%v/expired=%v", revoke, expired), func(t *testing.T) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + if expired { |
| + cancel() |
| + ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) |
| + } |
| + cancel() |
| + var calls []string |
| + cleanup := func(ctx context.Context, name string) error { |
| + deadline, ok := ctx.Deadline() |
| + if ctx.Err() != nil || !ok || time.Until(deadline) > 15*time.Second { |
| + t.Fatalf("cleanup context: %v %v", ctx.Err(), deadline) |
| + } |
| + calls = append(calls, name) |
| + return nil |
| + } |
| + ops := Operations{ |
| + Save: func(active, closed bool) error { |
| + if active || closed != revoke { |
| + t.Fatal(active, closed) |
| + } |
| + return errors.New("save") |
| + }, |
| + Addresses: func(ctx context.Context, on bool) error { |
| + if on { |
| + t.Fatal("add") |
| + } |
| + return cleanup(ctx, "remove") |
| + }, |
| + Exempt: func(ctx context.Context, on bool) error { |
| + if on { |
| + t.Fatal("exempt") |
| + } |
| + return cleanup(ctx, "deny") |
| + }, |
| + } |
| + var err error |
| + if revoke { |
| + err = ops.Revoke(ctx) |
| + } else { |
| + err = ops.Rollback(ctx) |
| + } |
| + if err == nil || !reflect.DeepEqual(calls, []string{"remove", "deny"}) { |
| + t.Fatal(err, calls) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/instancectl/hairpin.go b/internal/instancectl/hairpin.go| index 2a77be9c2..280b08b20 100644 |
| --- a/internal/instancectl/hairpin.go |
| +++ b/internal/instancectl/hairpin.go |
| @@ -24,6 +24,13 @@ var ( |
| hairpinSave = (*hairpin.Lease).Save |
| hairpinAddresses = (*hairpin.Lease).Addresses |
| hairpinEUID = os.Geteuid |
| + hairpinInstall = (*hairpin.Lease).Install |
| + hairpinVerify = (*hairpin.Lease).Verify |
| + hairpinCheck = (*hairpin.Lease).CheckAddresses |
| + hairpinCurrent = hairpin.Current |
| + hairpinMainProcess = hairpin.MainProcess |
| + hairpinPrepare = (*hairpin.Lease).Prepare |
| + hairpinResetServer = newHairpinResetServer |
| ) |
| type hairpinLeaseKey struct{} |
| @@ -82,18 +89,21 @@ func (s *Server) hairpinDeny(ctx context.Context, local []netip.Prefix) ([]netip |
| if !ok || !l.State.Active { |
| return local, nil |
| } |
| - if err := errors.Join(l.Verify(ctx), l.CheckAddresses(ctx, true)); err != nil { |
| - // A failed readback revokes both pieces of authority immediately. Even if |
| - // address removal fails, the caller still applies the complete local deny. |
| - l.State.Active = false |
| - l.State.Closed = true |
| - saved := hairpinSave(l, l.State) |
| - removed := hairpinAddresses(l, ctx, false) |
| - current, readErr := s.localPrefixes() |
| - if readErr == nil && len(current) > 0 { |
| - local = current |
| + if err := errors.Join(hairpinVerify(l, ctx), hairpinCheck(l, ctx, true)); err != nil { |
| + op := s.hairpinOperations(ctx, l, l.State.Process) |
| + // denyLocalAddrs already holds denyMu. Restore the full deny directly, |
| + // using the deactivation context, without entering the refresher again. |
| + op.Exempt = func(cleanup context.Context, _ bool) error { |
| + current, readErr := s.localPrefixes() |
| + if readErr == nil && len(current) > 0 { |
| + local = current |
| + } |
| + return errors.Join(readErr, s.applyLocalDeny(cleanup, local, true)) |
| + } |
| + if hairpinContextError(ctx, err) { |
| + return local, errors.Join(err, op.Rollback(ctx)) |
| } |
| - return local, errors.Join(err, saved, removed, readErr) |
| + return local, errors.Join(err, op.Revoke(ctx)) |
| } |
| out := make([]netip.Prefix, 0, len(local)) |
| for _, p := range local { |
| @@ -105,8 +115,8 @@ 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 { |
| - revoked := false |
| - return hairpin.Operations{Install: l.Install, Verify: l.Verify, |
| + return hairpin.Operations{Install: func(ctx context.Context) error { return hairpinInstall(l, ctx) }, |
| + Verify: func(ctx context.Context) error { return hairpinVerify(l, ctx) }, |
| Addresses: func(ctx context.Context, on bool) error { return hairpinAddresses(l, ctx, on) }, |
| Exempt: func(ctx context.Context, on bool) error { |
| if on { |
| @@ -114,20 +124,50 @@ func (s *Server) hairpinOperations(ctx context.Context, l *hairpin.Lease, p hair |
| } else { |
| l.State.Active = false |
| } |
| - err := s.denyLocalAddrs(ctx) |
| - if on { |
| - revoked = !l.State.Active && l.State.Closed |
| - } |
| - return err |
| + return s.denyLocalAddrs(ctx) |
| }, |
| Save: func(on, closed bool) error { |
| - if !on && revoked { |
| - closed = true |
| + // Rollback cannot undo a Revoke performed by exemption readback. |
| + closed = closed || (l.State.Process == p && l.State.Closed) |
| + state := hairpin.State{Process: p, Active: on && !closed, Closed: closed} |
| + l.State = state |
| + if !state.Active && s.hairpinWatch.process == p { |
| + s.stopHairpinWatch() |
| } |
| - return hairpinSave(l, hairpin.State{Process: p, Active: on, Closed: closed}) |
| + return hairpinSave(l, state) |
| }, |
| } |
| } |
| + |
| +func hairpinContextError(ctx context.Context, err error) bool { |
| + return ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) |
| +} |
| + |
| +type groupHairpinWatch struct { |
| + process hairpin.Process |
| + stop func() |
| +} |
| + |
| +// The root hairpin lock protects the watch along with the lease state. |
| +func (s *Server) stopHairpinWatch() { |
| + if s.hairpinWatch.stop != nil { |
| + s.hairpinWatch.stop() |
| + } |
| + s.hairpinWatch = groupHairpinWatch{} |
| +} |
| + |
| +func (s *Server) watchGroupHairpin(p hairpin.Process) error { |
| + if s.hairpinWatch.stop != nil && s.hairpinWatch.process == p { |
| + return nil |
| + } |
| + s.stopHairpinWatch() |
| + stop, err := hairpinWatchExit(p, func() { s.hairpinExited(p) }) |
| + if err == nil { |
| + s.hairpinWatch = groupHairpinWatch{process: p, stop: stop} |
| + } |
| + return err |
| +} |
| + |
| func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) { |
| ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second) |
| defer cancel() |
| @@ -186,11 +226,14 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) { |
| op := s.hairpinOperations(ctx, l, req.Process) |
| if *req.Enable { |
| if l.State.Process == req.Process && l.State.Closed { |
| + if cleanupErr := op.Rollback(ctx); cleanupErr != nil { |
| + s.logf(groupHairpinFailureText, "disable", "group_hairpin_unavailable", 503, cleanupErr) |
| + } |
| 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 { |
| + if err := errors.Join(hairpinVerify(l, ctx), hairpinCheck(l, ctx, true)); err != nil { |
| if disableErr := op.Rollback(ctx); disableErr != nil { |
| s.logf(groupHairpinFailureText, "disable", "group_hairpin_unavailable", 503, disableErr) |
| } |
| @@ -200,25 +243,22 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) { |
| w.WriteHeader(http.StatusNoContent) |
| return |
| } |
| - if l.State.Active { |
| - if err := op.Disable(ctx); err != nil { |
| - refuse("disable", "group_hairpin_unavailable", 503, err) |
| - return |
| - } |
| + if err := op.Rollback(ctx); err != nil { |
| + refuse("disable", "group_hairpin_unavailable", 503, err) |
| + return |
| } |
| // 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 := hairpinWatchExit(req.Process, func() { s.hairpinExited(req.Process) }) |
| - if watchErr != nil { |
| + if watchErr := s.watchGroupHairpin(req.Process); watchErr != nil { |
| refuse("watch", "group_hairpin_peer", 403, watchErr) |
| return |
| } |
| err = op.Enable(ctx) |
| if err != nil { |
| - stop() |
| + s.stopHairpinWatch() |
| } |
| } else { |
| - err = op.Disable(ctx) |
| + err = op.Revoke(ctx) |
| } |
| if err != nil { |
| step := "disable" |
| @@ -231,7 +271,11 @@ func (s *Server) handleHairpin(w http.ResponseWriter, r *http.Request) { |
| w.WriteHeader(http.StatusNoContent) |
| } |
| func (s *Server) hairpinExited(p hairpin.Process) { |
| - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| + s.cleanupHairpinExit(context.Background(), p) |
| +} |
| + |
| +func (s *Server) cleanupHairpinExit(ctx context.Context, p hairpin.Process) { |
| + ctx, cancel := context.WithTimeout(ctx, 60*time.Second) |
| defer cancel() |
| ctx, unlock, err := hairpinLocked(ctx) |
| if err != nil { |
| @@ -243,7 +287,7 @@ func (s *Server) hairpinExited(p hairpin.Process) { |
| if !ok || l.State.Process != p { |
| return |
| } |
| - if err = s.hairpinOperations(ctx, l, p).Disable(ctx); err != nil { |
| + if err = s.hairpinOperations(ctx, l, p).Revoke(ctx); err != nil { |
| s.logf("group hairpin exit cleanup failed: %v", err) |
| } |
| } |
| @@ -255,10 +299,7 @@ func ClearGroupHairpin(ctx context.Context) error { |
| 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) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| - return string(out), err |
| - }} |
| + s := hairpinResetServer() |
| ctx, unlock, err := hairpinLocked(ctx) |
| if err != nil { |
| return err |
| @@ -270,15 +311,22 @@ func ClearGroupHairpin(ctx context.Context) error { |
| } |
| // Tombstone the current process even if it has never enabled hairpin. |
| // A booting agent must not race a maintenance stop by enabling afterward. |
| - process, lookupErr := hairpin.MainProcess(ctx) |
| + process, lookupErr := hairpinMainProcess(ctx) |
| if process.PID == 0 { |
| process = l.State.Process |
| } |
| - if err := errors.Join(s.hairpinOperations(ctx, l, process).Disable(ctx), lookupErr); err != nil { |
| + if err := errors.Join(s.hairpinOperations(ctx, l, process).Revoke(ctx), lookupErr); err != nil { |
| return err |
| } |
| - return l.Prepare(ctx) |
| + return hairpinPrepare(l, ctx) |
| +} |
| +func newHairpinResetServer() *Server { |
| + return &Server{LocalAddrs: LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + }} |
| } |
| + |
| func groupHairpinMarker() bool { return hairpin.GroupPresent() } |
| func (c *Client) GroupHairpin(ctx context.Context, enable bool, p hairpin.Process) error { |
| @@ -322,11 +370,26 @@ func (s *Server) resumeGroupHairpin(ctx context.Context) error { |
| return nil |
| } |
| p := l.State.Process |
| - 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) |
| + op := s.hairpinOperations(ctx, l, p) |
| + if err := hairpinCurrent(ctx, p); err != nil { |
| + if hairpinContextError(ctx, err) { |
| + return op.Rollback(ctx) |
| + } |
| + return op.Revoke(ctx) |
| } |
| - _, err = hairpinWatchExit(p, func() { s.hairpinExited(p) }) |
| - return err |
| + if !l.State.Active { |
| + return op.Rollback(ctx) |
| + } |
| + if err := errors.Join(hairpinVerify(l, ctx), hairpinCheck(l, ctx, true)); err != nil { |
| + if hairpinContextError(ctx, err) { |
| + return op.Rollback(ctx) |
| + } |
| + return op.Revoke(ctx) |
| + } |
| + if err := s.watchGroupHairpin(p); err != nil { |
| + return errors.Join(err, op.Rollback(ctx)) |
| + } |
| + return nil |
| } |
| // InstallDormantGroupHairpin is the initial root boot stage, before bootstrap |
| @@ -348,14 +411,20 @@ func InstallDormantGroupHairpin(ctx context.Context) error { |
| if l.State != (hairpin.State{}) { |
| return fmt.Errorf("%w: dormant install found saved state", hairpin.ErrConfig) |
| } |
| - if current, err := hairpin.MainProcess(ctx); err != nil || current.PID != 0 { |
| + if current, err := hairpinMainProcess(ctx); err != nil || current.PID != 0 { |
| return fmt.Errorf("%w: dormant install agent lookup failed or agent exists", hairpin.ErrConfig) |
| } |
| - if err := l.Prepare(ctx); err != nil { |
| + if err := hairpinPrepare(l, ctx); err != nil { |
| return err |
| } |
| if err := l.CheckAddresses(ctx, false); err != nil { |
| return err |
| } |
| - return hairpinSave(l, hairpin.State{Closed: true}) |
| + op := hairpin.Operations{ |
| + Save: func(_, closed bool) error { return hairpinSave(l, hairpin.State{Closed: closed}) }, |
| + Addresses: func(ctx context.Context, on bool) error { return hairpinAddresses(l, ctx, on) }, |
| + // Initial install has never granted an exemption. |
| + Exempt: func(context.Context, bool) error { return nil }, |
| + } |
| + return op.Revoke(ctx) |
| } |
diff --git a/internal/instancectl/hairpin_invariant_test.go b/internal/instancectl/hairpin_invariant_test.go| new file mode 100644 |
| index 000000000..82f096286 |
| --- /dev/null |
| +++ b/internal/instancectl/hairpin_invariant_test.go |
| @@ -0,0 +1,525 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "math/rand" |
| + "net" |
| + "net/http/httptest" |
| + "net/netip" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hairpin" |
| +) |
| + |
| +// These seams replace only kernel identity, kernel commands and persistence. |
| +// The handler, Operations, deny application and restart decisions are real. |
| +type hairpinMachine struct { |
| + persisted hairpin.State |
| + failure error |
| + readbackCanceled bool |
| + t *testing.T |
| + s *Server |
| + l *hairpin.Lease |
| + p hairpin.Process |
| + live bool |
| + addresses, denied bool |
| + watches, maxWatches int |
| + fail, cancelAt string |
| + nth, seen int |
| + cancel context.CancelFunc |
| + trace []string |
| + removed, deactivated bool |
| + readbackFailure bool |
| +} |
| + |
| +func newHairpinMachine(t *testing.T) *hairpinMachine { |
| + t.Helper() |
| + m := &hairpinMachine{t: t, p: hairpin.Process{PID: 101, Start: "1", Boot: "boot"}, live: true, denied: true} |
| + m.l = &hairpin.Lease{Config: hairpin.Config{PublicIPs: []string{"8.8.8.8", "9.9.9.9"}}} |
| + resetServer := hairpinResetServer |
| + auth, watch, save, addresses, euid := hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID |
| + install, verify, check, current, main, prepare := hairpinInstall, hairpinVerify, hairpinCheck, hairpinCurrent, hairpinMainProcess, hairpinPrepare |
| + t.Cleanup(func() { |
| + m.s.stopHairpinWatch() |
| + hairpinResetServer = resetServer |
| + hairpinAuthenticate, hairpinWatchExit, hairpinSave, hairpinAddresses, hairpinEUID = auth, watch, save, addresses, euid |
| + hairpinInstall, hairpinVerify, hairpinCheck, hairpinCurrent, hairpinMainProcess, hairpinPrepare = install, verify, check, current, main, prepare |
| + }) |
| + hairpinResetServer = func() *Server { return m.s } |
| + hairpinAuthenticate = func(ctx context.Context, _ net.Conn, p hairpin.Process) error { |
| + if !m.live || p != m.p { |
| + return errors.New("stale") |
| + } |
| + return ctx.Err() |
| + } |
| + hairpinCurrent = func(ctx context.Context, p hairpin.Process) error { |
| + if err := m.step(ctx, "current"); err != nil { |
| + return err |
| + } |
| + if !m.live || p != m.p { |
| + return errors.New("dead") |
| + } |
| + return nil |
| + } |
| + hairpinMainProcess = func(ctx context.Context) (hairpin.Process, error) { return m.p, ctx.Err() } |
| + hairpinPrepare = func(*hairpin.Lease, context.Context) error { return nil } |
| + hairpinEUID = func() int { return 0 } |
| + hairpinWatchExit = func(p hairpin.Process, _ func()) (func(), error) { |
| + if err := m.step(context.Background(), "watch"); err != nil { |
| + return nil, err |
| + } |
| + if !m.live || p != m.p { |
| + return nil, errors.New("dead") |
| + } |
| + m.watches++ |
| + m.maxWatches = max(m.maxWatches, m.watches) |
| + stopped := false |
| + return func() { |
| + if !stopped { |
| + m.watches-- |
| + stopped = true |
| + } |
| + }, nil |
| + } |
| + hairpinInstall = func(_ *hairpin.Lease, ctx context.Context) error { return m.step(ctx, "install") } |
| + hairpinVerify = func(_ *hairpin.Lease, ctx context.Context) error { |
| + err := m.step(ctx, "verify") |
| + if err != nil && !hairpinContextError(ctx, err) { |
| + m.readbackFailure = true |
| + } |
| + return err |
| + } |
| + hairpinCheck = func(_ *hairpin.Lease, ctx context.Context, on bool) error { |
| + if err := m.step(ctx, "check"); err != nil { |
| + return err |
| + } |
| + if m.addresses != on { |
| + return errors.New("address readback") |
| + } |
| + return nil |
| + } |
| + hairpinAddresses = func(_ *hairpin.Lease, ctx context.Context, on bool) error { |
| + name := "remove" |
| + if on { |
| + name = "addresses" |
| + } |
| + if !on { |
| + m.removed = false |
| + m.cleanupContext(ctx) |
| + } |
| + if err := m.step(ctx, name); err != nil { |
| + return err |
| + } |
| + m.addresses = on |
| + if !on { |
| + m.removed = true |
| + } |
| + return nil |
| + } |
| + hairpinSave = func(l *hairpin.Lease, state hairpin.State) error { |
| + name := "save-off" |
| + if state.Active { |
| + name = "save" |
| + } else { |
| + m.deactivated = true |
| + } |
| + err := m.step(context.Background(), name) |
| + if err == nil { |
| + m.persisted = state |
| + } |
| + l.State = state |
| + return err |
| + } |
| + m.resetServer() |
| + return m |
| +} |
| + |
| +func (m *hairpinMachine) resetServer() { |
| + m.s = &Server{Logf: func(string, ...any) {}, 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(ctx context.Context, args ...string) (string, error) { |
| + deny := strings.Contains(args[len(args)-1], "8.8.8.8/32") |
| + name := "exempt" |
| + if deny { |
| + name = "deny" |
| + m.cleanupContext(ctx) |
| + } |
| + if err := m.step(ctx, name); err != nil { |
| + return "", err |
| + } |
| + m.denied = deny |
| + return "", nil |
| + }} |
| +} |
| +func (m *hairpinMachine) cleanupContext(ctx context.Context) { |
| + m.t.Helper() |
| + // Ordinary refreshes also apply a deny. Only deactivation is detached. |
| + if !m.deactivated { |
| + return |
| + } |
| + deadline, ok := ctx.Deadline() |
| + if ctx.Err() != nil || !ok || time.Until(deadline) > 15*time.Second { |
| + m.t.Fatalf("cleanup context: err=%v deadline=%v", ctx.Err(), deadline) |
| + } |
| +} |
| +func (m *hairpinMachine) step(ctx context.Context, name string) error { |
| + m.trace = append(m.trace, name) |
| + if name == m.cancelAt { |
| + m.cancel() |
| + m.cancelAt = "" |
| + } |
| + if err := ctx.Err(); err != nil { |
| + if name == "verify" || name == "check" { |
| + m.readbackCanceled = true |
| + } |
| + return err |
| + } |
| + if name == m.fail { |
| + m.seen++ |
| + if m.seen == max(1, m.nth) { |
| + if m.failure != nil { |
| + return m.failure |
| + } |
| + return errors.New("injected " + name) |
| + } |
| + } |
| + return nil |
| +} |
| +func (m *hairpinMachine) context() (context.Context, context.CancelFunc) { |
| + ctx, cancel := context.WithCancel(context.WithValue(context.Background(), hairpinLeaseKey{}, m.l)) |
| + m.cancel = cancel |
| + m.trace = nil |
| + m.seen = 0 |
| + m.removed = false |
| + m.deactivated = false |
| + m.readbackFailure = false |
| + m.readbackCanceled = false |
| + return ctx, cancel |
| +} |
| +func (m *hairpinMachine) request(ctx context.Context, on bool, p hairpin.Process) int { |
| + raw, _ := json.Marshal(hairpinRequest{Enable: &on, Process: p}) |
| + local, remote := net.Pipe() |
| + defer local.Close() |
| + defer remote.Close() |
| + req := httptest.NewRequest("POST", "/group-hairpin", strings.NewReader(string(raw))) |
| + req = req.WithContext(requestConnContext(ctx, local)) |
| + w := httptest.NewRecorder() |
| + m.s.handleHairpin(w, req) |
| + return w.Code |
| +} |
| +func (m *hairpinMachine) initial(active, closed bool) { |
| + m.l.State = hairpin.State{Process: m.p, Active: active, Closed: closed} |
| + m.persisted = m.l.State |
| + m.addresses = active |
| + m.denied = !active |
| +} |
| +func (m *hairpinMachine) act(ctx context.Context, path string) int { |
| + switch path { |
| + case "enable": |
| + return m.request(ctx, true, m.p) |
| + case "disable": |
| + return m.request(ctx, false, m.p) |
| + case "clear": |
| + if ClearGroupHairpin(ctx) != nil { |
| + return 503 |
| + } |
| + case "resume": |
| + m.s.stopHairpinWatch() |
| + m.l.State = m.persisted |
| + m.resetServer() |
| + if m.s.resumeGroupHairpin(ctx) != nil { |
| + return 503 |
| + } |
| + case "deny": |
| + if m.s.denyLocalAddrs(ctx) != nil { |
| + return 503 |
| + } |
| + case "exit": |
| + m.live = false |
| + m.s.cleanupHairpinExit(ctx, m.p) |
| + default: |
| + m.t.Fatal(path) |
| + } |
| + return 204 |
| +} |
| + |
| +func TestGroupHairpinRevocationGuard(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, path string |
| + active, closed, successor bool |
| + fail, cancel string |
| + wantActive, wantClosed bool |
| + next int |
| + }{ |
| + {name: "N1/predecessor-removal", path: "enable", active: true, successor: true, fail: "remove", next: 204}, |
| + {name: "N1/predecessor-watch", path: "enable", active: true, successor: true, fail: "watch", next: 204}, |
| + {name: "N2/restart-retry", path: "resume", next: 204}, |
| + {name: "N2/restart-closed", path: "resume", closed: true, wantClosed: true, next: 409}, |
| + {name: "N2/restart-active", path: "resume", active: true, wantActive: true, next: 204}, |
| + {name: "N2/restart-dead", path: "resume", active: true, successor: true, wantClosed: true, next: 204}, |
| + {name: "N3/deny-cancel-verify", path: "deny", active: true, cancel: "verify", next: 204}, |
| + {name: "N3/deny-cancel-check", path: "deny", active: true, cancel: "check", next: 204}, |
| + {name: "N3/resume-cancel-current", path: "resume", active: true, cancel: "current", next: 204}, |
| + {name: "N3/resume-cancel-verify", path: "resume", active: true, cancel: "verify", next: 204}, |
| + {name: "N3/deny-real-failure", path: "deny", active: true, fail: "verify", wantClosed: true, next: 409}, |
| + {name: "N3/resume-real-failure", path: "resume", active: true, fail: "verify", wantClosed: true, next: 409}, |
| + {name: "N4/idempotent-cancel", path: "enable", active: true, cancel: "verify", next: 204}, |
| + {name: "idempotent-verify", path: "enable", active: true, fail: "verify", next: 204}, |
| + {name: "disable", path: "disable", active: true, wantClosed: true, next: 409}, |
| + {name: "disable-cancel", path: "disable", active: true, cancel: "remove", wantClosed: true, next: 409}, |
| + {name: "clear", path: "clear", wantClosed: true, next: 409}, |
| + {name: "exit", path: "exit", active: true, wantClosed: true, next: 403}, |
| + {name: "install", path: "enable", fail: "install", next: 204}, |
| + {name: "verify", path: "enable", fail: "verify", next: 204}, |
| + {name: "addresses", path: "enable", fail: "addresses", next: 204}, |
| + {name: "exempt", path: "enable", fail: "exempt", next: 204}, |
| + {name: "save", path: "enable", fail: "save", next: 204}, |
| + {name: "save-off", path: "enable", fail: "save-off", next: 204}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(tc.active, tc.closed) |
| + old := m.p |
| + if tc.successor { |
| + m.p.Start = "2" |
| + } |
| + m.fail, m.cancelAt = tc.fail, tc.cancel |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, tc.path) |
| + wantProcess := m.p |
| + if tc.name == "N2/restart-dead" { |
| + wantProcess = old |
| + } |
| + want := hairpin.State{Process: wantProcess, Active: tc.wantActive, Closed: tc.wantClosed} |
| + if m.l.State != want { |
| + t.Fatalf("state=%+v want=%+v trace=%v", m.l.State, want, m.trace) |
| + } |
| + if !tc.wantActive && tc.fail != "remove" && (m.addresses || !m.denied) { |
| + t.Fatalf("deactivation addresses=%v denied=%v trace=%v", m.addresses, m.denied, m.trace) |
| + } |
| + m.fail, m.cancelAt = "", "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + if got := m.request(ctx, true, m.p); got != tc.next { |
| + t.Fatalf("next=%d want=%d state=%+v trace=%v", got, tc.next, m.l.State, m.trace) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinSingleExitWatch(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + for range 8 { |
| + ctx, cancel := m.context() |
| + if m.request(ctx, true, m.p) != 204 { |
| + t.Fatal("enable") |
| + } |
| + for range 3 { |
| + if m.request(ctx, true, m.p) != 204 { |
| + t.Fatal("idempotent") |
| + } |
| + } |
| + m.fail = "verify" |
| + m.seen = 0 |
| + if m.request(ctx, true, m.p) != 503 { |
| + t.Fatal("verify") |
| + } |
| + m.fail = "" |
| + cancel() |
| + } |
| + if m.maxWatches != 1 || m.watches != 0 { |
| + t.Fatalf("watchers max=%d left=%d", m.maxWatches, m.watches) |
| + } |
| +} |
| + |
| +func TestGroupHairpinSeededInvariants(t *testing.T) { |
| + paths := []string{"enable", "enable", "disable", "clear", "resume", "exit", "successor", "deny", "stale"} |
| + failures := []string{"", "install", "verify", "addresses", "remove", "exempt", "deny", "save", "save-off", "watch"} |
| + cancellations := []string{"", "current", "watch", "install", "verify", "check", "addresses", "remove", "exempt", "deny", "save", "save-off"} |
| + for seed := int64(0); seed < 500; seed++ { |
| + t.Run(fmt.Sprintf("seed=%d", seed), func(t *testing.T) { |
| + r := rand.New(rand.NewSource(seed)) |
| + m := newHairpinMachine(t) |
| + revoked := map[hairpin.Process]bool{} |
| + for n := 0; n < 80; n++ { |
| + path := paths[r.Intn(len(paths))] |
| + m.fail = failures[r.Intn(len(failures))] |
| + m.cancelAt = cancellations[r.Intn(len(cancellations))] |
| + m.nth = 1 + r.Intn(2) |
| + m.l.State = m.persisted |
| + ctx, cancel := m.context() |
| + prior := m.l.State |
| + switch path { |
| + case "successor": |
| + old := m.p |
| + m.p.Start = fmt.Sprint(n + 2) |
| + m.live = true |
| + if got := m.request(ctx, true, old); got != 403 || m.l.State != prior { |
| + t.Fatalf("S4 step=%d successor accepted stale request=%d state=%+v", n, got, m.l.State) |
| + } |
| + case "stale": |
| + stale := m.p |
| + stale.Start = "exited" |
| + if got := m.request(ctx, true, stale); got != 403 { |
| + t.Fatalf("S4 step=%d stale=%d", n, got) |
| + } |
| + default: |
| + m.act(ctx, path) |
| + if path == "clear" || path == "disable" && m.live || path == "exit" && prior.Process == m.p { |
| + revoked[m.p] = true |
| + } |
| + if path == "resume" && prior.Process != m.p || path == "resume" && !m.live { |
| + revoked[prior.Process] = true |
| + } |
| + // A genuine readback in refresh/resume revokes an active exemption. |
| + // Idempotent verification and pre-exemption Verify are retryable. |
| + if (path == "deny" || path == "resume") && prior.Active && m.readbackFailure && !m.readbackCanceled { |
| + revoked[prior.Process] = true |
| + } |
| + if path == "enable" && !prior.Active && m.readbackFailure && m.seen == 2 && !m.readbackCanceled { |
| + revoked[m.p] = true |
| + } |
| + } |
| + cancel() |
| + if m.l.State.Active && revoked[m.l.State.Process] { |
| + t.Fatalf("S2 step=%d path=%s state=%+v trace=%v", n, path, m.l.State, m.trace) |
| + } |
| + if m.deactivated && !m.l.State.Active && m.removed && m.addresses { |
| + t.Fatalf("S3 step=%d path=%s removed address remains", n, path) |
| + } |
| + if m.deactivated && !m.l.State.Active && m.removed && m.fail != "deny" && !m.denied { |
| + t.Fatalf("S3 step=%d path=%s deny missing trace=%v", n, path, m.trace) |
| + } |
| + // Stop failures after each transition. A restart retries incomplete |
| + // deactivation before the next enable; no elapsed-time escape is used. |
| + m.fail, m.cancelAt = "", "" |
| + m.nth = 1 |
| + ctx, finish := m.context() |
| + if !m.l.State.Active { |
| + if err := m.s.resumeGroupHairpin(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.addresses || !m.denied { |
| + t.Fatalf("S3 step=%d path=%s cleanup addresses=%v deny=%v", n, path, m.addresses, m.denied) |
| + } |
| + } |
| + got := m.request(ctx, true, m.p) |
| + switch { |
| + case !m.live: |
| + if got != 403 { |
| + t.Fatalf("S4 step=%d dead enable=%d", n, got) |
| + } |
| + case revoked[m.p]: |
| + if got != 409 || m.l.State.Active { |
| + t.Fatalf("S2 step=%d path=%s revoked retry=%d state=%+v", n, path, got, m.l.State) |
| + } |
| + default: |
| + if got != 204 || !m.l.State.Active { |
| + t.Fatalf("S1 step=%d path=%s retry=%d state=%+v", n, path, got, m.l.State) |
| + } |
| + } |
| + finish() |
| + if m.maxWatches > 1 { |
| + t.Fatalf("watch leak step=%d max=%d", n, m.maxWatches) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinReadbackDeadlineIsRetryable(t *testing.T) { |
| + for _, path := range []string{"enable", "deny", "resume"} { |
| + for _, step := range []string{"verify", "check"} { |
| + t.Run(path+"/"+step, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(true, false) |
| + m.fail = step |
| + m.failure = fmt.Errorf("readback: %w", context.DeadlineExceeded) |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, path) |
| + if m.l.State.Active || m.l.State.Closed || m.addresses || !m.denied { |
| + t.Fatalf("deadline state=%+v addresses=%v deny=%v", m.l.State, m.addresses, m.denied) |
| + } |
| + m.fail = "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + if got := m.request(ctx, true, m.p); got != 204 { |
| + t.Fatalf("deadline retry=%d", got) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestGroupHairpinFailedRemovalRetries(t *testing.T) { |
| + for _, path := range []string{"enable", "disable", "clear", "resume", "deny"} { |
| + t.Run(path, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(true, false) |
| + m.fail = "remove" |
| + if path == "enable" || path == "resume" || path == "deny" { |
| + m.cancelAt = "verify" |
| + } |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, path) |
| + if m.l.State.Active || !m.addresses || !m.denied { |
| + t.Fatalf("failed removal state=%+v addresses=%v deny=%v", m.l.State, m.addresses, m.denied) |
| + } |
| + closed := path == "disable" || path == "clear" |
| + if m.l.State.Closed != closed { |
| + t.Fatalf("closed=%v want=%v", m.l.State.Closed, closed) |
| + } |
| + m.fail, m.cancelAt = "", "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + if err := m.s.resumeGroupHairpin(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m.addresses || !m.denied { |
| + t.Fatal("restart did not retry removal") |
| + } |
| + want := 204 |
| + if closed { |
| + want = 409 |
| + } |
| + if got := m.request(ctx, true, m.p); got != want { |
| + t.Fatalf("retry=%d want=%d", got, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestGroupHairpinTransientRevocationSaveSurvivesRestart(t *testing.T) { |
| + for _, path := range []string{"disable", "clear", "exit"} { |
| + t.Run(path, func(t *testing.T) { |
| + m := newHairpinMachine(t) |
| + m.initial(true, false) |
| + m.fail = "save-off" |
| + ctx, cancel := m.context() |
| + defer cancel() |
| + m.act(ctx, path) |
| + if m.persisted.Active || !m.persisted.Closed { |
| + t.Fatalf("revocation lost on disk: %+v trace=%v", m.persisted, m.trace) |
| + } |
| + m.fail = "" |
| + ctx, cancel = m.context() |
| + defer cancel() |
| + m.act(ctx, "resume") |
| + want := 409 |
| + if path == "exit" { |
| + want = 403 |
| + } |
| + if got := m.request(ctx, true, m.p); got != want { |
| + t.Fatalf("restart enable=%d want=%d", got, want) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/instancectl/hardening.go b/internal/instancectl/hardening.go| index dab1a5430..2e4eb43dd 100644 |
| --- a/internal/instancectl/hardening.go |
| +++ b/internal/instancectl/hardening.go |
| @@ -303,6 +303,15 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| return fmt.Errorf("this box's addresses: %v; the last deny stands", err) |
| } |
| local, hairpinErr := s.hairpinDeny(ctx, local) |
| + if hairpinErr != nil { |
| + return hairpinErr |
| + } |
| + return s.applyLocalDeny(ctx, local, false) |
| +} |
| + |
| +// The caller holds denyMu. A failed hairpin readback forces a full deny even |
| +// when the last successful application already contained these addresses. |
| +func (s *Server) applyLocalDeny(ctx context.Context, local []netip.Prefix, force bool) error { |
| deny := denySet(local) |
| if len(deny) == 0 { |
| return errors.New("this box's addresses: none read; the last deny stands") |
| @@ -310,7 +319,7 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| l, group := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease) |
| s.mu.Lock() |
| unchanged := slices.Equal(deny, s.lastDeny) |
| - if group && unchanged && hairpinErr == nil { |
| + if group && unchanged && !force { |
| s.hairpinActive = l.State.Active |
| s.mu.Unlock() |
| return nil |
| @@ -328,7 +337,7 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| s.lastDeny = deny |
| s.hairpinActive = group && l.State.Active |
| s.mu.Unlock() |
| - return hairpinErr |
| + return nil |
| } |
| // denySet is local sorted by its string form, each prefix once: the deny |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index 90da0756c..a7a9ab490 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -208,6 +208,7 @@ type Server struct { |
| // and deduplicated (denySet); denyLoop compares a fresh read with it. |
| lastDeny []netip.Prefix |
| hairpinActive bool |
| + hairpinWatch groupHairpinWatch |
| // denyMu runs one denyLocalAddrs at a time (RunProbe's and denyLoop's), |
| // so an older read of the addresses is never applied over a newer one. |
| denyMu sync.Mutex |