diff --git a/docs/private-services/README.md b/docs/private-services/README.md index 3eba66553..73c16dc9b 100644 --- a/docs/private-services/README.md +++ b/docs/private-services/README.md @@ -366,23 +366,45 @@ during an incompatible map replacement. A router restart is covered in ## CNI program reloads -A CNI restart preserves the service-policy gate and attachment incarnation -tokens when the live two-program chain uses exactly the same kernel map IDs -as the replacement programs. Both resolver frontends can continue forwarding -while those programs are replaced. Missing identities, incomplete chains and -changed map generations require new tokens; old authorization cannot transfer -to them. An incompatible map layout still drains authorization before replacing -maps, and the router must rebuild the policy before forwarding resumes. The -router does so on its next service-route resync, at most 30 seconds later, and -needs no restart. When a replaced map belongs to the service map set, the -router sees the new map IDs. When it does not, as when only the drop counters -grow, the router finds the gate it finalized closed, rebuilds its generation -behind it and reopens it. - -This continuity applies to an unchanged set of referenced maps. A program that -starts referencing another map conservatively requires reauthorization even -if existing map layouts did not change. Router startup still performs its -cache-synchronized policy rebuild and stale-entry sweep. +Service authorization lives in the service policy map set, the maps listed in +`prog.ServicePolicyMapNames`: + +| Map | Holds | +| ----------------------------- | ----------------------------------------- | +| `service_route_table` | Node-local service routes | +| `service_access_table` | Consumer access rows | +| `service_reverse_table` | Reply state | +| `service_remote_grant_table` | Grants for tunneled requests | +| `service_remote_target_table` | Producer interface of each remote grant | +| `service_deny_table` | Explicit denies | +| `service_peer_table` | Per-attachment next hops | +| `service_producer_set_table` | Producer sets of `LocalSet` routes | +| `service_policy_state_table` | The node's service-policy gate | +| `attachment_identity_table` | Attachment incarnation tokens | + +A CNI restart keeps the service-policy gate and every attachment's identity +token when the live two-program chain references the same maps as the +replacement programs and shares every policy map with them. Both resolver +frontends keep forwarding while those programs are replaced. A map outside the +policy set may be recreated without either: when `drop_reasons` grows, the gate +stays open, the policy tables keep their rows and the tokens stay the same. A +router that restarts during such a rollout, in either order, keeps serving its +inherited generation. This covers service authorization only. A recreated +forwarding table starts empty and serves only what its writers put back. + +An incompatible layout of a policy map drains authorization before the CNI +replaces any map, and so does a failure to tell which maps changed. The CNI +closes the gate, removes the access rows and empties the reverse and remote +grant tables, and the new programs get new tokens. Missing identities +and incomplete chains also get new tokens; old authorization cannot transfer +to them. The router must rebuild the policy before forwarding resumes. It sees +the new policy map IDs and does so on its next service-route resync, at most +30 seconds later, with no restart. A router restarting at the same time keeps +the gate closed until its startup sync finalizes. + +A program that starts referencing another map conservatively requires new +tokens even if no existing map layout changed. Router startup still performs +its cache-synchronized policy rebuild and stale-entry sweep. ## Router restarts @@ -399,7 +421,7 @@ sync. The inherited gate closes, as it did before this behavior, when the startup sync fails a dataplane mutation or cannot finalize. Only a finalizing router opens the gate, and the CNI datapath only ever closes it, which it does when -it drains authorization to replace an incompatible map set. A compatible +it drains authorization to replace an incompatible policy map. Any other reload keeps the pinned gate, so the router keeps the inherited generation across it. A gate the previous process left closed, for example after a crash during a rebuild, stays closed until the startup sync finalizes. diff --git a/internal/plumbing/ebpf/attach/attach.go b/internal/plumbing/ebpf/attach/attach.go index f90c4f34c..3f9688b65 100644 --- a/internal/plumbing/ebpf/attach/attach.go +++ b/internal/plumbing/ebpf/attach/attach.go @@ -97,8 +97,9 @@ func Start(pinDir string) (objs *prog.UsidObjects, ifaces []string, err error) { return nil, nil, err } // Compatible reloads retain the pinned policy gate and attachment tokens. - // Load drains authorization before replacing incompatible maps, and a new - // gate defaults to disabled until the controller completes its startup sync. + // Load drains authorization before replacing an incompatible policy map, + // and a new gate defaults to disabled until the controller completes its + // startup sync. ifaces, err = ResolveInterfaces() if err != nil { @@ -191,13 +192,29 @@ func Load(pinDir string) (objs *prog.UsidObjects, err error) { // re-attaches, which blackholes every attachment on the node. An // unchanged map keeps its rows. // An already-attached old classifier keeps map FDs after their pins - // are removed. Revoke its service authorization before replacing any - // incompatible pin so it cannot keep forwarding against an orphaned - // policy generation if the subsequent reattach fails. - if drainErr := drainLegacyServiceAuthorization(pinDir); drainErr != nil { - err = fmt.Errorf("attach: revoke legacy service authorization before map replacement: %w", drainErr) + // are removed. When a policy map is replaced, revoke its service + // authorization first so it cannot keep forwarding against an + // orphaned policy generation if the subsequent reattach fails. A map + // outside the policy set holds no authorization: the old and new + // classifiers keep sharing one generation, so the gate and its tables + // stay as they are and a router restart in any order keeps serving. + incompatible, checkErr := mappin.Incompatible(spec, pinDir, nil) + if checkErr != nil { + // Which maps changed is unknown, so fail closed as for a policy map. + err = fmt.Errorf("attach: check pinned maps against the compiled map spec: %w", checkErr) + if drainErr := drainLegacyServiceAuthorization(pinDir); drainErr != nil { + err = errors.Join(err, fmt.Errorf("attach: revoke legacy service authorization: %w", drainErr)) + } return nil, err } + if policy := policyMaps(incompatible); len(policy) > 0 { + slog.Warn("attach: service policy maps changed layout, draining service authorization", + "pinDir", pinDir, "maps", policy) + if drainErr := drainLegacyServiceAuthorization(pinDir); drainErr != nil { + err = fmt.Errorf("attach: revoke legacy service authorization before map replacement: %w", drainErr) + return nil, err + } + } unpinned, unpinErr := mappin.UnpinIncompatible(spec, pinDir, nil) if unpinErr != nil { err = fmt.Errorf("attach: recreate incompatible pinned maps: %w", unpinErr) diff --git a/internal/plumbing/ebpf/attach/egress_reattach.go b/internal/plumbing/ebpf/attach/egress_reattach.go index 7cd259cdd..5e7ba57de 100644 --- a/internal/plumbing/ebpf/attach/egress_reattach.go +++ b/internal/plumbing/ebpf/attach/egress_reattach.go @@ -14,6 +14,7 @@ import ( "golang.org/x/sys/unix" "go.datum.net/galactic/internal/plumbing/ebpf/attachmentidentity" + "go.datum.net/galactic/internal/plumbing/ebpf/prog" "go.datum.net/galactic/internal/plumbing/nldump" ) @@ -122,8 +123,10 @@ func reattachEgressLinkLocked(link netlink.Link, serviceProgram, legacyProgram * return false, nil } // A program replacement is not a new interface incarnation. Keep its - // authorization only when the complete old chain shares the new programs' - // map generation. Orphaned maps and incomplete chains require a new token. + // authorization only when the complete old chain references the same maps + // as the new programs and shares every service policy map with them. An + // orphaned policy map, a newly referenced map and an incomplete chain + // require a new token. A recreated map outside the policy set does not. preserve, err := canPreserveEgressIdentity(filters, serviceProgram, legacyProgram, identityMap) if err != nil { return false, err @@ -352,7 +355,77 @@ func sameProgramMaps(previous, current *ebpf.Program, identityID ebpf.MapID, ide if identityRequired && !slices.Contains(newIDs, identityID) { return false, nil } - slices.Sort(oldIDs) - slices.Sort(newIDs) - return slices.Equal(oldIDs, newIDs), nil + oldKeys, err := authorizationMapKeys(oldIDs) + if err != nil { + return false, fmt.Errorf("inspect previous egress program maps: %w", err) + } + newKeys, err := authorizationMapKeys(newIDs) + if err != nil { + return false, fmt.Errorf("inspect replacement egress program maps: %w", err) + } + if oldKeys == nil || newKeys == nil { + // Without map names there is no telling a policy map from any other, + // so every map must be the same one. + slices.Sort(oldIDs) + slices.Sort(newIDs) + return slices.Equal(oldIDs, newIDs), nil + } + return slices.Equal(oldKeys, newKeys), nil +} + +// authorizationMapKeys returns, sorted, one authorizationMapKey per map in +// ids. Two programs with equal keys reference the same set of maps and share +// every map that holds service authorization, while a map outside that set, +// such as a recreated drop counter, may differ. It returns nil when the kernel +// reports a map with no name. +func authorizationMapKeys(ids []ebpf.MapID) ([]string, error) { + keys := make([]string, 0, len(ids)) + for _, id := range ids { + m, err := ebpf.NewMapFromID(id) + if err != nil { + return nil, fmt.Errorf("open map %d: %w", id, err) + } + info, err := m.Info() + _ = m.Close() + if err != nil { + return nil, fmt.Errorf("inspect map %d: %w", id, err) + } + if info.Name == "" { + return nil, nil + } + keys = append(keys, authorizationMapKey(info.Name, info.Type, info.KeySize, info.ValueSize, id)) + } + slices.Sort(keys) + return keys, nil +} + +// authorizationMapKey identifies one map a program references: its kernel +// name and shape, and for a service policy map its kernel ID too. The shape +// tells apart policy maps whose truncated kernel names collide, such as +// service_remote_grant_table and service_remote_target_table, so swapping +// them between roles cannot keep a token. +func authorizationMapKey(name string, typ ebpf.MapType, keySize, valueSize uint32, id ebpf.MapID) string { + key := fmt.Sprintf("%s/%d/%d/%d", name, typ, keySize, valueSize) + if isServicePolicyKernelName(name) { + key = fmt.Sprintf("%s#%d", key, id) + } + return key +} + +// kernelObjNameLen is the longest object name the kernel keeps; it truncates +// longer ones. +const kernelObjNameLen = unix.BPF_OBJ_NAME_LEN - 1 + +// isServicePolicyKernelName reports whether name, as the kernel reports a map +// name, is a service policy map's. +func isServicePolicyKernelName(name string) bool { + for _, policy := range prog.ServicePolicyMapNames { + if len(policy) > kernelObjNameLen { + policy = policy[:kernelObjNameLen] + } + if name == policy { + return true + } + } + return false } diff --git a/internal/plumbing/ebpf/attach/policy_scope_test.go b/internal/plumbing/ebpf/attach/policy_scope_test.go new file mode 100644 index 000000000..938652310 --- /dev/null +++ b/internal/plumbing/ebpf/attach/policy_scope_test.go @@ -0,0 +1,287 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package attach + +import ( + "fmt" + "maps" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/cilium/ebpf" + "github.com/containernetworking/plugins/pkg/ns" + "github.com/vishvananda/netlink" + + "go.datum.net/galactic/internal/config" + "go.datum.net/galactic/internal/plumbing/ebpf/prog" +) + +func TestPolicyMapsSelectsOnlyServicePolicyMaps(t *testing.T) { + for _, tc := range []struct { + name string + in []string + want []string + }{ + {"DropCountersOnly", []string{prog.UsidMapDropReasons}, nil}, + {"ForwardingTables", []string{prog.UsidMapVipXlatTable, prog.UsidMapVrfTable}, nil}, + {"PolicyMap", []string{prog.UsidMapDropReasons, prog.UsidMapServiceDenyTable}, + []string{prog.UsidMapServiceDenyTable}}, + {"IdentityMap", []string{prog.UsidMapAttachmentIdentityTable}, []string{prog.UsidMapAttachmentIdentityTable}}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := policyMaps(tc.in); !slices.Equal(got, tc.want) { + t.Fatalf("policyMaps(%v) = %v, want %v", tc.in, got, tc.want) + } + }) + } +} + +func TestServicePolicyKernelNamesAreTruncated(t *testing.T) { + for name, want := range map[string]bool{ + "service_remote_": true, // service_remote_grant_table and service_remote_target_table + "service_deny_ta": true, + "attachment_iden": true, + "service_flow_ta": false, + "drop_reasons": false, + prog.UsidMapServiceDenyTable: false, // the kernel never reports a name this long + } { + if got := isServicePolicyKernelName(name); got != want { + t.Errorf("isServicePolicyKernelName(%q) = %v, want %v", name, got, want) + } + } +} + +// A token survives a reload only when every policy map keeps its kernel ID and +// role. Maps outside the policy set may change ID. +func TestAuthorizationMapKey(t *testing.T) { + const grantID, targetID = ebpf.MapID(10), ebpf.MapID(11) + key := func(name string, valueSize uint32, id ebpf.MapID) string { + return authorizationMapKey(name, ebpf.Hash, 40, valueSize, id) + } + // service_remote_grant_table and service_remote_target_table share a + // truncated kernel name; their value sizes tell them apart. + grant, target := key("service_remote_", 56, grantID), key("service_remote_", 4, targetID) + swappedGrant, swappedTarget := key("service_remote_", 56, targetID), key("service_remote_", 4, grantID) + old := []string{grant, target} + swapped := []string{swappedGrant, swappedTarget} + slices.Sort(old) + slices.Sort(swapped) + if slices.Equal(old, swapped) { + t.Error("swapping the remote grant and target maps between roles kept the same keys") + } + if key("service_deny_ta", 8, 1) == key("service_deny_ta", 8, 2) { + t.Error("a recreated policy map kept its key") + } + if key("drop_reasons", 8, 1) != key("drop_reasons", 8, 2) { + t.Error("a recreated map outside the policy set changed its key") + } + if key("drop_reasons", 8, 1) == key("drop_reasons", 16, 1) { + t.Error("a map that changed shape kept its key") + } +} + +// A recreated map that holds no service authorization, here a drop_reasons +// that grew, must leave the policy gate open, the access rows in place and +// every attachment's identity token unchanged. Before, galactic-cni drained +// authorization and rotated every token, and private services on the node +// stayed down until galactic-router rebuilt its generation. +func TestStartRecreatingNonPolicyMapKeepsServiceAuthorization(t *testing.T) { + requireRoot(t) + runPolicyMapReplacement(t, prog.UsidMapDropReasons, func(t *testing.T, current *prog.UsidObjects, ci uint32, + before, after map[uint32]uint64, + ) { + var gate prog.UsidServicePolicyStateValue + if err := current.ServicePolicyStateTable.Lookup(uint32(0), &gate); err != nil { + t.Fatal(err) + } + if gate.Enabled != 1 { + t.Fatal("recreating drop_reasons closed the service policy gate") + } + if !maps.Equal(before, after) { + t.Fatalf("recreating drop_reasons rotated identity tokens: %v, then %v", before, after) + } + assertDNSVerdict(t, current.UsidServiceEgress, ci, 7) + }) +} + +// A recreated service policy map still drains authorization and fails closed. +func TestStartRecreatingPolicyMapDrainsServiceAuthorization(t *testing.T) { + requireRoot(t) + runPolicyMapReplacement(t, prog.UsidMapServiceDenyTable, func(t *testing.T, current *prog.UsidObjects, ci uint32, + before, after map[uint32]uint64, + ) { + var gate prog.UsidServicePolicyStateValue + if err := current.ServicePolicyStateTable.Lookup(uint32(0), &gate); err != nil { + t.Fatal(err) + } + if gate.Enabled != 0 { + t.Fatal("recreating service_deny_table left the service policy gate open") + } + var access prog.UsidServiceAccessValue + if err := current.ServiceAccessTable.Lookup(dnsAccessKey(ci, dnsPrimary), &access); err == nil { + t.Fatal("recreating service_deny_table kept a real access row") + } + if maps.Equal(before, after) { + t.Fatal("recreating service_deny_table kept identity tokens") + } + assertDNSVerdict(t, current.UsidServiceEgress, ci, 2) + }) +} + +// runPolicyMapReplacement starts the datapath, attaches a consumer and a +// producer with live DNS authorization, swaps the pin of mapName for one with +// another layout, starts the datapath again and hands both token sets to +// check. +func runPolicyMapReplacement(t *testing.T, mapName string, + check func(t *testing.T, current *prog.UsidObjects, ci uint32, before, after map[uint32]uint64), +) { + t.Helper() + pin := filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-policy-scope-%d", os.Getpid())) + t.Cleanup(func() { _ = os.RemoveAll(pin) }) + t.Setenv(config.EnvCNIEBPFInterfaces, rolloutUplink) + network, err := ns.TempNetNS() + if err != nil { + t.Fatal(err) + } + defer func() { _ = network.Close() }() + if err := network.Do(func(_ ns.NetNS) error { + for _, link := range []netlink.Link{ + &netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: rolloutUplink}}, + &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "consumer0"}, PeerName: "consumer0p"}, + &netlink.Veth{LinkAttrs: netlink.LinkAttrs{Name: "producer0"}, PeerName: "producer0p"}, + } { + if err := netlink.LinkAdd(link); err != nil { + return err + } + if err := netlink.LinkSetUp(link); err != nil { + return err + } + } + old, _, err := Start(pin) + if err != nil { + return err + } + defer func() { _ = old.Close() }() + consumer, err := netlink.LinkByName("consumer0") + if err != nil { + return err + } + producer, err := netlink.LinkByName("producer0") + if err != nil { + return err + } + ci, pi := uint32(consumer.Attrs().Index), uint32(producer.Attrs().Index) + for _, link := range []netlink.Link{consumer, producer} { + if err := AttachEgressWithIdentity(old.UsidServiceEgress, old.UsidEgress, old.AttachmentIdentityTable, + uint32(link.Attrs().Index), link.Attrs().Name); err != nil { + return err + } + } + before := identityTokens(t, old.AttachmentIdentityTable, ci, pi) + seedDNSAuthorization(t, old, ci, pi, before[ci], before[pi]) + assertDNSVerdict(t, old.UsidServiceEgress, ci, 7) + + standIn := replacePinWithOtherLayout(t, pin, mapName) + + current, _, err := Start(pin) + if err != nil { + return err + } + defer func() { _ = current.Close() }() + // The reload must have recreated the map and moved the chain onto the + // new programs, or the checks below would pass by doing nothing. + if id := pinnedMapID(t, pin, mapName); id == standIn { + t.Fatalf("%s still has the stand-in map %d; Load did not recreate it", mapName, id) + } + if got, want := serviceFilterProgramID(t, consumer), progID(t, current.UsidServiceEgress); got != want { + t.Fatalf("consumer0 runs service program %d, want the new one %d", got, want) + } + check(t, current, ci, before, identityTokens(t, current.AttachmentIdentityTable, ci, pi)) + return nil + }); err != nil { + t.Fatal(err) + } +} + +func identityTokens(t *testing.T, table *ebpf.Map, indexes ...uint32) map[uint32]uint64 { + t.Helper() + tokens := make(map[uint32]uint64, len(indexes)) + for _, index := range indexes { + var token uint64 + if err := table.Lookup(index, &token); err != nil { + t.Fatalf("lookup identity of ifindex %d: %v", index, err) + } + tokens[index] = token + } + return tokens +} + +func pinnedMapID(t *testing.T, pinDir, name string) ebpf.MapID { + t.Helper() + m, err := ebpf.LoadPinnedMap(filepath.Join(pinDir, name), nil) + if err != nil { + t.Fatalf("open %s: %v", name, err) + } + defer func() { _ = m.Close() }() + info, err := m.Info() + if err != nil { + t.Fatalf("inspect %s: %v", name, err) + } + id, ok := info.ID() + if !ok { + t.Fatalf("kernel did not report %s's map id", name) + } + return id +} + +// serviceFilterProgramID returns the program ID of link's service classifier. +func serviceFilterProgramID(t *testing.T, link netlink.Link) uint32 { + t.Helper() + filters, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS) + if err != nil { + t.Fatalf("list filters on %s: %v", link.Attrs().Name, err) + } + for _, f := range filters { + if bpf, ok := f.(*netlink.BpfFilter); ok && bpf.Name == serviceEgressFilterName { + return uint32(bpf.Id) + } + } + t.Fatalf("%s has no service classifier", link.Attrs().Name) + return 0 +} + +// replacePinWithOtherLayout swaps the pin of name for a map with half its +// entries, which the next Load finds incompatible and recreates, and returns +// the stand-in's map ID. +func replacePinWithOtherLayout(t *testing.T, pinDir, name string) ebpf.MapID { + t.Helper() + path := filepath.Join(pinDir, name) + current, err := ebpf.LoadPinnedMap(path, nil) + if err != nil { + t.Fatalf("open %s: %v", name, err) + } + info, err := current.Info() + _ = current.Close() + if err != nil { + t.Fatalf("inspect %s: %v", name, err) + } + if err := os.Remove(path); err != nil { + t.Fatalf("remove %s pin: %v", name, err) + } + previous, err := ebpf.NewMap(&ebpf.MapSpec{ + Name: name, Type: info.Type, KeySize: info.KeySize, ValueSize: info.ValueSize, + MaxEntries: info.MaxEntries / 2, Flags: info.Flags, + }) + if err != nil { + t.Fatalf("create previous %s: %v", name, err) + } + defer func() { _ = previous.Close() }() + if err := previous.Pin(path); err != nil { + t.Fatalf("pin previous %s: %v", name, err) + } + return pinnedMapID(t, pinDir, name) +} diff --git a/internal/plumbing/ebpf/attach/service_rollout.go b/internal/plumbing/ebpf/attach/service_rollout.go index 8864d720f..1be1489af 100644 --- a/internal/plumbing/ebpf/attach/service_rollout.go +++ b/internal/plumbing/ebpf/attach/service_rollout.go @@ -11,8 +11,23 @@ import ( "path/filepath" "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" ) +// policyMaps returns the names in names that hold service authorization, in +// their given order. Replacing any of them drains authorization; replacing +// only other maps leaves the gate and its tables alone. +func policyMaps(names []string) []string { + var out []string + for _, name := range names { + if prog.IsServicePolicyMap(name) { + out = append(out, name) + } + } + return out +} + // drainLegacyServiceAuthorization revokes the authorization held by a // classifier that may continue running briefly while an incompatible map set // is replaced. Protocol-zero access markers are deliberately retained: they diff --git a/internal/plumbing/ebpf/mappin/mappin.go b/internal/plumbing/ebpf/mappin/mappin.go index 8430f781a..9e8baa636 100644 --- a/internal/plumbing/ebpf/mappin/mappin.go +++ b/internal/plumbing/ebpf/mappin/mappin.go @@ -30,11 +30,40 @@ import ( "github.com/cilium/ebpf" ) +// Incompatible returns the names, sorted, of every map in spec whose pin under +// pinDir no longer matches spec. It removes nothing. A map with no pin, or +// whose pin still matches, is not listed. skip, when non-nil, excludes maps +// the caller does not own. +func Incompatible(spec *ebpf.CollectionSpec, pinDir string, skip func(name string) bool) ([]string, error) { + var names []string + err := eachIncompatible(spec, pinDir, skip, func(name string, _ *ebpf.Map) error { + names = append(names, name) + return nil + }) + return names, err +} + // UnpinIncompatible removes the pin under pinDir of every map in spec whose // pinned copy no longer matches spec, and returns their names, sorted. A map // with no pin, or whose pin still matches, is left alone. skip, when non-nil, // excludes maps the caller does not own. func UnpinIncompatible(spec *ebpf.CollectionSpec, pinDir string, skip func(name string) bool) ([]string, error) { + var unpinned []string + err := eachIncompatible(spec, pinDir, skip, func(name string, m *ebpf.Map) error { + if err := m.Unpin(); err != nil { + return fmt.Errorf("unpin incompatible map %q: %w", name, err) + } + unpinned = append(unpinned, name) + return nil + }) + return unpinned, err +} + +// eachIncompatible calls fn, in name order, for every map in spec whose pin +// under pinDir no longer matches spec. It joins every error and keeps going. +func eachIncompatible( + spec *ebpf.CollectionSpec, pinDir string, skip func(name string) bool, fn func(string, *ebpf.Map) error, +) error { names := make([]string, 0, len(spec.Maps)) for name := range spec.Maps { if skip == nil || !skip(name) { @@ -43,7 +72,6 @@ func UnpinIncompatible(spec *ebpf.CollectionSpec, pinDir string, skip func(name } sort.Strings(names) - var unpinned []string var errs []error for _, name := range names { m, err := ebpf.LoadPinnedMap(filepath.Join(pinDir, name), nil) @@ -55,21 +83,16 @@ func UnpinIncompatible(spec *ebpf.CollectionSpec, pinDir string, skip func(name continue } compatErr := spec.Maps[name].Compatible(m) - if compatErr == nil { - _ = m.Close() - continue - } - if !errors.Is(compatErr, ebpf.ErrMapIncompatible) { + switch { + case compatErr == nil: + case !errors.Is(compatErr, ebpf.ErrMapIncompatible): errs = append(errs, fmt.Errorf("check pinned map %q: %w", name, compatErr)) - _ = m.Close() - continue - } - if err := m.Unpin(); err != nil { - errs = append(errs, fmt.Errorf("unpin incompatible map %q: %w", name, err)) - } else { - unpinned = append(unpinned, name) + default: + if err := fn(name, m); err != nil { + errs = append(errs, err) + } } _ = m.Close() } - return unpinned, errors.Join(errs...) + return errors.Join(errs...) } diff --git a/internal/plumbing/ebpf/mappin/mappin_test.go b/internal/plumbing/ebpf/mappin/mappin_test.go index 0f76781ea..3fcd87cae 100644 --- a/internal/plumbing/ebpf/mappin/mappin_test.go +++ b/internal/plumbing/ebpf/mappin/mappin_test.go @@ -123,3 +123,35 @@ func TestUnpinIncompatible_CompatiblePinsUntouched(t *testing.T) { t.Errorf("a's pin is gone: %v", err) } } + +// Incompatible lists the changed maps, honours skip, and removes no pin. +func TestIncompatible_ReportsWithoutUnpinning(t *testing.T) { + requireRoot(t) + dir := pinDir(t) + const same, changed, skipped = "same", "changed", "skipped" + + value := []byte{1, 2, 3, 4, 5, 6, 7, 8} + pin(t, dir, hashSpec(same, 8), make([]byte, 8), value) + pin(t, dir, hashSpec(changed, 16), make([]byte, 16), value) + pin(t, dir, hashSpec(skipped, 16), make([]byte, 16), value) + + spec := &ebpf.CollectionSpec{Maps: map[string]*ebpf.MapSpec{ + same: hashSpec(same, 8), + changed: hashSpec(changed, 32), + skipped: hashSpec(skipped, 32), + "absent": hashSpec("absent", 8), + }} + + names, err := Incompatible(spec, dir, func(name string) bool { return name == skipped }) + if err != nil { + t.Fatalf("Incompatible: %v", err) + } + if !slices.Equal(names, []string{changed}) { + t.Errorf("incompatible = %v, want [%s]", names, changed) + } + for _, name := range []string{same, changed, skipped} { + if _, err := os.Stat(filepath.Join(dir, name)); err != nil { + t.Errorf("%s's pin is gone (%v), want every pin left in place", name, err) + } + } +} diff --git a/internal/plumbing/ebpf/prog/policymaps.go b/internal/plumbing/ebpf/prog/policymaps.go new file mode 100644 index 000000000..b35119965 --- /dev/null +++ b/internal/plumbing/ebpf/prog/policymaps.go @@ -0,0 +1,34 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package prog + +// ServicePolicyMapNames names every pinned map that holds the router's service +// policy generation, the set whose kernel map IDs galactic-router tracks. A +// classifier that shares these maps with its replacement shares their +// authorization. A map outside this set holds no service authorization, so +// galactic-cni replaces it without draining authorization and without new +// attachment identity tokens. +var ServicePolicyMapNames = [...]string{ + "service_route_table", + "service_access_table", + "service_reverse_table", + "service_remote_grant_table", + "attachment_identity_table", + "service_policy_state_table", + "service_deny_table", + "service_peer_table", + "service_producer_set_table", + "service_remote_target_table", +} + +// IsServicePolicyMap reports whether name is in ServicePolicyMapNames. +func IsServicePolicyMap(name string) bool { + for _, n := range ServicePolicyMapNames { + if n == name { + return true + } + } + return false +} diff --git a/internal/plumbing/ebpf/prog/policymaps_test.go b/internal/plumbing/ebpf/prog/policymaps_test.go new file mode 100644 index 000000000..4fe17bec7 --- /dev/null +++ b/internal/plumbing/ebpf/prog/policymaps_test.go @@ -0,0 +1,78 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package prog + +import ( + "fmt" + "strings" + "testing" +) + +// notServicePolicyMaps are the datapath's service maps that hold no service +// authorization. A new service map must land in ServicePolicyMapNames or here, +// with a reason. +var notServicePolicyMaps = map[string]string{ + // A flow pin only chooses among a route's current producers, which are + // checked against the producer set and identity tokens on every packet. + "service_flow_table": "flow pins grant nothing", + "service_fib_scratch": "per-CPU scratch space", +} + +// Every name in ServicePolicyMapNames must be a map the datapath declares, so a +// renamed map cannot silently drop out of the drain and the token fence. +func TestServicePolicyMapNamesExistInDatapath(t *testing.T) { + spec, err := LoadUsid() + if err != nil { + t.Fatalf("load usid collection spec: %v", err) + } + for _, name := range ServicePolicyMapNames { + if _, ok := spec.Maps[name]; !ok { + t.Errorf("service policy map %q is not declared by the usid datapath", name) + } + } +} + +// Every service map the datapath declares is classified, so a new one that +// holds authorization cannot be left out of the drain and the token fence. +func TestEveryServiceMapIsClassified(t *testing.T) { + spec, err := LoadUsid() + if err != nil { + t.Fatalf("load usid collection spec: %v", err) + } + for name := range spec.Maps { + if !strings.HasPrefix(name, "service_") && !strings.HasPrefix(name, "attachment_") { + continue + } + if _, ok := notServicePolicyMaps[name]; ok == IsServicePolicyMap(name) { + t.Errorf("map %q must be in exactly one of ServicePolicyMapNames and notServicePolicyMaps", name) + } + } +} + +// galactic-cni tells policy maps apart by kernel name, which the kernel cuts to +// 15 bytes, and by shape. Two policy maps sharing a cut name must differ in +// shape, or swapping them between roles would keep identity tokens. +func TestServicePolicyMapsAreDistinctByKernelNameAndShape(t *testing.T) { + spec, err := LoadUsid() + if err != nil { + t.Fatalf("load usid collection spec: %v", err) + } + seen := map[string]string{} + for _, name := range ServicePolicyMapNames { + m := spec.Maps[name] + if m == nil { + continue // TestServicePolicyMapNamesExistInDatapath reports it + } + kernelName := name + if len(kernelName) > 15 { + kernelName = kernelName[:15] + } + key := fmt.Sprintf("%s/%d/%d/%d", kernelName, m.Type, m.KeySize, m.ValueSize) + if other, ok := seen[key]; ok { + t.Errorf("policy maps %q and %q share kernel name and shape %s", other, name, key) + } + seen[key] = name + } +} diff --git a/internal/serviceroute/dataplane.go b/internal/serviceroute/dataplane.go index c548a2a96..62d299c9d 100644 --- a/internal/serviceroute/dataplane.go +++ b/internal/serviceroute/dataplane.go @@ -23,6 +23,7 @@ import ( api "go.datum.net/galactic/api/network/v1alpha1" "go.datum.net/galactic/internal/plumbing/ebpf/attach" + "go.datum.net/galactic/internal/plumbing/ebpf/prog" "go.datum.net/galactic/internal/plumbing/ebpf/serviceroutemap" ) @@ -498,18 +499,9 @@ func (p *EBPFRouteProgrammer) ensureOpen() error { return nil } -var serviceRouteMapNames = [...]string{ - "service_route_table", - "service_access_table", - "service_reverse_table", - "service_remote_grant_table", - "attachment_identity_table", - "service_policy_state_table", - "service_deny_table", - serviceroutemap.ServicePeerMapName, - serviceroutemap.ServiceProducerSetMapName, - serviceroutemap.ServiceRemoteTargetMapName, -} +// serviceRouteMapNames is the policy map set galactic-cni drains and fences +// identity tokens by, so the two sides agree on what holds authorization. +var serviceRouteMapNames = prog.ServicePolicyMapNames // optionalServiceRouteMap reports whether an older datapath may lack the map. func optionalServiceRouteMap(name string) bool {