Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(egress): bound Fast Sandbox DNS nft updates
leo peinb53cfc764c26
diff --git a/components/egress/fastsandbox_policy_relay_test.go b/components/egress/fastsandbox_policy_relay_test.goindex 69dade440..989fb784d 100644--- a/components/egress/fastsandbox_policy_relay_test.go+++ b/components/egress/fastsandbox_policy_relay_test.go@@ -413,7 +413,7 @@ func TestRelayPutRacingRebindNeverActivatesPredecessorPolicy(t *testing.T) {reg := subject.NewRegistry(nil, nil)hnft := &hookNft{}srv := newFastSandboxPolicyServer(context.Background(), reg, hnft)- srv.dnsRedirectApply = func([]netip.Addr, int) error { return nil }+ srv.dnsRedirectApply = func(context.Context, []netip.Addr, int) error { return nil }pp, err := newPolicyPersistence(t.TempDir())require.NoError(t, err)files := make(map[string]*fakeVaultFile)diff --git a/components/egress/fastsandbox_server.go b/components/egress/fastsandbox_server.goindex 8563fd7bb..e0db804c9 100644--- a/components/egress/fastsandbox_server.go+++ b/components/egress/fastsandbox_server.go@@ -117,7 +117,7 @@ type fastSandboxPolicyServer struct {// ownership for a later lifecycle retry. gwMu serializes map/table updates.gwMu sync.MutexgatewayDNSRefs map[subject.Subject]netip.Addr- dnsRedirectApply func(gateways []netip.Addr, port int) error+ dnsRedirectApply func(ctx context.Context, gateways []netip.Addr, port int) error// mitmMu guards the per-subject interception entries; the Pod-netns table// is rebuilt wholesale from this map on every change (see@@ -200,12 +200,12 @@ const policyApplyTimeout = 10 * time.Second// reconcile, including duplicate delivery: a prior command may have applied// but returned an ambiguous error. Fails closed: a subject whose DNS cannot// reach the proxy must not register as usable.-func (s *fastSandboxPolicyServer) installGatewayDNSRedirect(subj subject.Subject, gateway netip.Addr) error {+func (s *fastSandboxPolicyServer) installGatewayDNSRedirect(ctx context.Context, subj subject.Subject, gateway netip.Addr) error {s.gwMu.Lock()defer s.gwMu.Unlock()next := cloneGatewayDNSRefs(s.gatewayDNSRefs)next[subj] = gateway.Unmap()- if err := s.reconcileGatewayDNSRedirectsLocked(next); err != nil {+ if err := s.reconcileGatewayDNSRedirectsLocked(ctx, next); err != nil {return fmt.Errorf("gateway DNS redirect install: %w", err)}s.gatewayDNSRefs = next@@ -216,12 +216,12 @@ func (s *fastSandboxPolicyServer) installGatewayDNSRedirect(subj subject.Subject// set even when the subject is absent. A previous apply may have succeeded// while its result was lost, leaving no committed map entry to drive cleanup.// On failure, retain the old map for a retry.-func (s *fastSandboxPolicyServer) releaseGatewayDNSRedirect(subj subject.Subject) error {+func (s *fastSandboxPolicyServer) releaseGatewayDNSRedirect(ctx context.Context, subj subject.Subject) error {s.gwMu.Lock()defer s.gwMu.Unlock()next := cloneGatewayDNSRefs(s.gatewayDNSRefs)delete(next, subj)- if err := s.reconcileGatewayDNSRedirectsLocked(next); err != nil {+ if err := s.reconcileGatewayDNSRedirectsLocked(ctx, next); err != nil {return fmt.Errorf("gateway DNS redirect release: %w", err)}s.gatewayDNSRefs = next@@ -231,7 +231,7 @@ func (s *fastSandboxPolicyServer) releaseGatewayDNSRedirect(subj subject.Subject// reconcileGatewayDNSRedirectsLocked derives a normalized gateway set from// the staged subject map. Callers hold gwMu; the applier atomically replaces// the table and treats an empty set as removal of the table.-func (s *fastSandboxPolicyServer) reconcileGatewayDNSRedirectsLocked(refs map[subject.Subject]netip.Addr) error {+func (s *fastSandboxPolicyServer) reconcileGatewayDNSRedirectsLocked(ctx context.Context, refs map[subject.Subject]netip.Addr) error {if s.dnsRedirectApply == nil {return nil}@@ -243,7 +243,7 @@ func (s *fastSandboxPolicyServer) reconcileGatewayDNSRedirectsLocked(refs map[sufor gateway := range set {gateways = append(gateways, gateway)}- return s.dnsRedirectApply(gateways, fastSandboxDNSProxyPort)+ return s.dnsRedirectApply(ctx, gateways, fastSandboxDNSProxyPort)}func cloneGatewayDNSRefs(refs map[subject.Subject]netip.Addr) map[subject.Subject]netip.Addr {@@ -482,7 +482,7 @@ func (s *fastSandboxPolicyServer) OnRegistered(subj subject.Subject, att actionhreturn err}dnsStarted := time.Now()- if err := s.installGatewayDNSRedirect(subj, att.Gateway); err != nil {+ if err := s.installGatewayDNSRedirect(nftCtx, subj, att.Gateway); err != nil {// Fail closed: sandbox DNS addressed to gateway:53 must reach the// proxy; without the redirect the sandbox would fall back to a// resolver the policy cannot see.@@ -496,7 +496,7 @@ func (s *fastSandboxPolicyServer) OnRegistered(subj subject.Subject, att actionh// traffic the MITM layer is responsible for). Roll back the gateway// DNS redirect installed above — the caller retries OnRegistered,// and an unreleased mapping would keep the gateway redirect forever.- if rollbackErr := s.releaseGatewayDNSRedirect(subj); rollbackErr != nil {+ if rollbackErr := s.releaseGatewayDNSRedirect(nftCtx, subj); rollbackErr != nil {return fmt.Errorf("mitm redirect: %w (DNS rollback failed: %v)", err, rollbackErr)}return err@@ -564,7 +564,7 @@ func (s *fastSandboxPolicyServer) unloadEnforcement(subj subject.Subject) errorif err := s.nft.Remove(nftCtx, subj); err != nil {return err}- if err := s.releaseGatewayDNSRedirect(subj); err != nil {+ if err := s.releaseGatewayDNSRedirect(nftCtx, subj); err != nil {return err}s.removeMitmRedirect(subj)diff --git a/components/egress/fastsandbox_server_test.go b/components/egress/fastsandbox_server_test.goindex d86377eff..0993cfeeb 100644--- a/components/egress/fastsandbox_server_test.go+++ b/components/egress/fastsandbox_server_test.go@@ -25,6 +25,7 @@ import ("net/netip""sync""testing"+ "time""github.com/stretchr/testify/assert""github.com/stretchr/testify/require"@@ -65,7 +66,7 @@ func newFakeGatewayDNSRedirectApplier() *fakeGatewayDNSRedirectApplier {return &fakeGatewayDNSRedirectApplier{gateways: make(map[netip.Addr]struct{})}}-func (f *fakeGatewayDNSRedirectApplier) apply(gateways []netip.Addr, _ int) error {+func (f *fakeGatewayDNSRedirectApplier) apply(_ context.Context, gateways []netip.Addr, _ int) error {f.calls++fail := f.calls == f.failAtif fail && !f.applyThenFail {@@ -140,7 +141,7 @@ func fastSandboxTestServer(t *testing.T) (*fastSandboxPolicyServer, *subject.Memnft := &fakeNft{}srv := newFastSandboxPolicyServer(context.Background(), reg, nft)// no-op the gateway DNS redirect (no iptables/nft in unit tests)- srv.dnsRedirectApply = func([]netip.Addr, int) error { return nil }+ srv.dnsRedirectApply = func(context.Context, []netip.Addr, int) error { return nil }// Policy persistence is REQUIRED in the fast-sandbox profile — every// test server carries a store, mirroring the production posture (no// memory-only mode). The file seam defaults to a cross-platform fake@@ -1137,7 +1138,7 @@ func TestFastSandboxServerAlwaysRulesReachNft(t *testing.T) {nft := &fakeNft{}srv := newFastSandboxPolicyServer(context.Background(), reg, nft)wireTestPolicyPersistence(t, srv)- srv.dnsRedirectApply = func([]netip.Addr, int) error { return nil }+ srv.dnsRedirectApply = func(context.Context, []netip.Addr, int) error { return nil }// activation through the action protocol; the binding policy reaches nft// merged with the always overlay@@ -1228,19 +1229,41 @@ func TestFastSandboxServerGatewayRedirectRefcounted(t *testing.T) {assert.Empty(t, dns.snapshot(), "the final release removes the DNS table contents")}+func TestFastSandboxServerGatewayRedirectUsesLifecycleDeadline(t *testing.T) {+ srv, _, _ := fastSandboxTestServer(t)+ var contexts []context.Context+ srv.dnsRedirectApply = func(ctx context.Context, _ []netip.Addr, _ int) error {+ contexts = append(contexts, ctx)+ return nil+ }+ subj := subject.FromSandboxUID("dns-context")+ att := mitmAtt(t, "10.0.0.5", "10.10.0.1")++ require.NoError(t, srv.OnRegistered(subj, att))+ require.NoError(t, srv.OnUnloaded(subj, att))+ require.Len(t, contexts, 2)+ for i, maxTimeout := range []time.Duration{policyApplyTimeout, 30 * time.Second} {+ deadline, ok := contexts[i].Deadline()+ require.True(t, ok, "lifecycle operation %d must have a deadline", i)+ remaining := time.Until(deadline)+ assert.Positive(t, remaining, "lifecycle context should still be within its deadline")+ assert.LessOrEqual(t, remaining, maxTimeout, "lifecycle context must preserve its existing timeout")+ }+}+func TestFastSandboxServerReleaseCleansUncommittedInstallAfterLostResult(t *testing.T) {srv, _, _ := fastSandboxTestServer(t)dns := newFakeGatewayDNSRedirectApplier()srv.dnsRedirectApply = dns.applysubj, gw := subject.FromSandboxUID("uncommitted"), netip.MustParseAddr("10.10.0.1")dns.failOnCall(1, errors.New("result lost"), true)- require.Error(t, srv.installGatewayDNSRedirect(subj, gw))+ require.Error(t, srv.installGatewayDNSRedirect(context.Background(), subj, gw))srv.gwMu.Lock()assert.Empty(t, srv.gatewayDNSRefs)srv.gwMu.Unlock()assert.Equal(t, map[netip.Addr]struct{}{gw: {}}, dns.snapshot())- require.NoError(t, srv.releaseGatewayDNSRedirect(subj))+ require.NoError(t, srv.releaseGatewayDNSRedirect(context.Background(), subj))assert.Empty(t, dns.snapshot(), "release reconciles even though install ownership was not committed")}diff --git a/components/egress/fastsandbox_transition_rules_test.go b/components/egress/fastsandbox_transition_rules_test.goindex d855cf296..69043cf16 100644--- a/components/egress/fastsandbox_transition_rules_test.go+++ b/components/egress/fastsandbox_transition_rules_test.go@@ -72,7 +72,9 @@ func TestTransitionChangedIPRebuildRemovesCumulativeOldDispatch(t *testing.T) {srv.nft = fastsandboxnft.NewApplier(model.run, fastsandboxnft.Options{MitmRedirectPort: 18080})subj := subject.FromSandboxUID(testUID)if unknownAfterPartialInstall {- srv.dnsRedirectApply = func([]netip.Addr, int) error { return errors.New("gateway redirect failure after nft install") }+ srv.dnsRedirectApply = func(context.Context, []netip.Addr, int) error {+ return errors.New("gateway redirect failure after nft install")+ }}initial := doAction(t, srv, bindBody(t, testUID, testIP, testFenceR, testFenceA, 1, vaultAllowPolicy()))if unknownAfterPartialInstall {@@ -82,7 +84,7 @@ func TestTransitionChangedIPRebuildRemovesCumulativeOldDispatch(t *testing.T) {srv.mu.Lock()delete(srv.subjAtt, subj)srv.mu.Unlock()- srv.dnsRedirectApply = func([]netip.Addr, int) error { return nil }+ srv.dnsRedirectApply = func(context.Context, []netip.Addr, int) error { return nil }} else {require.Equal(t, http.StatusOK, initial.Code)require.Equal(t, http.StatusOK, doAction(t, srv, hookBody(t, testUID, testFenceR, testFenceA, constants.HookDataPlaneReady)).Code)diff --git a/components/egress/pkg/iptables/gateway_dns.go b/components/egress/pkg/iptables/gateway_dns.goindex dac74d750..738b6d125 100644--- a/components/egress/pkg/iptables/gateway_dns.go+++ b/components/egress/pkg/iptables/gateway_dns.go@@ -36,14 +36,14 @@ const gatewayDNSNftTable = "opensandbox_gateway_dns"// shared table. Empty gateways means remove the table; addresses are// normalized and deduplicated before rendering so mapped IPv4 values cannot// create a second spelling of the same gateway.-func gatewayDNSRedirectScript(gateways []netip.Addr, port int) (string, error) {+func gatewayDNSRedirectScript(gateways []netip.Addr, port int) (string, int, error) {if port <= 0 {- return "", fmt.Errorf("gateway DNS redirect: invalid port %d", port)+ return "", 0, fmt.Errorf("gateway DNS redirect: invalid port %d", port)}unique := make(map[netip.Addr]struct{}, len(gateways))for _, gateway := range gateways {if !gateway.IsValid() {- return "", fmt.Errorf("gateway DNS redirect: invalid gateway %s", gateway)+ return "", 0, fmt.Errorf("gateway DNS redirect: invalid gateway %s", gateway)}unique[gateway.Unmap()] = struct{}{}}@@ -56,7 +56,7 @@ func gatewayDNSRedirectScript(gateways []netip.Addr, port int) (string, error) {var b strings.Builderfmt.Fprintf(&b, "delete table inet %s\n", gatewayDNSNftTable)if len(normalized) == 0 {- return b.String(), nil+ return b.String(), len(normalized), nil}fmt.Fprintf(&b, "add table inet %s\n", gatewayDNSNftTable)fmt.Fprintf(&b, "add chain inet %s gw { type nat hook prerouting priority dstnat; }\n", gatewayDNSNftTable)@@ -68,24 +68,27 @@ func gatewayDNSRedirectScript(gateways []netip.Addr, port int) (string, error) {fmt.Fprintf(&b, "add rule inet %s gw %s daddr %s udp dport 53 redirect to :%d\n", gatewayDNSNftTable, family, addr, port)fmt.Fprintf(&b, "add rule inet %s gw %s daddr %s tcp dport 53 redirect to :%d\n", gatewayDNSNftTable, family, addr, port)}- return b.String(), nil+ return b.String(), len(normalized), nil}// ReplaceGatewayDNSRedirects atomically replaces the shared prerouting// redirect table with exactly the supplied gateway set. Callers own the// subject-to-gateway map and must retain it for a retry when this returns an// error; an ambiguous command result does not prove the old table is live.-func ReplaceGatewayDNSRedirects(gateways []netip.Addr, port int) error {- return replaceGatewayDNSRedirects(defaultRedirectRunner(), gateways, port)+func ReplaceGatewayDNSRedirects(ctx context.Context, gateways []netip.Addr, port int) error {+ return replaceGatewayDNSRedirects(ctx, defaultRedirectRunner(), gateways, port)}-func replaceGatewayDNSRedirects(r redirectRunner, gateways []netip.Addr, port int) error {- script, err := gatewayDNSRedirectScript(gateways, port)+func replaceGatewayDNSRedirects(ctx context.Context, r redirectRunner, gateways []netip.Addr, port int) error {+ script, uniqueGatewayCount, err := gatewayDNSRedirectScript(gateways, port)if err != nil {return err}- out, err := r.runNft(context.Background(), script)+ out, err := r.runNft(ctx, script)if err != nil {+ if ctxErr := ctx.Err(); ctxErr != nil {+ return fmt.Errorf("gateway DNS redirect replace: %w (output: %s)", ctxErr, strings.TrimSpace(string(out)))+ }if !isNftMissingTableErrorFor(out, err, gatewayDNSNftTable) {return fmt.Errorf("gateway DNS redirect replace: %w (output: %s)", err, strings.TrimSpace(string(out)))}@@ -93,11 +96,14 @@ func replaceGatewayDNSRedirects(r redirectRunner, gateways []netip.Addr, port inreturn nil}retryScript := removeNftDeleteTableLineFor(script, gatewayDNSNftTable)- retryOut, retryErr := r.runNft(context.Background(), retryScript)+ retryOut, retryErr := r.runNft(ctx, retryScript)if retryErr != nil {+ if ctxErr := ctx.Err(); ctxErr != nil {+ return fmt.Errorf("gateway DNS redirect replace retry: %w (output: %s)", ctxErr, strings.TrimSpace(string(retryOut)))+ }return fmt.Errorf("gateway DNS redirect replace retry: %w (output: %s)", retryErr, strings.TrimSpace(string(retryOut)))}}- log.Infof("gateway DNS redirects replaced (%d gateway input(s) -> :%d)", len(gateways), port)+ log.Infof("gateway DNS redirects replaced (%d unique gateway(s) -> :%d)", uniqueGatewayCount, port)return nil}diff --git a/components/egress/pkg/iptables/gateway_dns_linux_test.go b/components/egress/pkg/iptables/gateway_dns_linux_test.goindex b2607c212..7c0185f9a 100644--- a/components/egress/pkg/iptables/gateway_dns_linux_test.go+++ b/components/egress/pkg/iptables/gateway_dns_linux_test.go@@ -76,7 +76,7 @@ func TestGatewayDNSRedirectKernelPrivateNS(t *testing.T) {assertGatewayDNSTableMissing(t, ctx)t.Cleanup(func() {- if err := ReplaceGatewayDNSRedirects(nil, 15353); err != nil {+ if err := ReplaceGatewayDNSRedirects(context.Background(), nil, 15353); err != nil {t.Errorf("remove gateway DNS test table during cleanup: %v", err)}})@@ -89,26 +89,26 @@ func TestGatewayDNSRedirectKernelPrivateNS(t *testing.T) {// The first real install begins with no table and exercises the production// missing-table retry, not just rule parsing in a fake runner.- require.NoError(t, ReplaceGatewayDNSRedirects([]netip.Addr{gw1}, 15353))+ require.NoError(t, ReplaceGatewayDNSRedirects(context.Background(), []netip.Addr{gw1}, 15353))assertGatewayDNSKernelRules(t, ctx, []netip.Addr{gw1})wantShared := []netip.Addr{gw1, gw1PrefixNeighbor, ipv6, gw1PrefixNeighbor, mappedGW1}- require.NoError(t, ReplaceGatewayDNSRedirects(wantShared, 15353))+ require.NoError(t, ReplaceGatewayDNSRedirects(context.Background(), wantShared, 15353))assertGatewayDNSKernelRules(t, ctx, wantShared)remaining := []netip.Addr{gw1PrefixNeighbor, ipv6}- require.NoError(t, ReplaceGatewayDNSRedirects(remaining, 15353))+ require.NoError(t, ReplaceGatewayDNSRedirects(context.Background(), remaining, 15353))assertGatewayDNSKernelRules(t, ctx, remaining)rebound := []netip.Addr{gw1PrefixNeighbor, gw3, ipv6}- require.NoError(t, ReplaceGatewayDNSRedirects(rebound, 15353))+ require.NoError(t, ReplaceGatewayDNSRedirects(context.Background(), rebound, 15353))assertGatewayDNSKernelRules(t, ctx, rebound)- require.NoError(t, ReplaceGatewayDNSRedirects(rebound, 15353), "replay of the same complete set")+ require.NoError(t, ReplaceGatewayDNSRedirects(context.Background(), rebound, 15353), "replay of the same complete set")assertGatewayDNSKernelRules(t, ctx, rebound)- require.NoError(t, ReplaceGatewayDNSRedirects(nil, 15353))+ require.NoError(t, ReplaceGatewayDNSRedirects(context.Background(), nil, 15353))assertGatewayDNSTableMissing(t, ctx)- require.NoError(t, ReplaceGatewayDNSRedirects(nil, 15353), "empty desired set is idempotent when the table is absent")+ require.NoError(t, ReplaceGatewayDNSRedirects(context.Background(), nil, 15353), "empty desired set is idempotent when the table is absent")assertGatewayDNSTableMissing(t, ctx)}diff --git a/components/egress/pkg/iptables/gateway_dns_test.go b/components/egress/pkg/iptables/gateway_dns_test.goindex f0dd70b82..1b60a3c72 100644--- a/components/egress/pkg/iptables/gateway_dns_test.go+++ b/components/egress/pkg/iptables/gateway_dns_test.go@@ -17,16 +17,20 @@ package iptablesimport ("context""errors"+ "fmt""net/netip""strings""testing"+ "time"+ egresslog "github.com/alibaba/opensandbox/egress/pkg/log"+ internallogger "github.com/alibaba/opensandbox/internal/logger""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")func TestGatewayDNSRedirectScriptExactIPv4IPv6Set(t *testing.T) {- script, err := gatewayDNSRedirectScript([]netip.Addr{+ script, uniqueGatewayCount, err := gatewayDNSRedirectScript([]netip.Addr{netip.MustParseAddr("10.0.0.10"),netip.MustParseAddr("10.0.0.1"),netip.MustParseAddr("::ffff:10.0.0.1"),@@ -36,6 +40,7 @@ func TestGatewayDNSRedirectScriptExactIPv4IPv6Set(t *testing.T) {require.NoError(t, err)require.Contains(t, script, "delete table inet "+gatewayDNSNftTable+"\nadd table inet "+gatewayDNSNftTable)require.Contains(t, script, "add chain inet "+gatewayDNSNftTable+" gw { type nat hook prerouting priority dstnat; }")+ assert.Equal(t, 3, uniqueGatewayCount, "five inputs normalize to three unique gateways")assert.Equal(t, 6, strings.Count(script, "add rule "), "three unique gateways each need UDP and TCP rules")assert.Contains(t, script, "ip daddr 10.0.0.1 udp dport 53 redirect to :15353")assert.Contains(t, script, "ip daddr 10.0.0.1 tcp dport 53 redirect to :15353")@@ -47,15 +52,16 @@ func TestGatewayDNSRedirectScriptExactIPv4IPv6Set(t *testing.T) {}func TestGatewayDNSRedirectScriptEmptySetAndValidation(t *testing.T) {- empty, err := gatewayDNSRedirectScript(nil, 15353)+ empty, uniqueGatewayCount, err := gatewayDNSRedirectScript(nil, 15353)require.NoError(t, err)+ assert.Equal(t, 0, uniqueGatewayCount)assert.Equal(t, "delete table inet "+gatewayDNSNftTable+"\n", empty)assert.Error(t, func() error {- _, err := gatewayDNSRedirectScript([]netip.Addr{netip.Addr{}}, 15353)+ _, _, err := gatewayDNSRedirectScript([]netip.Addr{netip.Addr{}}, 15353)return err}())assert.Error(t, func() error {- _, err := gatewayDNSRedirectScript(nil, 0)+ _, _, err := gatewayDNSRedirectScript(nil, 0)return err}())}@@ -70,7 +76,7 @@ func TestReplaceGatewayDNSRedirectsRetriesMissingTableWithoutDelete(t *testing.Treturn nil, nil}}- err := replaceGatewayDNSRedirects(r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353)+ err := replaceGatewayDNSRedirects(context.Background(), r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353)require.NoError(t, err)require.Len(t, scripts, 2)assert.Contains(t, scripts[0], "delete table inet "+gatewayDNSNftTable)@@ -79,6 +85,73 @@ func TestReplaceGatewayDNSRedirectsRetriesMissingTableWithoutDelete(t *testing.Tassert.Contains(t, scripts[1], "ip daddr 10.0.0.1")}+func TestReplaceGatewayDNSRedirectsPreservesCallerDeadlineAcrossRetry(t *testing.T) {+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)+ defer cancel()+ var seen []context.Context+ r := redirectRunner{runNft: func(got context.Context, script string) ([]byte, error) {+ seen = append(seen, got)+ if len(seen) == 1 {+ return []byte("Error: No such file or directory\n" + script), errors.New("exit status 1")+ }+ return nil, nil+ }}++ err := replaceGatewayDNSRedirects(ctx, r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353)+ require.NoError(t, err)+ require.Len(t, seen, 2)+ wantDeadline, wantOK := ctx.Deadline()+ for _, got := range seen {+ gotDeadline, gotOK := got.Deadline()+ assert.True(t, gotOK)+ assert.Equal(t, wantOK, gotOK)+ assert.Equal(t, wantDeadline, gotDeadline)+ assert.Equal(t, ctx.Done(), got.Done(), "the original operation context is reused")+ }+}++func TestReplaceGatewayDNSRedirectsDoesNotRetryAfterCancellation(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ calls := 0+ r := redirectRunner{runNft: func(_ context.Context, script string) ([]byte, error) {+ calls+++ cancel()+ return []byte("Error: No such file or directory\n" + script), errors.New("exit status 1")+ }}++ err := replaceGatewayDNSRedirects(ctx, r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353)+ require.ErrorIs(t, err, context.Canceled)+ assert.Equal(t, 1, calls, "cancellation must not trigger the missing-table retry")+}++type captureGatewayDNSLogger struct {+ internallogger.Logger+ messages []string+}++func (l *captureGatewayDNSLogger) Infof(template string, args ...any) {+ l.messages = append(l.messages, fmt.Sprintf(template, args...))+}++func TestReplaceGatewayDNSRedirectsLogsUniqueGatewayCount(t *testing.T) {+ previous := egresslog.Logger+ capture := &captureGatewayDNSLogger{}+ egresslog.Logger = capture+ t.Cleanup(func() { egresslog.Logger = previous })++ r := redirectRunner{runNft: func(context.Context, string) ([]byte, error) { return nil, nil }}+ inputs := []netip.Addr{+ netip.MustParseAddr("10.0.0.10"),+ netip.MustParseAddr("10.0.0.1"),+ netip.MustParseAddr("::ffff:10.0.0.1"),+ netip.MustParseAddr("fd00::1"),+ netip.MustParseAddr("10.0.0.10"),+ }+ require.NoError(t, replaceGatewayDNSRedirects(context.Background(), r, inputs, 15353))+ require.Equal(t, []string{"gateway DNS redirects replaced (3 unique gateway(s) -> :15353)"}, capture.messages)+}+func TestReplaceGatewayDNSRedirectsTreatsMissingEmptyTableAsSuccess(t *testing.T) {calls := 0r := redirectRunner{runNft: func(_ context.Context, script string) ([]byte, error) {@@ -87,7 +160,7 @@ func TestReplaceGatewayDNSRedirectsTreatsMissingEmptyTableAsSuccess(t *testing.Treturn []byte("Error: No such file or directory\n" + script), errors.New("exit status 1")}}- require.NoError(t, replaceGatewayDNSRedirects(r, nil, 15353))+ require.NoError(t, replaceGatewayDNSRedirects(context.Background(), r, nil, 15353))assert.Equal(t, 1, calls, "no retry is needed when the desired set is empty")}@@ -98,7 +171,7 @@ func TestReplaceGatewayDNSRedirectsPropagatesFailures(t *testing.T) {calls++return []byte("syntax error"), errors.New("exit status 1")}}- assert.Error(t, replaceGatewayDNSRedirects(r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353))+ assert.Error(t, replaceGatewayDNSRedirects(context.Background(), r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353))assert.Equal(t, 1, calls)})t.Run("failed missing-table retry", func(t *testing.T) {@@ -110,7 +183,7 @@ func TestReplaceGatewayDNSRedirectsPropagatesFailures(t *testing.T) {}return []byte("nft busy"), errors.New("exit status 1")}}- err := replaceGatewayDNSRedirects(r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353)+ err := replaceGatewayDNSRedirects(context.Background(), r, []netip.Addr{netip.MustParseAddr("10.0.0.1")}, 15353)assert.ErrorContains(t, err, "retry")assert.Equal(t, 2, calls)})