region HA P3b T5: review fixes for refresh, removal and sandbox witness
Apply closed review round 1 P2-1/P2-2 and requested P3-1/P3-2/P3-4 fixes. Require external connections and accept-time closure; retain production control service hardening in the kernel witness. Check route removal and avoid unchanged group deny writes. Keep the runtime-directory allowance optional and group-only. Targeted RED/GREEN tests and package vet pass; root-runner validation follows.
Co-Authored-By: GPT-6 Astra (codex) <noreply@openai.com>
8 files changed,
+316
−62
infra/modules/region-host/group-init.sh.tftpl+1 −1internal/hairpin/native_linux.go+12 −1internal/hairpin/native_linux_test.go+32 −0internal/host/group_hairpin_rootrunner_linux_test.go+137 −58internal/host/group_hairpin_test.go+22 −0internal/instancectl/hairpin_refresh_linux_test.go+97 −0internal/instancectl/hardening.go+13 −1internal/instancectl/server.go+2 −1
Intent
Human
<task-notification> <task-id>bkx2ku21g</task-id> <tool-use-id>toolu_017rGUBpWA74UGQQLj8ncxL2</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/05c816f1-0a2d-43e3-9285-de8352549786/tasks/bkx2ku21g.output</output-file> <status>completed</status> <summary>Background command "D=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3b-build/.superpowers/sdd/2026-11-04-region-ha-p3b-group; $D/wait-astra.sh t5dg $D/task-5-report.md" completed (exit code 0)</summary> </task-notification>
diff --git a/infra/modules/region-host/group-init.sh.tftpl b/infra/modules/region-host/group-init.sh.tftpl| index 70e652d06..33281c1ef 100644 |
| --- a/infra/modules/region-host/group-init.sh.tftpl |
| +++ b/infra/modules/region-host/group-init.sh.tftpl |
| @@ -237,7 +237,7 @@ files = { |
| '/etc/sysctl.d/99-carlos-hairpin.conf': 'net.ipv4.conf.all.arp_ignore=1\nnet.ipv4.conf.default.arp_ignore=1\nnet.ipv4.conf.all.arp_announce=2\nnet.ipv4.conf.default.arp_announce=2\n', |
| '/etc/systemd/system/carlos-edge.service.d/60-hairpin.conf': '[Service]\nRestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK\nExecStartPre=+/usr/bin/systemctl start carlos-hairpin-reset.service\nExecStop=+/usr/bin/systemctl start carlos-hairpin-reset.service\nExecStopPost=+/usr/bin/systemctl start carlos-hairpin-reset.service\n', |
| '/etc/systemd/system/carlos-hairpin-reset.service': '[Unit]\nRequires=nftables.service\nAfter=nftables.service\n\n[Service]\nType=oneshot\nExecStart=/opt/carlos/carlos instance-control --group-hairpin-reset\nTimeoutStartSec=70\n', |
| - '/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf': '[Service]\nRestrictAddressFamilies=AF_UNIX AF_NETLINK\nReadWritePaths=/run/carlos-hairpin\n', |
| + '/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf': '[Service]\nRestrictAddressFamilies=AF_UNIX AF_NETLINK\nReadWritePaths=-/run/carlos-hairpin\n', |
| } |
| os.mkdir('/etc/systemd/system/carlos-instance-control.service.d', 0o755) |
| for path, body in files.items(): |
diff --git a/internal/hairpin/native_linux.go b/internal/hairpin/native_linux.go| index a66c6af1c..2fb9c409e 100644 |
| --- a/internal/hairpin/native_linux.go |
| +++ b/internal/hairpin/native_linux.go |
| @@ -260,7 +260,18 @@ func (l *Lease) Addresses(ctx context.Context, on bool) error { |
| if err != nil { |
| return err |
| } |
| - return l.CheckAddresses(ctx, false) |
| + if err := l.CheckAddresses(ctx, false); err != nil { |
| + return err |
| + } |
| + raw, err := run(ctx, "", "ip", "-j", "-4", "route", "show", "table", "local", "dev", Interface) |
| + if err != nil { |
| + return err |
| + } |
| + var routes []json.RawMessage |
| + if json.Unmarshal(raw, &routes) != nil || routes == nil || len(routes) != 0 { |
| + return fmt.Errorf("%w: local routes remain or route inventory invalid", ErrConfig) |
| + } |
| + return nil |
| } |
| for _, setting := range []struct{ name, value string }{{"arp_ignore", "1"}, {"arp_announce", "2"}} { |
| b, err := os.ReadFile(filepath.Join("/proc/sys/net/ipv4/conf/all", setting.name)) |
diff --git a/internal/hairpin/native_linux_test.go b/internal/hairpin/native_linux_test.go| index d43c54c82..029f38d3d 100644 |
| --- a/internal/hairpin/native_linux_test.go |
| +++ b/internal/hairpin/native_linux_test.go |
| @@ -72,3 +72,35 @@ func TestHairpinAddressReadback(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func TestHairpinRemovalChecksLocalRoutes(t *testing.T) { |
| + dir := t.TempDir() |
| + t.Setenv("PATH", dir) |
| + for _, tc := range []struct { |
| + name, routes string |
| + ok bool |
| + }{ |
| + {"empty", "[]", true}, |
| + {"surviving", `[{"type":"local","dst":"8.8.8.8","dev":"carlos-hairpin"}]`, false}, |
| + {"null", "null", false}, |
| + {"malformed", "[", false}, |
| + {"unreadable", "ERROR", false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + script := `#!/bin/sh |
| +case "$*" in |
| + '-j -d link show') echo '[{"ifname":"carlos-hairpin","linkinfo":{"info_kind":"dummy"}}]' ;; |
| + '-4 addr flush dev carlos-hairpin') ;; |
| + '-j -4 addr show dev carlos-hairpin') echo '[]' ;; |
| + '-j -4 route show table local dev carlos-hairpin') |
| +` + "[ '" + tc.routes + "' != ERROR ] || exit 1\necho '" + tc.routes + "'\n;;\n*) exit 2 ;;\nesac\n" |
| + if err := os.WriteFile(filepath.Join(dir, "ip"), []byte(script), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + err := (&Lease{Config: fixtureConfig()}).Addresses(t.Context(), false) |
| + if (err == nil) != tc.ok { |
| + t.Fatalf("removal with %s routes: %v", tc.name, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/host/group_hairpin_rootrunner_linux_test.go b/internal/host/group_hairpin_rootrunner_linux_test.go| index f17a91e3f..633164794 100644 |
| --- a/internal/host/group_hairpin_rootrunner_linux_test.go |
| +++ b/internal/host/group_hairpin_rootrunner_linux_test.go |
| @@ -20,6 +20,7 @@ import ( |
| "math/big" |
| "net" |
| "net/http" |
| + "net/netip" |
| "os" |
| "os/exec" |
| "path/filepath" |
| @@ -172,25 +173,19 @@ func hairpinKernelWitness(t *testing.T) { |
| hairpinCmd(t, "ip", "-6", "addr", "add", "fd42:ca:5::1/128", "dev", v6, "nodad") |
| hairpinCmd(t, "ip", "-6", "route", "add", "fd00:ec2::254/128", "dev", v6, "src", "fd42:ca:5::1") |
| } |
| - ctlLn, err := net.Listen("unix", controlsock.Path) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - if err = os.Chown(controlsock.Path, uid, gid); err != nil { |
| - t.Fatal(err) |
| - } |
| - if err = os.Chmod(controlsock.Path, 0600); err != nil { |
| - t.Fatal(err) |
| + controlUnit := hairpinControlUnit(t, payload, "TestHairpinControlPayload") |
| + hairpinRunnerUnit(t, "carlos-instance-control.service", controlUnit) |
| + hairpinCmd(t, "systemctl", "start", "carlos-instance-control.service") |
| + deadline := time.Now().Add(10 * time.Second) |
| + for { |
| + if _, err := os.Stat(controlsock.Path); err == nil { |
| + break |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatal("control service not ready", egressJournal("carlos-instance-control.service")) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| } |
| - srv := &instancectl.Server{PeerOK: func(net.Conn) error { return nil }, LocalAddrs: instancectl.LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| - out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| - return string(out), err |
| - }, Logf: t.Logf} |
| - serving, cancelServing := context.WithCancel(context.Background()) |
| - defer cancelServing() |
| - ctlDone := make(chan error, 1) |
| - go func() { ctlDone <- srv.Serve(serving, ctlLn) }() |
| - t.Cleanup(func() { cancelServing(); ctlLn.Close(); <-ctlDone }) |
| // An app backend observes what the real edge derived, including through an |
| // upgrade. It never trusts the caller's forwarding headers. |
| backend, err := net.Listen("unix", "/run/carlos/hairpin-app.sock") |
| @@ -348,37 +343,8 @@ func hairpinKernelWitness(t *testing.T) { |
| } |
| // Fail after the kernel has made both EIPs local. The production operation |
| // must remove them, restore plain #367 denial, and retain the IMDS table. |
| - l, err := hairpin.Acquire(ctx) |
| - if err != nil || l == nil { |
| - t.Fatal("rollback lock", err) |
| - } |
| - plainDeny := func(ctx context.Context, on bool) error { |
| - local, err := instancectl.LocalAddresses() |
| - if err != nil { |
| - return err |
| - } |
| - var values []string |
| - for _, p := range local { |
| - if on && p.IsSingleIP() && slices.Contains(config.PublicIPs, p.Addr().String()) { |
| - continue |
| - } |
| - values = append(values, p.String()) |
| - } |
| - slices.Sort(values) |
| - _, err = exec.CommandContext(ctx, "systemctl", "set-property", "--runtime", parent, "IPAddressDeny=", "IPAddressDeny="+strings.Join(values, " ")).CombinedOutput() |
| - return err |
| - } |
| - ops := hairpin.Operations{Install: l.Install, Verify: l.Verify, Addresses: l.Addresses, Exempt: plainDeny, Save: func(on bool) error { |
| - if on { |
| - return errors.New("injected post-assignment save failure") |
| - } |
| - return l.Save(hairpin.State{Process: l.State.Process, Closed: true}) |
| - }} |
| - rollbackErr := ops.Enable(ctx) |
| - l.Close() |
| - if rollbackErr == nil { |
| - t.Fatal("injected failure accepted") |
| - } |
| + hairpinRunnerUnit(t, "carlos-hairpin-rollback.service", hairpinControlUnit(t, payload, "TestHairpinRollbackPayload")+"\n[Service]\nType=oneshot\n") |
| + hairpinCmd(t, "systemctl", "start", "carlos-hairpin-rollback.service") |
| hairpinAssertEmpty(t) |
| if got := hairpinCmd(t, "nft", "-s", "list", "table", "inet", "carlos_group_imds"); got != imdsBefore { |
| t.Fatal("rollback touched IMDS table") |
| @@ -581,7 +547,7 @@ func hairpinAgentCall(t *testing.T, c *http.Client, path string) { |
| defer resp.Body.Close() |
| body, _ := io.ReadAll(resp.Body) |
| if resp.StatusCode != 200 { |
| - t.Fatalf("agent %s: %d %s\n%s", path, resp.StatusCode, body, egressJournal(agentUnit)) |
| + t.Fatalf("agent %s: %d %s\n%s\n%s", path, resp.StatusCode, body, egressJournal(agentUnit), egressJournal("carlos-instance-control.service")) |
| } |
| } |
| @@ -838,6 +804,23 @@ func hairpinExternalAndARP(t *testing.T, payload string, c hairpin.Config) { |
| hairpinCmd(t, "ip", "-n", ns, "link", "set", peer, "up") |
| hairpinCmd(t, "ip", "-n", ns, "link", "set", "lo", "up") |
| hairpinCmd(t, "ip", "-n", ns, "route", "add", "default", "via", "172.30.0.1") |
| + const external = "198.18.0.2" |
| + local, err := instancectl.LocalAddresses() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range local { |
| + if p.Contains(netip.MustParseAddr(external)) { |
| + t.Fatal("external peer is box-local", p) |
| + } |
| + } |
| + if out := hairpinCmd(t, "ip", "route", "show", "exact", external+"/32"); strings.TrimSpace(out) != "" { |
| + t.Fatal("external peer route exists", out) |
| + } |
| + hairpinCmd(t, "ip", "-n", ns, "addr", "add", external+"/32", "dev", "lo") |
| + hairpinCmd(t, "ip", "route", "add", external+"/32", "via", "172.30.0.2", "dev", host) |
| + defer exec.Command("ip", "route", "del", external+"/32").Run() |
| + |
| cmd := exec.Command("ip", "netns", "exec", ns, payload, "-test.run=^TestHairpinExternalPayload$", "-test.v", "-test.timeout=15s") |
| cmd.Env = append(os.Environ(), "HAIRPIN_EXTERNAL=1", "HAIRPIN_PRIMARY="+c.PrimaryIPv4) |
| if out, err := cmd.CombinedOutput(); err != nil { |
| @@ -853,17 +836,19 @@ func TestHairpinExternalPayload(t *testing.T) { |
| } |
| for _, ip := range []string{"8.8.8.8", "9.9.9.9"} { |
| for _, port := range []string{"80", "443"} { |
| - conn, err := net.DialTimeout("tcp", net.JoinHostPort(ip, port), time.Second) |
| + dialer := net.Dialer{Timeout: time.Second, LocalAddr: &net.TCPAddr{IP: net.ParseIP("198.18.0.2")}} |
| + conn, err := dialer.Dial("tcp", net.JoinHostPort(ip, port)) |
| if err != nil { |
| - continue |
| + t.Fatalf("external peer did not reach %s:%s: %v", ip, port, err) |
| } |
| - conn.SetDeadline(time.Now().Add(time.Second)) |
| - fmt.Fprint(conn, "GET / HTTP/1.1\r\nHost: hairpin.test\r\nX-Carlos-Hairpin: 1\r\n\r\n") |
| - _, err = http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "GET"}) |
| + conn.SetReadDeadline(time.Now().Add(time.Second)) |
| + var b [1]byte |
| + n, err := conn.Read(b[:]) |
| conn.Close() |
| - if err == nil { |
| - t.Fatal("EIP-local connection accepted from a non-local peer", ip, port) |
| + if n != 0 || !(errors.Is(err, io.EOF) || errors.Is(err, unix.ECONNRESET)) { |
| + t.Fatalf("EIP-local connection not closed at accept from non-local peer %s:%s: bytes=%d err=%v", ip, port, n, err) |
| } |
| + |
| } |
| hairpinARPRefused(t, ip) |
| } |
| @@ -939,10 +924,104 @@ func hairpinARPRefused(t *testing.T, target string) { |
| } |
| // The installed reset unit executes this binary through the same bounded root |
| -// entry point as production, independently of the test's in-process server. |
| +// entry point as production, independently of the control service fixture. |
| func init() { |
| if len(os.Args) == 3 && os.Args[1] == "instance-control" && os.Args[2] == "--group-hairpin-reset" { |
| RunInstanceControl(os.Args[2:]) |
| os.Exit(0) |
| } |
| } |
| + |
| +func hairpinControlUnit(t *testing.T, payload, test string) string { |
| + t.Helper() |
| + base, err := unitsFS.ReadFile("units/carlos-instance-control.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var lines []string |
| + for _, line := range strings.Split(string(base), "\n") { |
| + // Socket activation and instance mounts are supplied by this fixture. |
| + // Every Service hardening directive is retained byte for byte. |
| + if strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") { |
| + continue |
| + } |
| + if strings.HasPrefix(line, "ExecStart=") { |
| + line = "ExecStart=" + payload + " -test.run=^" + test + "$ -test.v -test.timeout=4m" |
| + } |
| + lines = append(lines, line) |
| + } |
| + return strings.Join(lines, "\n") + "\n" + hairpinControlDropIn + "Environment=HAIRPIN_CONTROL=1\n" |
| +} |
| + |
| +func TestHairpinControlPayload(t *testing.T) { |
| + if os.Getenv("HAIRPIN_CONTROL") != "1" { |
| + t.Fatal("fixture-only payload") |
| + } |
| + uid, gid := generationRunnerRegistryUser(t) |
| + ctlLn, err := net.Listen("unix", controlsock.Path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.Chown(controlsock.Path, uid, gid); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = os.Chmod(controlsock.Path, 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &instancectl.Server{PeerOK: func(net.Conn) error { return nil }, LocalAddrs: instancectl.LocalAddresses, Systemctl: func(ctx context.Context, args ...string) (string, error) { |
| + out, err := exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() |
| + return string(out), err |
| + }, Logf: t.Logf} |
| + |
| + defer ctlLn.Close() |
| + if err := srv.Serve(t.Context(), ctlLn); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestHairpinRollbackPayload(t *testing.T) { |
| + if os.Getenv("HAIRPIN_CONTROL") != "1" { |
| + t.Fatal("fixture-only payload") |
| + } |
| + ctx, cancel := context.WithTimeout(t.Context(), 60*time.Second) |
| + defer cancel() |
| + config, err := hairpin.Load() |
| + if err != nil || config == nil { |
| + t.Fatal(err) |
| + } |
| + parent := instancectl.InstancesSlice |
| + l, err := hairpin.Acquire(ctx) |
| + if err != nil || l == nil { |
| + t.Fatal("rollback lock", err) |
| + } |
| + plainDeny := func(ctx context.Context, on bool) error { |
| + local, err := instancectl.LocalAddresses() |
| + if err != nil { |
| + return err |
| + } |
| + var values []string |
| + for _, p := range local { |
| + if on && p.IsSingleIP() && slices.Contains(config.PublicIPs, p.Addr().String()) { |
| + continue |
| + } |
| + values = append(values, p.String()) |
| + } |
| + slices.Sort(values) |
| + _, err = exec.CommandContext(ctx, "systemctl", "set-property", "--runtime", parent, "IPAddressDeny=", "IPAddressDeny="+strings.Join(values, " ")).CombinedOutput() |
| + 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 { |
| + if on { |
| + return injected |
| + } |
| + return l.Save(hairpin.State{Process: l.State.Process, Closed: true}) |
| + }} |
| + rollbackErr := ops.Enable(ctx) |
| + l.Close() |
| + if !errors.Is(rollbackErr, injected) { |
| + t.Fatal("rollback did not reach post-assignment failure", rollbackErr) |
| + } |
| + |
| + hairpinAssertEmpty(t) |
| +} |
diff --git a/internal/host/group_hairpin_test.go b/internal/host/group_hairpin_test.go| index c52c088f1..34d9278a3 100644 |
| --- a/internal/host/group_hairpin_test.go |
| +++ b/internal/host/group_hairpin_test.go |
| @@ -3,6 +3,8 @@ package host |
| import ( |
| "context" |
| "github.com/carlosframework/platform/internal/groupadmission" |
| + "os" |
| + "strings" |
| "sync/atomic" |
| "testing" |
| "time" |
| @@ -90,3 +92,23 @@ func TestHairpinCloseCancelsWorkBeforeRoot(t *testing.T) { |
| t.Fatal("departure work remained live while root removal blocked") |
| } |
| } |
| + |
| +const hairpinControlDropIn = "[Service]\nRestrictAddressFamilies=AF_UNIX AF_NETLINK\nReadWritePaths=-/run/carlos-hairpin\n" |
| + |
| +func TestHairpinControlGroupDropIn(t *testing.T) { |
| + raw, err := os.ReadFile("../../infra/modules/region-host/group-init.sh.tftpl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := "'/etc/systemd/system/carlos-instance-control.service.d/60-hairpin.conf': '" + strings.ReplaceAll(hairpinControlDropIn, "\n", `\n`) + "'" |
| + if !strings.Contains(string(raw), want) { |
| + t.Fatal("group control drop-in must allow netlink and an optional runtime directory") |
| + } |
| + base, err := unitsFS.ReadFile("units/carlos-instance-control.service") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if strings.Contains(string(base), "carlos-hairpin") || strings.Contains(string(base), "AF_NETLINK") { |
| + t.Fatal("group hairpin hardening escaped into fixed unit") |
| + } |
| +} |
diff --git a/internal/instancectl/hairpin_refresh_linux_test.go b/internal/instancectl/hairpin_refresh_linux_test.go| new file mode 100644 |
| index 000000000..318b0eb7e |
| --- /dev/null |
| +++ b/internal/instancectl/hairpin_refresh_linux_test.go |
| @@ -0,0 +1,97 @@ |
| +//go:build linux |
| + |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/hairpin" |
| +) |
| + |
| +func TestHairpinDenyRefreshOnlyChanges(t *testing.T) { |
| + dir := t.TempDir() |
| + t.Setenv("PATH", dir) |
| + c := 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: "12345678-1234-1234-1234-123456789abc", Account: "123456789012", InstanceID: "i-0123456789abcdef0"} |
| + rules, err := c.Rules() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + write := func(name, body string) { |
| + t.Helper() |
| + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + write("nft", "#!/bin/sh\necho checked >> '"+filepath.Join(dir, "checks")+"'\n/bin/cat <<'RULES'\n"+rules+"\nRULES\n") |
| + write("ip", `#!/bin/sh |
| +case "$*" in |
| + '-j -4 addr show dev carlos-hairpin') echo '[{"addr_info":[{"local":"8.8.8.8","prefixlen":32},{"local":"9.9.9.9","prefixlen":32}]}]' ;; |
| + '-j -d link show') echo '[{"ifname":"carlos-hairpin","linkinfo":{"info_kind":"dummy"}}]' ;; |
| + '-4 addr flush dev carlos-hairpin') ;; |
| + '-j -4 route show table local dev carlos-hairpin') echo '[]' ;; |
| + *) exit 2 ;; |
| +esac |
| +`) |
| + local := parsePrefixes("172.31.7.19/32", "8.8.8.8/32", "9.9.9.9/32") |
| + ctl := &fakeCtl{} |
| + s := &Server{Systemctl: ctl.run, Logf: t.Logf, LocalAddrs: func() ([]netip.Prefix, error) { return local, nil }} |
| + l := &hairpin.Lease{Config: c, State: hairpin.State{Active: true}} |
| + ctx := context.WithValue(t.Context(), hairpinLeaseKey{}, l) |
| + // The loop must still verify active state when the effective deny is unchanged. |
| + ticks := make(chan time.Time, 3) |
| + for range 3 { |
| + ticks <- time.Time{} |
| + } |
| + loopCtx, cancel := context.WithCancel(ctx) |
| + defer cancel() |
| + n := 0 |
| + s.denyLoopWith(loopCtx, ticks, func() { |
| + n++ |
| + if n == 3 { |
| + cancel() |
| + } |
| + }) |
| + if got := ctl.count("set-property"); got != 1 { |
| + t.Errorf("unchanged active deny applied %d times, want 1", got) |
| + } |
| + if b, err := os.ReadFile(filepath.Join(dir, "checks")); err != nil || string(b) != "checked\nchecked\nchecked\n" { |
| + t.Errorf("active readbacks: %q %v", b, err) |
| + } |
| + // Even if the last applied deny already equals the full local set, a failed |
| + // readback must reapply it and return the refusal. |
| + s.lastDeny = denySet(local) |
| + write("nft", "#!/bin/sh\nexit 1\n") |
| + before := ctl.count("set-property") |
| + if err := s.denyLocalAddrs(ctx); err == nil { |
| + t.Fatal("failed verification accepted") |
| + } |
| + if ctl.count("set-property") != before+1 { |
| + t.Fatal("failed verification did not restore full deny") |
| + } |
| + if l.State.Active { |
| + t.Fatal("failed verification retained active state") |
| + } |
| + // Inactive and unchanged: no systemctl or command readback work on a tick. |
| + before = ctl.count("set-property") |
| + if err := s.denyLocalAddrs(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.denyLocalAddrs(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ctl.count("set-property") != before { |
| + t.Error("unchanged inactive deny was applied") |
| + } |
| + local = append(local, netip.MustParsePrefix("2001:db8::1/128")) |
| + if err := s.denyLocalAddrs(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ctl.count("set-property") != before+1 { |
| + t.Error("changed deny was not applied") |
| + } |
| +} |
diff --git a/internal/instancectl/hardening.go b/internal/instancectl/hardening.go| index 95498102a..dab1a5430 100644 |
| --- a/internal/instancectl/hardening.go |
| +++ b/internal/instancectl/hardening.go |
| @@ -16,6 +16,7 @@ import ( |
| "strings" |
| "time" |
| + "github.com/carlosframework/platform/internal/hairpin" |
| "github.com/carlosframework/platform/internal/provision" |
| ) |
| @@ -306,6 +307,15 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| if len(deny) == 0 { |
| return errors.New("this box's addresses: none read; the last deny stands") |
| } |
| + l, group := ctx.Value(hairpinLeaseKey{}).(*hairpin.Lease) |
| + s.mu.Lock() |
| + unchanged := slices.Equal(deny, s.lastDeny) |
| + if group && unchanged && hairpinErr == nil { |
| + s.hairpinActive = l.State.Active |
| + s.mu.Unlock() |
| + return nil |
| + } |
| + s.mu.Unlock() |
| rendered := make([]string, len(deny)) |
| for i, p := range deny { |
| rendered[i] = p.String() |
| @@ -316,6 +326,7 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| } |
| s.mu.Lock() |
| s.lastDeny = deny |
| + s.hairpinActive = group && l.State.Active |
| s.mu.Unlock() |
| return hairpinErr |
| } |
| @@ -379,8 +390,9 @@ func (s *Server) denyLoopWith(ctx context.Context, ticks <-chan time.Time, done |
| s.mu.Lock() |
| previous := slices.Clone(s.lastDeny) |
| unchanged := slices.Equal(denySet(local), previous) |
| + active := s.hairpinActive |
| s.mu.Unlock() |
| - if !unchanged || groupHairpinMarker() { |
| + if !unchanged || active { |
| err := s.denyLocalAddrs(ctx) |
| logErr(err) |
| if err == nil { |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index 3e8592848..90da0756c 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -206,7 +206,8 @@ type Server struct { |
| probed bool |
| // lastDeny is the box-address deny denyLocalAddrs last applied, sorted |
| // and deduplicated (denySet); denyLoop compares a fresh read with it. |
| - lastDeny []netip.Prefix |
| + lastDeny []netip.Prefix |
| + hairpinActive bool |
| // 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 |