diff --git a/docs/cni/architecture.md b/docs/cni/architecture.md index 6daea67c4..85757486b 100644 --- a/docs/cni/architecture.md +++ b/docs/cni/architecture.md @@ -183,6 +183,34 @@ All nodes in the same VPC derive the same BGP Route Target by truncating the configuration. The RT is also used as the `BGPVRFInstance`'s Route Distinguisher and import/export Route Target. +### SRv6 ingress source filter + +`usid_ingress` can check each claimed packet's outer source before any tenant +delivery. The check runs only after the destination matches `locator_table`, +so traffic not addressed to this node's locator (BGP, BFD, everything else) +never reaches it. The source must match an allowed prefix, and unless that +entry accepts any interface, the packet must arrive on an uplink whose slot bit +is set in the entry's mask. + +- `off` (the default, and what a never-written config reads as) is a single + array read with no other effect. `audit` counts and records rejections but + still delivers. `enforce` drops them. +- Until the control plane marks the allow-list populated, every packet passes + and is counted as a bypass, so the filter cannot drop traffic before its + first complete sync. +- All state lives in new maps, so upgrading never trips the loader's + incompatible-pin recreation of the existing uSID maps. +- `internal/plumbing/ebpf/srcfiltermap` is the typed read/write API over these + maps, with an in-memory fake for tests. + +| Map | Type | Holds | +|---------------------------|-------------------|--------------------------------------------------------------------------------------| +| `src_allow_table` | LPM trie (4096) | Allowed outer source prefixes, each with an uplink bitmask and an any-interface flag | +| `uplink_slot_table` | Hash (64) | Uplink ifindex to its bit (0-31) in the bitmask | +| `src_filter_config_table` | Array (1) | Mode (`off`/`audit`/`enforce`), populated flag, generation | +| `src_filter_stats` | Per-CPU array (8) | Checked, allowed, denied by prefix, denied by interface, bypassed before first sync | +| `src_filter_denied` | LRU hash (1024) | Denied source /64s with count, last interface, last reason and time, for triage | + --- ## Data flow diff --git a/internal/plumbing/ebpf/doc.go b/internal/plumbing/ebpf/doc.go index 0f4101332..c0bb2ba71 100644 --- a/internal/plumbing/ebpf/doc.go +++ b/internal/plumbing/ebpf/doc.go @@ -20,6 +20,8 @@ // external event silently clearing the filter, requires it. // - usidmap: the read/write API that populates and reconciles the three // control-plane maps, used by the CNI ADD path and by garbage collection. +// - srcfiltermap: the read/write API for the SRv6 ingress source filter's +// allow-list, uplink slots, mode, counters, and denied-source record. // - metrics: Prometheus metrics and health event hooks spanning the whole // datapath. // diff --git a/internal/plumbing/ebpf/prog/doc.go b/internal/plumbing/ebpf/prog/doc.go index f7a4512d5..4321a62b6 100644 --- a/internal/plumbing/ebpf/prog/doc.go +++ b/internal/plumbing/ebpf/prog/doc.go @@ -40,4 +40,4 @@ package prog // -cc is deliberately omitted: bpf2go defaults to $BPF2GO_CC or "clang", so CI // can pin an exact version without this directive changing. // -//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type locator_value -type function_value -type vrf_value -type ifindex_vrf_value -type nptv6_value -type vip_xlat_range -type vip_xlat_key -type vip_xlat_value -type egress_route_key -type egress_route_value -type service_route_key -type service_route_value -type service_access_key -type service_access_value -type service_deny_key -type service_deny_value -type service_reverse_key -type service_reverse_value -type service_remote_grant_key -type service_remote_grant_value -type service_remote_target_value -type service_peer_key -type service_peer_value -type service_policy_state_value -type public_uplink_value -type egress_shard_group_value -type egress_shard_member -type egress_shard_pin_key -type egress_shard_pin_value -type egress_shard_counter -type mss_clamp_value -type tenant_gw_value -type host_only_ports_value -type vpc_attribution_value -type vrf_direction_counter -type vrf_traffic_value -type tp_state_value -type tp_iface_value -type tp_iface_addr_key -type tp_binding_key -type tp_entry -type tp_header -type tp_counter -type tp_fallback_key Usid usid.c +//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cflags "-O2 -g -Wall -idirafter /usr/include/x86_64-linux-gnu -idirafter /usr/include/aarch64-linux-gnu" -target bpfel,bpfeb -type locator_value -type function_value -type vrf_value -type ifindex_vrf_value -type nptv6_value -type vip_xlat_range -type vip_xlat_key -type vip_xlat_value -type egress_route_key -type egress_route_value -type service_route_key -type service_route_value -type service_access_key -type service_access_value -type service_deny_key -type service_deny_value -type service_reverse_key -type service_reverse_value -type service_remote_grant_key -type service_remote_grant_value -type service_remote_target_value -type service_peer_key -type service_peer_value -type service_policy_state_value -type public_uplink_value -type egress_shard_group_value -type egress_shard_member -type egress_shard_pin_key -type egress_shard_pin_value -type egress_shard_counter -type mss_clamp_value -type tenant_gw_value -type host_only_ports_value -type vpc_attribution_value -type vrf_direction_counter -type vrf_traffic_value -type tp_state_value -type tp_iface_value -type tp_iface_addr_key -type tp_binding_key -type tp_entry -type tp_header -type tp_counter -type tp_fallback_key -type src_allow_key -type src_allow_value -type src_filter_config -type src_denied_key -type src_denied_value Usid usid.c diff --git a/internal/plumbing/ebpf/prog/srcfilter.go b/internal/plumbing/ebpf/prog/srcfilter.go new file mode 100644 index 000000000..0c46f5984 --- /dev/null +++ b/internal/plumbing/ebpf/prog/srcfilter.go @@ -0,0 +1,37 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package prog + +// Source filter constants mirroring usid.c's enum src_filter_mode, +// SRCF_ANY_IFACE, SRC_FILTER_MAX_SLOTS and enum src_filter_stat. Hand-kept in +// sync with the C source for the same reason as the drop reasons: the generator +// produces no Go symbol for an enum used only as a literal or for a #define. +const ( + SrcFilterModeOff uint32 = 0 + SrcFilterModeAudit uint32 = 1 + SrcFilterModeEnforce uint32 = 2 + + SrcFilterFlagAnyIface uint32 = 1 << 0 + + SrcFilterMaxSlots = 32 + + SrcFilterStatChecked uint32 = 0 + SrcFilterStatAllowed uint32 = 1 + SrcFilterStatDenyPrefix uint32 = 2 + SrcFilterStatDenyIface uint32 = 3 + SrcFilterStatBypassUnpopulated uint32 = 4 + SrcFilterStatCount uint32 = 5 + SrcFilterStatSlots uint32 = 8 +) + +// SrcFilterStatNames maps each src_filter_stats index to a short, stable, +// metrics-friendly name. +var SrcFilterStatNames = map[uint32]string{ + SrcFilterStatChecked: "checked", + SrcFilterStatAllowed: "allowed", + SrcFilterStatDenyPrefix: "deny_prefix", + SrcFilterStatDenyIface: "deny_iface", + SrcFilterStatBypassUnpopulated: "bypass_unpopulated", +} diff --git a/internal/plumbing/ebpf/prog/usid.c b/internal/plumbing/ebpf/prog/usid.c index 4605e48a8..606cfe6dc 100644 --- a/internal/plumbing/ebpf/prog/usid.c +++ b/internal/plumbing/ebpf/prog/usid.c @@ -7,14 +7,19 @@ // usid.c implements the TC-BPF ingress datapath for the uFMT 48+16 SRv6 uSID // carrier format. // -// Packet path. Every lookup is an exact hash match; nothing here matches looser -// than a full /64, and none of the lookup maps below is an LPM trie: +// Packet path. Every uSID decode lookup is an exact hash match; nothing in +// steps 2 through 6 matches looser than a full /64. The source filter at step +// 2a is the one longest-prefix match on this path: // // 1. Parse the outer Ethernet and IPv6 header, bounds-checked. Not IPv6, or // too short to parse: TC_ACT_UNSPEC, handed to the next tc filter // unmodified. // 2. Exact-match the destination's top 64 bits, Block and Node-ID read with no // shift, against locator_table. No match: TC_ACT_UNSPEC. +// 2a. Source filter, when enabled: the outer source must fall inside an +// allowed fabric prefix, and the packet must arrive on an uplink that +// prefix is bound to. A rejected packet is dropped in enforce mode and +// only counted in audit mode. See src_filter_config_table. // 3. Read Function from the unmutated packet at its fixed offset. // 4. Exact-match (Block, Function) against function_table. No match: drop, // counted, because step 2 already claimed this packet and passing it @@ -1523,8 +1528,7 @@ struct { __type(value, struct vip_xlat_key); } vip_xlat_key_scratch SEC(".maps"); -// egress_route_table: see struct egress_route_key. The only LPM trie in this -// file. Everything above is a hash map because uSID decode is always a +// egress_route_table: see struct egress_route_key. uSID decode uses a // fixed-width exact match, but egress routing is inherently a longest-prefix // problem: an intra-VPC peer's specific prefix must win over a VRF's ::/0 // default. BPF_F_NO_PREALLOC is required by the kernel for this map type, not a @@ -2021,6 +2025,117 @@ struct { __type(value, struct pmtu_icmp_bucket); } pmtu_icmp_bucket SEC(".maps"); +// --------------------------------------------------------------------- +// SRv6 ingress source filter, step 2a. Every map here is new rather than a +// field on an existing one, so the loader never treats an upgrade as an +// incompatible pin and recreates the uSID decode maps. +// --------------------------------------------------------------------- + +// enum src_filter_mode is src_filter_config.mode. Any value other than +// SRC_FILTER_MODE_ENFORCE counts but never drops. +enum src_filter_mode { + SRC_FILTER_MODE_OFF = 0, + SRC_FILTER_MODE_AUDIT = 1, + SRC_FILTER_MODE_ENFORCE = 2, +}; + +// SRCF_ANY_IFACE marks an allow entry that is accepted on any interface, +// skipping the uplink binding check. +#define SRCF_ANY_IFACE (1U << 0) + +// SRC_FILTER_MAX_SLOTS is the number of uplink slots iface_mask can name. +#define SRC_FILTER_MAX_SLOTS 32 + +// struct src_allow_key keys src_allow_table. prefixlen counts only addr's +// significant bits; a packet lookup uses 128. +struct src_allow_key { + __u32 prefixlen; + __u8 addr[16]; +}; + +// struct src_allow_value is one allowed source prefix: iface_mask has bit N set +// for every uplink whose uplink_slot_table slot is N, and flags holds SRCF_*. +struct src_allow_value { + __u32 iface_mask; + __u32 flags; +}; + +// struct src_filter_config is src_filter_config_table's single value. +// populated stays zero until the control plane completes its first full sync +// of src_allow_table; until then every packet passes, counted as a bypass. +// generation is written by the control plane and never read here. +struct src_filter_config { + __u32 mode; + __u32 populated; + __u32 generation; +}; + +// enum src_filter_stat indexes src_filter_stats. Slots past +// SRC_FILTER_STAT_BYPASS_UNPOPULATED are reserved. +enum src_filter_stat { + SRC_FILTER_STAT_CHECKED = 0, + SRC_FILTER_STAT_ALLOWED = 1, + SRC_FILTER_STAT_DENY_PREFIX = 2, + SRC_FILTER_STAT_DENY_IFACE = 3, + SRC_FILTER_STAT_BYPASS_UNPOPULATED = 4, + __SRC_FILTER_STAT_SLOTS = 8, +}; + +// struct src_denied_key keys src_filter_denied: the top 64 bits of a denied +// outer source, in wire order. +struct src_denied_key { + __u8 prefix[8]; +}; + +// struct src_denied_value records one denied source /64 for triage. last_reason +// is the enum src_filter_stat deny slot of the most recent denial. +struct src_denied_value { + __u64 count; + __u64 last_ns; + __u32 last_ifindex; + __u32 last_reason; +}; + +// src_allow_table: allowed outer source prefixes. BPF_F_NO_PREALLOC is required +// by the kernel for this map type. +struct { + __uint(type, BPF_MAP_TYPE_LPM_TRIE); + __uint(map_flags, BPF_F_NO_PREALLOC); + __uint(max_entries, 4096); + __type(key, struct src_allow_key); + __type(value, struct src_allow_value); +} src_allow_table SEC(".maps"); + +// uplink_slot_table: uplink ifindex to its bit position in iface_mask. +struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 64); + __type(key, __u32); + __type(value, __u32); +} uplink_slot_table SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_ARRAY); + __uint(max_entries, 1); + __type(key, __u32); + __type(value, struct src_filter_config); +} src_filter_config_table SEC(".maps"); + +struct { + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); + __uint(max_entries, __SRC_FILTER_STAT_SLOTS); + __type(key, __u32); + __type(value, __u64); +} src_filter_stats SEC(".maps"); + +// src_filter_denied: a bounded, least-recently-used record of denied sources. +struct { + __uint(type, BPF_MAP_TYPE_LRU_HASH); + __uint(max_entries, 1024); + __type(key, struct src_denied_key); + __type(value, struct src_denied_value); +} src_filter_denied SEC(".maps"); + // --------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------- @@ -3021,6 +3136,104 @@ static USID_ALWAYS_INLINE void count_claimed_drop(__u32 reason, struct vrf_value c->dropped_packets++; } +static USID_ALWAYS_INLINE void count_src_filter(__u32 stat) +{ + __u64 *count = bpf_map_lookup_elem(&src_filter_stats, &stat); + + if (count) + __sync_fetch_and_add(count, 1); +} + +static USID_ALWAYS_INLINE void record_src_denial(const struct src_allow_key *src, __u32 ifindex, + __u32 reason) +{ + struct src_denied_key key; + __u64 now = bpf_ktime_get_ns(); + + __builtin_memcpy(key.prefix, src->addr, sizeof(key.prefix)); + + struct src_denied_value *seen = bpf_map_lookup_elem(&src_filter_denied, &key); + + if (seen) { + __sync_fetch_and_add(&seen->count, 1); + seen->last_ns = now; + seen->last_ifindex = ifindex; + seen->last_reason = reason; + return; + } + + struct src_denied_value fresh = { + .count = 1, + .last_ns = now, + .last_ifindex = ifindex, + .last_reason = reason, + }; + + bpf_map_update_elem(&src_filter_denied, &key, &fresh, BPF_NOEXIST); +} + +// src_filter_allows reports whether an outer source may deliver into a tenant +// network through the uplink at ifindex, counting the decision. An unpopulated +// filter allows everything, counted as a bypass. A denial is also recorded in +// src_filter_denied. +static USID_ALWAYS_INLINE int src_filter_allows(const struct src_filter_config *cfg, + const __u8 *saddr, __u32 ifindex) +{ + count_src_filter(SRC_FILTER_STAT_CHECKED); + + if (!cfg->populated) { + count_src_filter(SRC_FILTER_STAT_BYPASS_UNPOPULATED); + return 1; + } + + struct src_allow_key key = { .prefixlen = 128 }; + + __builtin_memcpy(key.addr, saddr, sizeof(key.addr)); + + struct src_allow_value *allow = bpf_map_lookup_elem(&src_allow_table, &key); + + if (!allow) { + count_src_filter(SRC_FILTER_STAT_DENY_PREFIX); + record_src_denial(&key, ifindex, SRC_FILTER_STAT_DENY_PREFIX); + return 0; + } + + if (!(allow->flags & SRCF_ANY_IFACE)) { + __u32 *slot = bpf_map_lookup_elem(&uplink_slot_table, &ifindex); + + if (!slot || *slot >= SRC_FILTER_MAX_SLOTS || + !(allow->iface_mask & (1U << (*slot & (SRC_FILTER_MAX_SLOTS - 1))))) { + count_src_filter(SRC_FILTER_STAT_DENY_IFACE); + record_src_denial(&key, ifindex, SRC_FILTER_STAT_DENY_IFACE); + return 0; + } + } + + count_src_filter(SRC_FILTER_STAT_ALLOWED); + return 1; +} + +// Verify the source-filter decision once. Its individual audit and allow paths +// return the same scalar verdict to the rest of the ingress program. +USID_NOINLINE int src_filter_drops(struct __sk_buff *skb) +{ + __u32 zero = 0; + struct src_filter_config *cfg = bpf_map_lookup_elem(&src_filter_config_table, &zero); + + if (!cfg || cfg->mode == SRC_FILTER_MODE_OFF) + return 0; + + // The caller has already matched the outer IPv6 locator. A global BPF + // function must establish its own packet bounds before reading the source. + void *data = (void *) (long) skb->data; + void *data_end = (void *) (long) skb->data_end; + struct usid_ip6hdr *ip6 = data + sizeof(struct usid_ethhdr); + + if ((void *) (ip6 + 1) > data_end) + return cfg->mode == SRC_FILTER_MODE_ENFORCE; + return !src_filter_allows(cfg, ip6->saddr, skb->ifindex) && cfg->mode == SRC_FILTER_MODE_ENFORCE; +} + // read_be64 composes an 8-byte big-endian buffer into a host-native u64 byte by // byte, rather than casting: p is not guaranteed 8-byte aligned, pointing 38 // bytes into the packet, and some architectures reject unaligned wide loads at @@ -4288,6 +4501,12 @@ int usid_ingress(struct __sk_buff *skb) return TC_ACT_UNSPEC; } + // Step 2a: source filter. Only packets already claimed by step 2 reach + // it, so traffic for any other destination is untouched. With the filter + // off this is a single array read. + if (src_filter_drops(skb)) + return TC_ACT_SHOT; + __u64 block = locator_key >> 16; // Step 3: read Function from the unmutated packet at its fixed offset, the diff --git a/internal/plumbing/ebpf/prog/usid_srcfilter_test.go b/internal/plumbing/ebpf/prog/usid_srcfilter_test.go new file mode 100644 index 000000000..acf081a6f --- /dev/null +++ b/internal/plumbing/ebpf/prog/usid_srcfilter_test.go @@ -0,0 +1,392 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package prog + +import ( + "bytes" + "errors" + "net/netip" + "runtime" + "testing" + + "github.com/cilium/ebpf" + "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" + + "go.datum.net/galactic/internal/plumbing/ebpf/uformat" +) + +// testRunIfindex is the skb->ifindex BPF_PROG_TEST_RUN uses when no context is +// supplied: the loopback device. +const testRunIfindex uint32 = 1 + +var ( + fabricPeerSrc = netip.MustParseAddr("fd00:aa:1:2::1") + fabricPrefix = netip.MustParsePrefix("fd00:aa::/32") + outsideSrc = netip.MustParseAddr("2001:db8:ffff:1::1") +) + +// srcFilterFixture is a loaded datapath with one claimed uSID whose vrf_table +// entry points at a routing table that does not exist, so a packet the source +// filter lets through ends at DROP_REASON_FIB_LOOKUP_FAILED. Reaching that +// reason proves the filter passed the packet on to the rest of the path. +type srcFilterFixture struct { + objs *UsidObjects + usid testUSID +} + +func newSrcFilterFixture(t *testing.T) *srcFilterFixture { + t.Helper() + requireRoot(t) + f := &srcFilterFixture{ + objs: loadObjects(t), + usid: testUSID{block: baseUSID.block, nodeID: baseUSID.nodeID, function: uformat.FunctionEndDT46, argument: 0x321}, + } + if err := f.objs.LocatorTable.Put(f.usid.locatorKey(t), UsidLocatorValue{Generation: 1}); err != nil { + t.Fatalf("populate locator_table: %v", err) + } + if err := f.objs.FunctionTable.Put(f.usid.functionKey(t), UsidFunctionValue{Behavior: 1}); err != nil { + t.Fatalf("populate function_table: %v", err) + } + if err := f.objs.VrfTable.Put(f.usid.vrfKey(), UsidVrfValue{VrfTableId: 0x3A3A3A}); err != nil { + t.Fatalf("populate vrf_table: %v", err) + } + return f +} + +func (f *srcFilterFixture) setConfig(t *testing.T, mode uint32, populated bool) { + t.Helper() + cfg := UsidSrcFilterConfig{Mode: mode, Generation: 1} + if populated { + cfg.Populated = 1 + } + if err := f.objs.SrcFilterConfigTable.Put(uint32(0), cfg); err != nil { + t.Fatalf("write src_filter_config_table: %v", err) + } +} + +func (f *srcFilterFixture) allow(t *testing.T, prefix netip.Prefix, ifaceMask, flags uint32) { + t.Helper() + key := UsidSrcAllowKey{Prefixlen: uint32(prefix.Bits()), Addr: prefix.Masked().Addr().As16()} + if err := f.objs.SrcAllowTable.Put(key, UsidSrcAllowValue{IfaceMask: ifaceMask, Flags: flags}); err != nil { + t.Fatalf("populate src_allow_table[%s]: %v", prefix, err) + } +} + +func (f *srcFilterFixture) setSlot(t *testing.T, ifindex, slot uint32) { + t.Helper() + if err := f.objs.UplinkSlotTable.Put(ifindex, slot); err != nil { + t.Fatalf("populate uplink_slot_table[%d]: %v", ifindex, err) + } +} + +func (f *srcFilterFixture) packet(t *testing.T, src netip.Addr) []byte { + t.Helper() + return buildPacket(t, f.usid.addr(t), src, true) +} + +func (f *srcFilterFixture) run(t *testing.T, pkt []byte) uint32 { + t.Helper() + ret, _, err := f.objs.UsidIngress.Test(pkt) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + return ret +} + +// wantStats asserts every src_filter_stats slot, with any slot absent from want +// expected to be zero. +func (f *srcFilterFixture) wantStats(t *testing.T, want map[uint32]uint64) { + t.Helper() + for i := range SrcFilterStatSlots { + if got := sumPerCPU(t, f.objs.SrcFilterStats, i); got != want[i] { + t.Errorf("src_filter_stats[%s] = %d, want %d", srcFilterStatName(i), got, want[i]) + } + } +} + +// wantForwarded asserts the packet passed the filter and reached the FIB lookup. +func (f *srcFilterFixture) wantForwarded(t *testing.T, ret uint32) { + t.Helper() + if ret != tcActShot { + t.Errorf("verdict = %d, want TC_ACT_SHOT from the FIB lookup (%d)", ret, tcActShot) + } + assertOnlyDropReason(t, f.objs.DropReasons, DropReasonFibLookupFailed, 1) + if got := f.vrfPackets(t); got != 1 { + t.Errorf("vrf_table packets = %d, want 1", got) + } +} + +// wantFiltered asserts the filter dropped the packet before any uSID decode +// step past the locator match. +func (f *srcFilterFixture) wantFiltered(t *testing.T, ret uint32) { + t.Helper() + if ret != tcActShot { + t.Errorf("verdict = %d, want TC_ACT_SHOT (%d)", ret, tcActShot) + } + assertOnlyDropReason(t, f.objs.DropReasons, 0, 0) + if got := f.vrfPackets(t); got != 0 { + t.Errorf("vrf_table packets = %d, want 0: a filtered packet must not reach vrf_table", got) + } +} + +func (f *srcFilterFixture) vrfPackets(t *testing.T) uint64 { + t.Helper() + var v UsidVrfValue + if err := f.objs.VrfTable.Lookup(f.usid.vrfKey(), &v); err != nil { + t.Fatalf("lookup vrf_table: %v", err) + } + return v.Packets +} + +// wantDenied asserts src_filter_denied holds src's /64 with the given count and +// reason. +func (f *srcFilterFixture) wantDenied(t *testing.T, src netip.Addr, count uint64, reason, ifindex uint32) { + t.Helper() + var key UsidSrcDeniedKey + a := src.As16() + copy(key.Prefix[:], a[:8]) + var v UsidSrcDeniedValue + if err := f.objs.SrcFilterDenied.Lookup(key, &v); err != nil { + t.Fatalf("lookup src_filter_denied[%s/64]: %v", src, err) + } + if v.Count != count || v.LastReason != reason || v.LastIfindex != ifindex || v.LastNs == 0 { + t.Errorf("src_filter_denied[%s/64] = %+v, want count %d reason %s ifindex %d and a timestamp", + src, v, count, srcFilterStatName(reason), ifindex) + } +} + +func (f *srcFilterFixture) wantNoDenials(t *testing.T) { + t.Helper() + var key UsidSrcDeniedKey + var v UsidSrcDeniedValue + if f.objs.SrcFilterDenied.Iterate().Next(&key, &v) { + t.Errorf("src_filter_denied has entry %x = %+v, want none", key.Prefix, v) + } +} + +func srcFilterStatName(i uint32) string { + if name, ok := SrcFilterStatNames[i]; ok { + return name + } + return "reserved" +} + +func TestUsidIngressSrcFilter_ModeOffIsNoOp(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeOff, true) + + f.wantForwarded(t, f.run(t, f.packet(t, outsideSrc))) + f.wantStats(t, nil) + f.wantNoDenials(t) +} + +func TestUsidIngressSrcFilter_DefaultConfigIsOff(t *testing.T) { + f := newSrcFilterFixture(t) + + f.wantForwarded(t, f.run(t, f.packet(t, outsideSrc))) + f.wantStats(t, nil) +} + +func TestUsidIngressSrcFilter_AuditCountsAndForwards(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeAudit, true) + f.allow(t, fabricPrefix, 0, SrcFilterFlagAnyIface) + + f.wantForwarded(t, f.run(t, f.packet(t, outsideSrc))) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatDenyPrefix: 1}) + f.wantDenied(t, outsideSrc, 1, SrcFilterStatDenyPrefix, testRunIfindex) +} + +func TestUsidIngressSrcFilter_AuditAllowedSource(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeAudit, true) + f.allow(t, fabricPrefix, 0, SrcFilterFlagAnyIface) + + f.wantForwarded(t, f.run(t, f.packet(t, fabricPeerSrc))) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatAllowed: 1}) + f.wantNoDenials(t) +} + +func TestUsidIngressSrcFilter_EnforcePrefixMissDrops(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeEnforce, true) + f.allow(t, fabricPrefix, 0, SrcFilterFlagAnyIface) + + pkt := f.packet(t, outsideSrc) + f.wantFiltered(t, f.run(t, pkt)) + f.wantFiltered(t, f.run(t, pkt)) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 2, SrcFilterStatDenyPrefix: 2}) + f.wantDenied(t, outsideSrc, 2, SrcFilterStatDenyPrefix, testRunIfindex) +} + +func TestUsidIngressSrcFilter_EnforceEmptyAllowListDrops(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeEnforce, true) + + f.wantFiltered(t, f.run(t, f.packet(t, fabricPeerSrc))) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatDenyPrefix: 1}) +} + +func TestUsidIngressSrcFilter_EnforceInterfaceBinding(t *testing.T) { + tests := []struct { + name string + slot *uint32 + ifaceMask uint32 + flags uint32 + wantAllow bool + }{ + {"BoundSlotAllowed", ptr(uint32(3)), 1 << 3, 0, true}, + {"OneOfSeveralSlotsAllowed", ptr(uint32(3)), 1<<0 | 1<<3 | 1<<31, 0, true}, + {"WrongSlotDropped", ptr(uint32(3)), 1 << 4, 0, false}, + {"EmptyMaskDropped", ptr(uint32(0)), 0, 0, false}, + {"UnknownUplinkDropped", nil, ^uint32(0), 0, false}, + {"SlotOutOfRangeDropped", ptr(uint32(40)), ^uint32(0), 0, false}, + {"AnyIfaceAllowedOnUnknownUplink", nil, 0, SrcFilterFlagAnyIface, true}, + {"AnyIfaceAllowedOnWrongSlot", ptr(uint32(3)), 1 << 4, SrcFilterFlagAnyIface, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeEnforce, true) + f.allow(t, fabricPrefix, tt.ifaceMask, tt.flags) + if tt.slot != nil { + f.setSlot(t, testRunIfindex, *tt.slot) + } + + ret := f.run(t, f.packet(t, fabricPeerSrc)) + if tt.wantAllow { + f.wantForwarded(t, ret) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatAllowed: 1}) + return + } + f.wantFiltered(t, ret) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatDenyIface: 1}) + f.wantDenied(t, fabricPeerSrc, 1, SrcFilterStatDenyIface, testRunIfindex) + }) + } +} + +func TestUsidIngressSrcFilter_LongestPrefixWins(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeEnforce, true) + f.setSlot(t, testRunIfindex, 1) + f.allow(t, fabricPrefix, 1<<1, 0) + f.allow(t, netip.PrefixFrom(fabricPeerSrc, 64).Masked(), 1<<2, 0) + + f.wantFiltered(t, f.run(t, f.packet(t, fabricPeerSrc))) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatDenyIface: 1}) +} + +func TestUsidIngressSrcFilter_UnpopulatedFailsOpen(t *testing.T) { + for _, mode := range []uint32{SrcFilterModeAudit, SrcFilterModeEnforce} { + f := newSrcFilterFixture(t) + f.setConfig(t, mode, false) + + f.wantForwarded(t, f.run(t, f.packet(t, outsideSrc))) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatBypassUnpopulated: 1}) + f.wantNoDenials(t) + } +} + +func TestUsidIngressSrcFilter_LocatorMissNeverChecked(t *testing.T) { + f := newSrcFilterFixture(t) + f.setConfig(t, SrcFilterModeEnforce, true) + + other := testUSID{block: 0xFFEEDDCCBBAA, nodeID: 0x0002, function: uformat.FunctionEndDT46, argument: 0x001} + pkt := buildPacket(t, other.addr(t), outsideSrc, true) + + ret, out, err := f.objs.UsidIngress.Test(pkt) + if err != nil { + t.Fatalf("program test-run: %v", err) + } + if ret != tcActUnspec { + t.Errorf("verdict = %d, want TC_ACT_UNSPEC (%d)", ret, tcActUnspec) + } + if !bytes.Equal(out, pkt) { + t.Errorf("packet mutated on a locator_table miss:\n in: % x\nout: % x", pkt, out) + } + f.wantStats(t, nil) + f.wantNoDenials(t) +} + +// skbContext is the leading part of struct __sk_buff that BPF_PROG_TEST_RUN +// accepts as input, up to and including ifindex. Every other field must be +// zero. +type skbContext struct { + Len uint32 + PktType uint32 + Mark uint32 + QueueMapping uint32 + Protocol uint32 + VlanPresent uint32 + VlanTci uint32 + VlanProto uint32 + Priority uint32 + IngressIfindex uint32 + Ifindex uint32 +} + +// TestUsidIngressSrcFilter_BindsToArrivalInterface runs the program with its +// skb on a real device in a private network namespace, proving the binding +// check keys on the interface the packet arrived on rather than a fixed value. +func TestUsidIngressSrcFilter_BindsToArrivalInterface(t *testing.T) { + f := newSrcFilterFixture(t) + + runtime.LockOSThread() + origNS := openThreadNetns(t) + t.Cleanup(func() { + if err := unix.Setns(origNS, unix.CLONE_NEWNET); err != nil { + t.Errorf("restore original network namespace: %v", err) + return + } + _ = unix.Close(origNS) + runtime.UnlockOSThread() + }) + if err := unix.Unshare(unix.CLONE_NEWNET); err != nil { + t.Fatalf("unshare network namespace: %v", err) + } + for _, name := range []string{"sf0", "sf1"} { + if err := netlink.LinkAdd(&netlink.Dummy{LinkAttrs: netlink.LinkAttrs{Name: name}}); err != nil { + t.Fatalf("add dummy link %s: %v", name, err) + } + } + bound := uint32(setLinkUp(t, "sf0").Attrs().Index) + other := uint32(setLinkUp(t, "sf1").Attrs().Index) + + f.setConfig(t, SrcFilterModeEnforce, true) + f.setSlot(t, bound, 5) + f.setSlot(t, other, 6) + f.allow(t, fabricPrefix, 1<<5, 0) + + runOn := func(ifindex uint32) uint32 { + t.Helper() + pkt := f.packet(t, fabricPeerSrc) + ret, err := f.objs.UsidIngress.Run(&ebpf.RunOptions{ + Data: pkt, + DataOut: make([]byte, len(pkt)+256), + Context: skbContext{Ifindex: ifindex}, + Repeat: 1, + }) + if err != nil { + if errors.Is(err, ebpf.ErrNotSupported) { + t.Skipf("kernel cannot run tc programs with a context: %v", err) + } + t.Fatalf("program test-run on ifindex %d: %v", ifindex, err) + } + return ret + } + + f.wantFiltered(t, runOn(other)) + f.wantStats(t, map[uint32]uint64{SrcFilterStatChecked: 1, SrcFilterStatDenyIface: 1}) + f.wantDenied(t, fabricPeerSrc, 1, SrcFilterStatDenyIface, other) + + f.wantForwarded(t, runOn(bound)) + f.wantStats(t, map[uint32]uint64{ + SrcFilterStatChecked: 2, SrcFilterStatDenyIface: 1, SrcFilterStatAllowed: 1, + }) +} + +func ptr[T any](v T) *T { return &v } diff --git a/internal/plumbing/ebpf/srcfiltermap/doc.go b/internal/plumbing/ebpf/srcfiltermap/doc.go new file mode 100644 index 000000000..98a9513a9 --- /dev/null +++ b/internal/plumbing/ebpf/srcfiltermap/doc.go @@ -0,0 +1,13 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +// Package srcfiltermap implements the read/write API for the eBPF uSID +// datapath's SRv6 ingress source filter: src_allow_table, uplink_slot_table, +// src_filter_config_table, src_filter_stats and src_filter_denied. +// +// It decides nothing about which sources are allowed or when. A control-plane +// reconciler computes the desired allow-list and uplink slots and applies them +// here, then marks the filter populated once its first complete sync lands. +// Until then the datapath lets every packet through, counted as a bypass. +package srcfiltermap diff --git a/internal/plumbing/ebpf/srcfiltermap/fake.go b/internal/plumbing/ebpf/srcfiltermap/fake.go new file mode 100644 index 000000000..f403f9cb4 --- /dev/null +++ b/internal/plumbing/ebpf/srcfiltermap/fake.go @@ -0,0 +1,127 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfiltermap + +import ( + "reflect" + "sync" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" +) + +// NewFake returns a Filter over in-memory tables, and the tables themselves so +// a test can seed datapath-written state such as stats or denied sources. The +// fake matches keys exactly; it does not perform longest-prefix matching. +// +// Stats values are []uint64 per-CPU slices keyed by uint32 slot, and denied +// sources are prog.UsidSrcDeniedValue keyed by prog.UsidSrcDeniedKey. +func NewFake() (*Filter, Tables) { + t := Tables{ + Allow: NewFakeTable(), + UplinkSlots: NewFakeTable(), + Config: NewFakeTable(), + Stats: NewFakeTable(), + Denied: NewFakeTable(), + } + return New(t), t +} + +// FakeTable is an in-memory usidmap.Table, safe for concurrent use. Iteration +// runs over a snapshot in insertion order. +type FakeTable struct { + mu sync.Mutex + entries map[any]any + order []any + // PutErr, when set, is returned by every Put instead of storing. + PutErr error +} + +// NewFakeTable returns an empty FakeTable. +func NewFakeTable() *FakeTable { + return &FakeTable{entries: make(map[any]any)} +} + +// Put stores value at key, or returns PutErr if set. +func (f *FakeTable) Put(key, value any) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.PutErr != nil { + return f.PutErr + } + if _, exists := f.entries[key]; !exists { + f.order = append(f.order, key) + } + f.entries[key] = value + return nil +} + +// Lookup copies the value at key into valueOut, or returns +// ebpf.ErrKeyNotExist. +func (f *FakeTable) Lookup(key, valueOut any) error { + f.mu.Lock() + defer f.mu.Unlock() + v, ok := f.entries[key] + if !ok { + return ebpf.ErrKeyNotExist + } + reflect.ValueOf(valueOut).Elem().Set(reflect.ValueOf(v)) + return nil +} + +// Delete removes key, or returns ebpf.ErrKeyNotExist. +func (f *FakeTable) Delete(key any) error { + f.mu.Lock() + defer f.mu.Unlock() + if _, ok := f.entries[key]; !ok { + return ebpf.ErrKeyNotExist + } + delete(f.entries, key) + for i, k := range f.order { + if k == key { + f.order = append(f.order[:i], f.order[i+1:]...) + break + } + } + return nil +} + +// Len returns the number of entries. +func (f *FakeTable) Len() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.entries) +} + +// Iterate returns an iterator over a snapshot of the table. +func (f *FakeTable) Iterate() usidmap.Iterator { + f.mu.Lock() + defer f.mu.Unlock() + it := &fakeIterator{idx: -1} + for _, k := range f.order { + it.keys = append(it.keys, k) + it.values = append(it.values, f.entries[k]) + } + return it +} + +type fakeIterator struct { + keys []any + values []any + idx int +} + +func (it *fakeIterator) Next(keyOut, valueOut any) bool { + it.idx++ + if it.idx >= len(it.keys) { + return false + } + reflect.ValueOf(keyOut).Elem().Set(reflect.ValueOf(it.keys[it.idx])) + reflect.ValueOf(valueOut).Elem().Set(reflect.ValueOf(it.values[it.idx])) + return true +} + +func (it *fakeIterator) Err() error { return nil } diff --git a/internal/plumbing/ebpf/srcfiltermap/kernel_test.go b/internal/plumbing/ebpf/srcfiltermap/kernel_test.go new file mode 100644 index 000000000..6338b74c9 --- /dev/null +++ b/internal/plumbing/ebpf/srcfiltermap/kernel_test.go @@ -0,0 +1,171 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfiltermap + +import ( + "errors" + "net/netip" + "os" + "path/filepath" + "reflect" + "testing" + + "github.com/cilium/ebpf" + "github.com/cilium/ebpf/rlimit" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" +) + +func requireRoot(t *testing.T) { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("test requires root (CAP_BPF/CAP_NET_ADMIN) to load real BPF maps; re-run via sudo") + } + if err := rlimit.RemoveMemlock(); err != nil { + t.Fatalf("rlimit.RemoveMemlock: %v", err) + } +} + +func loadTestObjects(t *testing.T, opts *ebpf.CollectionOptions) *prog.UsidObjects { + t.Helper() + spec, err := prog.LoadUsid() + if err != nil { + t.Fatalf("load spec: %v", err) + } + if opts != nil { + for _, m := range spec.Maps { + m.Pinning = ebpf.PinByName + } + } + var objs prog.UsidObjects + if err := spec.LoadAndAssign(&objs, opts); err != nil { + var ve *ebpf.VerifierError + if errors.As(err, &ve) { + t.Fatalf("load objects: verifier rejected program:\n%+v", ve) + } + t.Fatalf("load objects: %v", err) + } + t.Cleanup(func() { + if err := objs.Close(); err != nil { + t.Errorf("close objects: %v", err) + } + }) + return &objs +} + +// TestKernelMaps round-trips every Filter operation through real kernel maps, +// proving the Go key and value layouts match the datapath's. +func TestKernelMaps(t *testing.T) { + requireRoot(t) + objs := loadTestObjects(t, nil) + f := NewFromObjects(objs) + + desired := []Entry{ + {Prefix: netip.MustParsePrefix("fd00:aa::/32"), IfaceMask: 1<<0 | 1<<3}, + {Prefix: netip.MustParsePrefix("fd00:aa:1::/48"), AnyIface: true}, + } + if _, err := f.SyncAllow(desired); err != nil { + t.Fatalf("SyncAllow: %v", err) + } + got, err := f.ListAllow() + if err != nil { + t.Fatalf("ListAllow: %v", err) + } + if !reflect.DeepEqual(got, desired) { + t.Errorf("ListAllow = %+v, want %+v", got, desired) + } + + var v prog.UsidSrcAllowValue + probe := prog.UsidSrcAllowKey{Prefixlen: 128, Addr: netip.MustParseAddr("fd00:aa:1::7").As16()} + if err := objs.SrcAllowTable.Lookup(probe, &v); err != nil { + t.Fatalf("longest-prefix probe: %v", err) + } + if v.Flags != prog.SrcFilterFlagAnyIface { + t.Errorf("probe matched %+v, want the more specific any-iface entry", v) + } + + if res, err := f.SyncAllow(desired[:1]); err != nil || res.Removed != 1 || res.Unchanged != 1 { + t.Errorf("SyncAllow shrink = %+v, %v, want one removed and one unchanged", res, err) + } + + if err := f.SyncUplinkSlots(map[uint32]uint8{4: 0, 5: 3}); err != nil { + t.Fatalf("SyncUplinkSlots: %v", err) + } + slots, err := f.UplinkSlots() + if err != nil { + t.Fatalf("UplinkSlots: %v", err) + } + if want := map[uint32]uint8{4: 0, 5: 3}; !reflect.DeepEqual(slots, want) { + t.Errorf("UplinkSlots = %v, want %v", slots, want) + } + + cfg, err := f.Config() + if err != nil || cfg != (Config{}) { + t.Errorf("fresh Config = %+v, %v, want zero", cfg, err) + } + want := Config{Mode: ModeEnforce, Populated: true, Generation: 2} + if err := f.SetConfig(want); err != nil { + t.Fatalf("SetConfig: %v", err) + } + if cfg, err = f.Config(); err != nil || cfg != want { + t.Errorf("Config = %+v, %v, want %+v", cfg, err, want) + } + + stats, err := f.Stats() + if err != nil || stats != (Stats{}) { + t.Errorf("fresh Stats = %+v, %v, want zero", stats, err) + } + + var key prog.UsidSrcDeniedKey + a := netip.MustParseAddr("2001:db8:5:6::1").As16() + copy(key.Prefix[:], a[:8]) + if err := objs.SrcFilterDenied.Put(key, prog.UsidSrcDeniedValue{Count: 3, LastNs: 9, LastIfindex: 4, + LastReason: prog.SrcFilterStatDenyPrefix}); err != nil { + t.Fatalf("seed src_filter_denied: %v", err) + } + denied, err := f.DeniedSources() + if err != nil { + t.Fatalf("DeniedSources: %v", err) + } + wantDenied := []DeniedSource{{Prefix: netip.MustParsePrefix("2001:db8:5:6::/64"), Count: 3, LastIfindex: 4, + LastSeenNs: 9, LastReason: DenyReasonPrefix}} + if !reflect.DeepEqual(denied, wantDenied) { + t.Errorf("DeniedSources = %+v, want %+v", denied, wantDenied) + } +} + +func TestOpenPinned(t *testing.T) { + requireRoot(t) + if _, err := os.Stat("/sys/fs/bpf"); err != nil { + t.Skipf("test requires a bpffs at /sys/fs/bpf: %v", err) + } + pinDir, err := os.MkdirTemp("/sys/fs/bpf", "srcfiltermap-test-") + if err != nil { + t.Skipf("cannot create a pin directory on bpffs: %v", err) + } + t.Cleanup(func() { _ = os.RemoveAll(pinDir) }) + + if _, _, err := OpenPinned(filepath.Join(pinDir, "missing")); err == nil { + t.Error("OpenPinned on an empty directory succeeded, want error") + } + + objs := loadTestObjects(t, &ebpf.CollectionOptions{Maps: ebpf.MapOptions{PinPath: pinDir}}) + f, closer, err := OpenPinned(pinDir) + if err != nil { + t.Fatalf("OpenPinned: %v", err) + } + t.Cleanup(func() { _ = closer.Close() }) + + if err := f.SetConfig(Config{Mode: ModeAudit}); err != nil { + t.Fatalf("SetConfig through pin: %v", err) + } + var cfg prog.UsidSrcFilterConfig + if err := objs.SrcFilterConfigTable.Lookup(uint32(0), &cfg); err != nil { + t.Fatalf("read back config: %v", err) + } + if cfg.Mode != prog.SrcFilterModeAudit { + t.Errorf("pinned config mode = %d, want audit", cfg.Mode) + } +} diff --git a/internal/plumbing/ebpf/srcfiltermap/pin.go b/internal/plumbing/ebpf/srcfiltermap/pin.go new file mode 100644 index 000000000..7f4d8869e --- /dev/null +++ b/internal/plumbing/ebpf/srcfiltermap/pin.go @@ -0,0 +1,76 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfiltermap + +import ( + "errors" + "fmt" + "io" + "path/filepath" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" +) + +// OpenPinned opens every source filter map from its pin under pinDir, where +// each is pinned at /, and returns a Filter over them. +// +// The returned closer releases only this process's descriptors, never the +// maps' pinned lifetime. On error nothing is left open. +func OpenPinned(pinDir string) (*Filter, io.Closer, error) { + var opened closers + load := func(name string) usidmap.Table { + m, err := ebpf.LoadPinnedMap(filepath.Join(pinDir, name), nil) + if err != nil { + opened.errs = append(opened.errs, fmt.Errorf("open pinned map %q under %q: %w", name, pinDir, err)) + return nil + } + opened.maps = append(opened.maps, m) + return usidmap.KernelTable{Map: m} + } + + tables := Tables{ + Allow: load(prog.UsidMapSrcAllowTable), + UplinkSlots: load(prog.UsidMapUplinkSlotTable), + Config: load(prog.UsidMapSrcFilterConfigTable), + Stats: load(prog.UsidMapSrcFilterStats), + Denied: load(prog.UsidMapSrcFilterDenied), + } + if len(opened.errs) > 0 { + err := errors.Join(opened.errs...) + _ = opened.Close() + return nil, nil, fmt.Errorf("srcfiltermap: %w", err) + } + return New(tables), &opened, nil +} + +// NewFromObjects returns a Filter over the source filter maps of an already +// loaded datapath collection. The caller keeps ownership of objs. +func NewFromObjects(objs *prog.UsidObjects) *Filter { + return New(Tables{ + Allow: usidmap.KernelTable{Map: objs.SrcAllowTable}, + UplinkSlots: usidmap.KernelTable{Map: objs.UplinkSlotTable}, + Config: usidmap.KernelTable{Map: objs.SrcFilterConfigTable}, + Stats: usidmap.KernelTable{Map: objs.SrcFilterStats}, + Denied: usidmap.KernelTable{Map: objs.SrcFilterDenied}, + }) +} + +type closers struct { + maps []*ebpf.Map + errs []error +} + +func (c *closers) Close() error { + var errs []error + for _, m := range c.maps { + if err := m.Close(); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} diff --git a/internal/plumbing/ebpf/srcfiltermap/srcfilter.go b/internal/plumbing/ebpf/srcfiltermap/srcfilter.go new file mode 100644 index 000000000..db84777fc --- /dev/null +++ b/internal/plumbing/ebpf/srcfiltermap/srcfilter.go @@ -0,0 +1,482 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfiltermap + +import ( + "errors" + "fmt" + "net/netip" + "slices" + "strings" + + "github.com/cilium/ebpf" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" + "go.datum.net/galactic/internal/plumbing/ebpf/usidmap" +) + +// MaxSlots is the number of distinct uplinks an allow entry's interface mask +// can name. Valid slots are 0 through MaxSlots-1. +const MaxSlots = prog.SrcFilterMaxSlots + +// configKey is the only key of the single-entry src_filter_config_table. +const configKey uint32 = 0 + +// deniedPrefixBits is the width of the source prefix src_filter_denied records. +const deniedPrefixBits = 64 + +// Mode selects how the datapath acts on a source the filter rejects. +type Mode uint32 + +const ( + // ModeOff skips the filter entirely. + ModeOff = Mode(prog.SrcFilterModeOff) + // ModeAudit counts and records rejected sources but still delivers them. + ModeAudit = Mode(prog.SrcFilterModeAudit) + // ModeEnforce drops rejected sources. + ModeEnforce = Mode(prog.SrcFilterModeEnforce) +) + +// String returns the mode's configuration name. +func (m Mode) String() string { + switch m { + case ModeOff: + return "off" + case ModeAudit: + return "audit" + case ModeEnforce: + return "enforce" + default: + return fmt.Sprintf("unknown(%d)", uint32(m)) + } +} + +// ParseMode returns the Mode named by s, case-insensitively, or an error if s +// names none. +func ParseMode(s string) (Mode, error) { + for _, m := range []Mode{ModeOff, ModeAudit, ModeEnforce} { + if strings.EqualFold(strings.TrimSpace(s), m.String()) { + return m, nil + } + } + return ModeOff, fmt.Errorf("srcfiltermap: unknown mode %q (want off, audit or enforce)", s) +} + +func (m Mode) valid() bool { return m <= ModeEnforce } + +// Config is the filter's global state. +type Config struct { + Mode Mode + // Populated reports that the allow-list reflects a complete sync. While + // false, the datapath passes every packet whatever the mode. + Populated bool + // Generation is an opaque control-plane counter the datapath never reads. + Generation uint32 +} + +// Entry is one allowed source prefix. +type Entry struct { + // Prefix is an IPv6 prefix; Put stores it masked. + Prefix netip.Prefix + // IfaceMask has bit N set for every uplink assigned slot N. + IfaceMask uint32 + // AnyIface accepts the prefix on every interface, ignoring IfaceMask. + AnyIface bool +} + +// Stats is the sum of the datapath's per-CPU decision counters. +type Stats struct { + Checked uint64 + Allowed uint64 + DenyPrefix uint64 + DenyIface uint64 + BypassUnpopulated uint64 +} + +// DenyReason says why a source was rejected. +type DenyReason uint32 + +const ( + // DenyReasonPrefix means the source matched no allowed prefix. + DenyReasonPrefix = DenyReason(prog.SrcFilterStatDenyPrefix) + // DenyReasonIface means the source's prefix is not allowed on the arrival + // interface. + DenyReasonIface = DenyReason(prog.SrcFilterStatDenyIface) +) + +// String returns a stable, metrics-friendly name for the reason. +func (r DenyReason) String() string { + if name, ok := prog.SrcFilterStatNames[uint32(r)]; ok { + return name + } + return fmt.Sprintf("unknown(%d)", uint32(r)) +} + +// DeniedSource is one src_filter_denied record: a source /64 the filter has +// rejected, in audit or enforce mode. +type DeniedSource struct { + Prefix netip.Prefix + Count uint64 + LastIfindex uint32 + LastSeenNs uint64 + LastReason DenyReason +} + +// SyncResult counts what SyncAllow changed. +type SyncResult struct { + Added int + Updated int + Removed int + Unchanged int +} + +// Tables are the five maps a Filter reads and writes. +type Tables struct { + Allow usidmap.Table + UplinkSlots usidmap.Table + Config usidmap.Table + Stats usidmap.Table + Denied usidmap.Table +} + +// Filter is the read/write API over the source filter maps. It holds no state +// of its own, so it is safe for concurrent use whenever its tables are. +type Filter struct { + t Tables +} + +// New returns a Filter over tables. Production callers use OpenPinned; tests +// pass fakes. +func New(tables Tables) *Filter { + return &Filter{t: tables} +} + +// IfaceMask returns the interface mask naming every slot in slots, or an error +// if any slot is MaxSlots or above. +func IfaceMask(slots ...uint8) (uint32, error) { + var mask uint32 + for _, s := range slots { + if int(s) >= MaxSlots { + return 0, fmt.Errorf("srcfiltermap: uplink slot %d out of range [0,%d)", s, MaxSlots) + } + mask |= 1 << s + } + return mask, nil +} + +func allowKey(p netip.Prefix) (prog.UsidSrcAllowKey, netip.Prefix, error) { + if !p.IsValid() || !p.Addr().Is6() || p.Addr().Is4In6() { + return prog.UsidSrcAllowKey{}, netip.Prefix{}, fmt.Errorf("srcfiltermap: %s is not an IPv6 prefix", p) + } + p = p.Masked() + return prog.UsidSrcAllowKey{Prefixlen: uint32(p.Bits()), Addr: p.Addr().As16()}, p, nil +} + +func (e Entry) value() prog.UsidSrcAllowValue { + v := prog.UsidSrcAllowValue{IfaceMask: e.IfaceMask} + if e.AnyIface { + v.Flags |= prog.SrcFilterFlagAnyIface + } + return v +} + +// PutAllow creates or overwrites the allow entry for e.Prefix. It returns an +// error if e.Prefix is not an IPv6 prefix or the write fails. +func (f *Filter) PutAllow(e Entry) error { + key, p, err := allowKey(e.Prefix) + if err != nil { + return err + } + if err := f.t.Allow.Put(key, e.value()); err != nil { + return fmt.Errorf("srcfiltermap: src_allow_table: put %s: %w", p, err) + } + return nil +} + +// DeleteAllow removes the allow entry for p. An absent entry is not an error. +func (f *Filter) DeleteAllow(p netip.Prefix) error { + key, p, err := allowKey(p) + if err != nil { + return err + } + if err := f.t.Allow.Delete(key); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + return fmt.Errorf("srcfiltermap: src_allow_table: delete %s: %w", p, err) + } + return nil +} + +// ListAllow returns every allow entry, sorted by prefix. +func (f *Filter) ListAllow() ([]Entry, error) { + var ( + key prog.UsidSrcAllowKey + val prog.UsidSrcAllowValue + entries []Entry + ) + it := f.t.Allow.Iterate() + for it.Next(&key, &val) { + p := netip.PrefixFrom(netip.AddrFrom16(key.Addr), int(key.Prefixlen)) + entries = append(entries, Entry{ + Prefix: p, + IfaceMask: val.IfaceMask, + AnyIface: val.Flags&prog.SrcFilterFlagAnyIface != 0, + }) + } + if err := it.Err(); err != nil { + return nil, fmt.Errorf("srcfiltermap: src_allow_table: iterate: %w", err) + } + slices.SortFunc(entries, func(a, b Entry) int { return a.Prefix.Compare(b.Prefix) }) + return entries, nil +} + +// SyncAllow makes the allow-list exactly desired: it writes new and changed +// entries first and only then removes entries desired no longer names, so a +// prefix present in both the old and new sets is never briefly missing. +// Entries whose prefixes mask to the same value are an error, as is any +// invalid prefix; either leaves the map untouched. +func (f *Filter) SyncAllow(desired []Entry) (SyncResult, error) { + want := make(map[netip.Prefix]Entry, len(desired)) + for _, e := range desired { + _, p, err := allowKey(e.Prefix) + if err != nil { + return SyncResult{}, err + } + if _, dup := want[p]; dup { + return SyncResult{}, fmt.Errorf("srcfiltermap: duplicate allow entry for %s", p) + } + e.Prefix = p + want[p] = e + } + + current, err := f.ListAllow() + if err != nil { + return SyncResult{}, err + } + have := make(map[netip.Prefix]Entry, len(current)) + for _, e := range current { + have[e.Prefix] = e + } + + var res SyncResult + var errs []error + for _, p := range sortedPrefixes(want) { + e := want[p] + old, ok := have[p] + switch { + case ok && old == e: + res.Unchanged++ + continue + case ok: + res.Updated++ + default: + res.Added++ + } + if err := f.PutAllow(e); err != nil { + errs = append(errs, err) + } + } + if len(errs) > 0 { + return res, errors.Join(errs...) + } + for _, p := range sortedPrefixes(have) { + if _, ok := want[p]; ok { + continue + } + if err := f.DeleteAllow(p); err != nil { + errs = append(errs, err) + continue + } + res.Removed++ + } + return res, errors.Join(errs...) +} + +func sortedPrefixes(m map[netip.Prefix]Entry) []netip.Prefix { + out := make([]netip.Prefix, 0, len(m)) + for p := range m { + out = append(out, p) + } + slices.SortFunc(out, netip.Prefix.Compare) + return out +} + +// SetUplinkSlot assigns ifindex to slot, the bit an allow entry's interface +// mask uses to name it. It returns an error if slot is MaxSlots or above. +func (f *Filter) SetUplinkSlot(ifindex uint32, slot uint8) error { + if int(slot) >= MaxSlots { + return fmt.Errorf("srcfiltermap: uplink_slot_table: slot %d for ifindex %d out of range [0,%d)", + slot, ifindex, MaxSlots) + } + if err := f.t.UplinkSlots.Put(ifindex, uint32(slot)); err != nil { + return fmt.Errorf("srcfiltermap: uplink_slot_table: put ifindex %d: %w", ifindex, err) + } + return nil +} + +// DeleteUplinkSlot removes ifindex's slot. An absent entry is not an error. +func (f *Filter) DeleteUplinkSlot(ifindex uint32) error { + if err := f.t.UplinkSlots.Delete(ifindex); err != nil && !errors.Is(err, ebpf.ErrKeyNotExist) { + return fmt.Errorf("srcfiltermap: uplink_slot_table: delete ifindex %d: %w", ifindex, err) + } + return nil +} + +// UplinkSlots returns every ifindex-to-slot assignment. +func (f *Filter) UplinkSlots() (map[uint32]uint8, error) { + var ifindex, slot uint32 + out := make(map[uint32]uint8) + it := f.t.UplinkSlots.Iterate() + for it.Next(&ifindex, &slot) { + out[ifindex] = uint8(slot) + } + if err := it.Err(); err != nil { + return nil, fmt.Errorf("srcfiltermap: uplink_slot_table: iterate: %w", err) + } + return out, nil +} + +// SyncUplinkSlots makes the slot assignments exactly desired, writing before +// deleting. Two interfaces sharing a slot is an error and leaves the map +// untouched. +func (f *Filter) SyncUplinkSlots(desired map[uint32]uint8) error { + owner := make(map[uint8]uint32, len(desired)) + for ifindex, slot := range desired { + if int(slot) >= MaxSlots { + return fmt.Errorf("srcfiltermap: uplink slot %d for ifindex %d out of range [0,%d)", slot, ifindex, MaxSlots) + } + if other, dup := owner[slot]; dup { + return fmt.Errorf("srcfiltermap: uplink slot %d assigned to both ifindex %d and %d", + slot, min(other, ifindex), max(other, ifindex)) + } + owner[slot] = ifindex + } + + current, err := f.UplinkSlots() + if err != nil { + return err + } + var errs []error + for ifindex, slot := range desired { + if cur, ok := current[ifindex]; ok && cur == slot { + continue + } + if err := f.SetUplinkSlot(ifindex, slot); err != nil { + errs = append(errs, err) + } + } + if len(errs) > 0 { + return errors.Join(errs...) + } + for ifindex := range current { + if _, ok := desired[ifindex]; ok { + continue + } + if err := f.DeleteUplinkSlot(ifindex); err != nil { + errs = append(errs, err) + } + } + return errors.Join(errs...) +} + +// Config returns the filter's global state. A never-written config reads as +// ModeOff and unpopulated. +func (f *Filter) Config() (Config, error) { + var v prog.UsidSrcFilterConfig + if err := f.t.Config.Lookup(configKey, &v); err != nil { + if errors.Is(err, ebpf.ErrKeyNotExist) { + return Config{}, nil + } + return Config{}, fmt.Errorf("srcfiltermap: src_filter_config_table: lookup: %w", err) + } + return Config{Mode: Mode(v.Mode), Populated: v.Populated != 0, Generation: v.Generation}, nil +} + +// SetConfig writes the filter's global state. It returns an error for an +// unknown mode. +func (f *Filter) SetConfig(c Config) error { + if !c.Mode.valid() { + return fmt.Errorf("srcfiltermap: src_filter_config_table: invalid mode %s", c.Mode) + } + v := prog.UsidSrcFilterConfig{Mode: uint32(c.Mode), Generation: c.Generation} + if c.Populated { + v.Populated = 1 + } + if err := f.t.Config.Put(configKey, v); err != nil { + return fmt.Errorf("srcfiltermap: src_filter_config_table: put: %w", err) + } + return nil +} + +// Stats returns the datapath's decision counters summed across CPUs. +func (f *Filter) Stats() (Stats, error) { + read := func(slot uint32) (uint64, error) { + var perCPU []uint64 + if err := f.t.Stats.Lookup(slot, &perCPU); err != nil { + if errors.Is(err, ebpf.ErrKeyNotExist) { + return 0, nil + } + return 0, fmt.Errorf("srcfiltermap: src_filter_stats: lookup %s: %w", + prog.SrcFilterStatNames[slot], err) + } + var total uint64 + for _, v := range perCPU { + total += v + } + return total, nil + } + + var ( + s Stats + errs []error + ) + for slot, dst := range map[uint32]*uint64{ + prog.SrcFilterStatChecked: &s.Checked, + prog.SrcFilterStatAllowed: &s.Allowed, + prog.SrcFilterStatDenyPrefix: &s.DenyPrefix, + prog.SrcFilterStatDenyIface: &s.DenyIface, + prog.SrcFilterStatBypassUnpopulated: &s.BypassUnpopulated, + } { + v, err := read(slot) + if err != nil { + errs = append(errs, err) + continue + } + *dst = v + } + return s, errors.Join(errs...) +} + +// DeniedSources returns every recorded denied source /64, most denials first. +func (f *Filter) DeniedSources() ([]DeniedSource, error) { + var ( + key prog.UsidSrcDeniedKey + val prog.UsidSrcDeniedValue + out []DeniedSource + ) + it := f.t.Denied.Iterate() + for it.Next(&key, &val) { + var a [16]byte + copy(a[:], key.Prefix[:]) + out = append(out, DeniedSource{ + Prefix: netip.PrefixFrom(netip.AddrFrom16(a), deniedPrefixBits), + Count: val.Count, + LastIfindex: val.LastIfindex, + LastSeenNs: val.LastNs, + LastReason: DenyReason(val.LastReason), + }) + } + if err := it.Err(); err != nil { + return nil, fmt.Errorf("srcfiltermap: src_filter_denied: iterate: %w", err) + } + slices.SortFunc(out, func(a, b DeniedSource) int { + if a.Count != b.Count { + if a.Count > b.Count { + return -1 + } + return 1 + } + return a.Prefix.Compare(b.Prefix) + }) + return out, nil +} diff --git a/internal/plumbing/ebpf/srcfiltermap/srcfilter_test.go b/internal/plumbing/ebpf/srcfiltermap/srcfilter_test.go new file mode 100644 index 000000000..56e02ce4c --- /dev/null +++ b/internal/plumbing/ebpf/srcfiltermap/srcfilter_test.go @@ -0,0 +1,320 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package srcfiltermap + +import ( + "errors" + "net/netip" + "reflect" + "testing" + + "go.datum.net/galactic/internal/plumbing/ebpf/prog" +) + +func TestParseMode(t *testing.T) { + tests := []struct { + in string + want Mode + wantError bool + }{ + {"off", ModeOff, false}, + {"Audit", ModeAudit, false}, + {" enforce ", ModeEnforce, false}, + {"", ModeOff, true}, + {"drop", ModeOff, true}, + } + for _, tt := range tests { + t.Run(tt.in, func(t *testing.T) { + got, err := ParseMode(tt.in) + if (err != nil) != tt.wantError { + t.Fatalf("ParseMode(%q) error = %v, wantError = %v", tt.in, err, tt.wantError) + } + if got != tt.want { + t.Errorf("ParseMode(%q) = %s, want %s", tt.in, got, tt.want) + } + }) + } +} + +func TestIfaceMask(t *testing.T) { + tests := []struct { + name string + slots []uint8 + want uint32 + wantError bool + }{ + {"None", nil, 0, false}, + {"Single", []uint8{3}, 1 << 3, false}, + {"Several", []uint8{0, 5, 31}, 1 | 1<<5 | 1<<31, false}, + {"OutOfRange", []uint8{32}, 0, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := IfaceMask(tt.slots...) + if (err != nil) != tt.wantError { + t.Fatalf("IfaceMask(%v) error = %v, wantError = %v", tt.slots, err, tt.wantError) + } + if got != tt.want { + t.Errorf("IfaceMask(%v) = %#x, want %#x", tt.slots, got, tt.want) + } + }) + } +} + +func TestPutAllow(t *testing.T) { + f, tables := NewFake() + + if err := f.PutAllow(Entry{Prefix: netip.MustParsePrefix("fd00:aa:1::5/48"), IfaceMask: 1 << 2}); err != nil { + t.Fatalf("PutAllow: %v", err) + } + if err := f.PutAllow(Entry{Prefix: netip.MustParsePrefix("fd00:bb::/32"), AnyIface: true}); err != nil { + t.Fatalf("PutAllow: %v", err) + } + + var v prog.UsidSrcAllowValue + key := prog.UsidSrcAllowKey{Prefixlen: 48, Addr: netip.MustParseAddr("fd00:aa:1::").As16()} + if err := tables.Allow.Lookup(key, &v); err != nil { + t.Fatalf("stored key not masked: %v", err) + } + if v.IfaceMask != 1<<2 || v.Flags != 0 { + t.Errorf("stored value = %+v, want mask 0x4 and no flags", v) + } + key = prog.UsidSrcAllowKey{Prefixlen: 32, Addr: netip.MustParseAddr("fd00:bb::").As16()} + if err := tables.Allow.Lookup(key, &v); err != nil { + t.Fatalf("lookup any-iface entry: %v", err) + } + if v.Flags != prog.SrcFilterFlagAnyIface { + t.Errorf("stored flags = %#x, want SrcFilterFlagAnyIface", v.Flags) + } + + got, err := f.ListAllow() + if err != nil { + t.Fatalf("ListAllow: %v", err) + } + want := []Entry{ + {Prefix: netip.MustParsePrefix("fd00:aa:1::/48"), IfaceMask: 1 << 2}, + {Prefix: netip.MustParsePrefix("fd00:bb::/32"), AnyIface: true}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("ListAllow = %+v, want %+v", got, want) + } +} + +func TestPutAllowRejectsNonIPv6(t *testing.T) { + f, _ := NewFake() + for _, p := range []netip.Prefix{ + {}, + netip.MustParsePrefix("10.0.0.0/8"), + netip.MustParsePrefix("::ffff:10.0.0.0/104"), + } { + if err := f.PutAllow(Entry{Prefix: p, AnyIface: true}); err == nil { + t.Errorf("PutAllow(%s) succeeded, want error", p) + } + } +} + +func TestDeleteAllowAbsentIsNotError(t *testing.T) { + f, _ := NewFake() + if err := f.DeleteAllow(netip.MustParsePrefix("fd00::/16")); err != nil { + t.Errorf("DeleteAllow on absent entry: %v", err) + } +} + +func TestSyncAllow(t *testing.T) { + f, tables := NewFake() + keep := Entry{Prefix: netip.MustParsePrefix("fd00:1::/32"), IfaceMask: 1} + change := Entry{Prefix: netip.MustParsePrefix("fd00:2::/32"), IfaceMask: 1} + stale := Entry{Prefix: netip.MustParsePrefix("fd00:3::/32"), IfaceMask: 1} + for _, e := range []Entry{keep, change, stale} { + if err := f.PutAllow(e); err != nil { + t.Fatalf("seed %s: %v", e.Prefix, err) + } + } + + changed := Entry{Prefix: change.Prefix, IfaceMask: 1 | 1<<1} + added := Entry{Prefix: netip.MustParsePrefix("fd00:4::/32"), AnyIface: true} + res, err := f.SyncAllow([]Entry{keep, changed, added}) + if err != nil { + t.Fatalf("SyncAllow: %v", err) + } + if want := (SyncResult{Added: 1, Updated: 1, Removed: 1, Unchanged: 1}); res != want { + t.Errorf("SyncAllow result = %+v, want %+v", res, want) + } + got, err := f.ListAllow() + if err != nil { + t.Fatalf("ListAllow: %v", err) + } + if want := []Entry{keep, changed, added}; !reflect.DeepEqual(got, want) { + t.Errorf("after sync = %+v, want %+v", got, want) + } + if n := tables.Allow.(*FakeTable).Len(); n != 3 { + t.Errorf("table holds %d entries, want 3", n) + } +} + +func TestSyncAllowRejectsInvalidInputUntouched(t *testing.T) { + tests := []struct { + name string + desired []Entry + }{ + {"Duplicate", []Entry{ + {Prefix: netip.MustParsePrefix("fd00:1::1/32")}, + {Prefix: netip.MustParsePrefix("fd00:1::2/32")}, + }}, + {"IPv4", []Entry{{Prefix: netip.MustParsePrefix("10.0.0.0/8")}}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f, tables := NewFake() + seed := Entry{Prefix: netip.MustParsePrefix("fd00:9::/32"), AnyIface: true} + if err := f.PutAllow(seed); err != nil { + t.Fatalf("seed: %v", err) + } + if _, err := f.SyncAllow(tt.desired); err == nil { + t.Fatal("SyncAllow succeeded, want error") + } + if n := tables.Allow.(*FakeTable).Len(); n != 1 { + t.Errorf("table holds %d entries, want the untouched seed only", n) + } + }) + } +} + +func TestSyncAllowWriteFailureKeepsStaleEntries(t *testing.T) { + f, tables := NewFake() + stale := Entry{Prefix: netip.MustParsePrefix("fd00:3::/32"), AnyIface: true} + if err := f.PutAllow(stale); err != nil { + t.Fatalf("seed: %v", err) + } + tables.Allow.(*FakeTable).PutErr = errors.New("map full") + + if _, err := f.SyncAllow([]Entry{{Prefix: netip.MustParsePrefix("fd00:4::/32"), AnyIface: true}}); err == nil { + t.Fatal("SyncAllow succeeded, want the write error") + } + got, err := f.ListAllow() + if err != nil { + t.Fatalf("ListAllow: %v", err) + } + if want := []Entry{stale}; !reflect.DeepEqual(got, want) { + t.Errorf("after failed sync = %+v, want stale entry kept: %+v", got, want) + } +} + +func TestUplinkSlots(t *testing.T) { + f, _ := NewFake() + if err := f.SetUplinkSlot(7, 32); err == nil { + t.Error("SetUplinkSlot with slot 32 succeeded, want error") + } + if err := f.SetUplinkSlot(7, 0); err != nil { + t.Fatalf("SetUplinkSlot: %v", err) + } + if err := f.SetUplinkSlot(9, 1); err != nil { + t.Fatalf("SetUplinkSlot: %v", err) + } + + if err := f.SyncUplinkSlots(map[uint32]uint8{7: 0, 11: 2}); err != nil { + t.Fatalf("SyncUplinkSlots: %v", err) + } + got, err := f.UplinkSlots() + if err != nil { + t.Fatalf("UplinkSlots: %v", err) + } + if want := map[uint32]uint8{7: 0, 11: 2}; !reflect.DeepEqual(got, want) { + t.Errorf("UplinkSlots = %v, want %v", got, want) + } + + if err := f.SyncUplinkSlots(map[uint32]uint8{7: 1, 11: 1}); err == nil { + t.Error("SyncUplinkSlots with a shared slot succeeded, want error") + } + if err := f.DeleteUplinkSlot(7); err != nil { + t.Errorf("DeleteUplinkSlot: %v", err) + } + if err := f.DeleteUplinkSlot(7); err != nil { + t.Errorf("DeleteUplinkSlot on absent entry: %v", err) + } +} + +func TestConfig(t *testing.T) { + f, _ := NewFake() + + got, err := f.Config() + if err != nil { + t.Fatalf("Config: %v", err) + } + if got != (Config{}) { + t.Errorf("unwritten Config = %+v, want off and unpopulated", got) + } + + want := Config{Mode: ModeAudit, Populated: true, Generation: 4} + if err := f.SetConfig(want); err != nil { + t.Fatalf("SetConfig: %v", err) + } + if got, err = f.Config(); err != nil || got != want { + t.Errorf("Config = %+v, %v, want %+v", got, err, want) + } + + if err := f.SetConfig(Config{Mode: Mode(9)}); err == nil { + t.Error("SetConfig with an unknown mode succeeded, want error") + } +} + +func TestStats(t *testing.T) { + f, tables := NewFake() + seed := map[uint32][]uint64{ + prog.SrcFilterStatChecked: {3, 4}, + prog.SrcFilterStatAllowed: {2, 1}, + prog.SrcFilterStatDenyPrefix: {1, 0}, + prog.SrcFilterStatDenyIface: {0, 2}, + prog.SrcFilterStatBypassUnpopulated: {0, 1}, + } + for slot, v := range seed { + if err := tables.Stats.Put(slot, v); err != nil { + t.Fatalf("seed stats: %v", err) + } + } + + got, err := f.Stats() + if err != nil { + t.Fatalf("Stats: %v", err) + } + want := Stats{Checked: 7, Allowed: 3, DenyPrefix: 1, DenyIface: 2, BypassUnpopulated: 1} + if got != want { + t.Errorf("Stats = %+v, want %+v", got, want) + } +} + +func TestDeniedSources(t *testing.T) { + f, tables := NewFake() + put := func(src string, v prog.UsidSrcDeniedValue) { + t.Helper() + var key prog.UsidSrcDeniedKey + a := netip.MustParseAddr(src).As16() + copy(key.Prefix[:], a[:8]) + if err := tables.Denied.Put(key, v); err != nil { + t.Fatalf("seed denied: %v", err) + } + } + put("2001:db8:1:2::9", prog.UsidSrcDeniedValue{Count: 2, LastNs: 10, LastIfindex: 4, + LastReason: prog.SrcFilterStatDenyPrefix}) + put("fd00:aa:1:2::1", prog.UsidSrcDeniedValue{Count: 5, LastNs: 20, LastIfindex: 5, + LastReason: prog.SrcFilterStatDenyIface}) + + got, err := f.DeniedSources() + if err != nil { + t.Fatalf("DeniedSources: %v", err) + } + want := []DeniedSource{ + {Prefix: netip.MustParsePrefix("fd00:aa:1:2::/64"), Count: 5, LastIfindex: 5, LastSeenNs: 20, + LastReason: DenyReasonIface}, + {Prefix: netip.MustParsePrefix("2001:db8:1:2::/64"), Count: 2, LastIfindex: 4, LastSeenNs: 10, + LastReason: DenyReasonPrefix}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("DeniedSources = %+v, want %+v", got, want) + } + if got[0].LastReason.String() != "deny_iface" { + t.Errorf("reason name = %q, want deny_iface", got[0].LastReason) + } +}