Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/traffic-policy/node.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ compiled differently is republished, starting its rules from zero. A
snapshot on an interface no attachment claims within one resync is unbound,
and its rows are freed.

To read a snapshot back, galactic-router pins each one it publishes under
`tp_snapshots/` in the datapath's pin directory, beside the policy maps, and
galactic-cni removes the pin when it unbinds the snapshot. On its first
reconcile and at most once every five minutes after, galactic-router removes
any pin that holds no bound snapshot, such as one left by a publish that an
interface's removal or a restart interrupted. Until then, such a pin holds its
snapshot's memory. The kernel opens a map
by ID only for `CAP_SYS_ADMIN`, which galactic-router does not have (it runs
with `NET_ADMIN` and `BPF`), so a snapshot without a matching pin, such as
one bound by a release that did not pin, cannot be read. galactic-router
adopts it as empty and logs it: it stays bound, so traffic keeps its
current verdict, until the next reconcile republishes it with fresh counter
rows or the sweep unbinds it. Until then its rules can count into rows
another snapshot was given, so those counters can over-count for that
window; verdicts are unaffected.

A rebind that cannot be installed, such as one that runs out of counter
rows, unbinds the direction rather than keeping the old policy's grants,
and reports `Failed`. A failed update of the same policy keeps its last
Expand Down
9 changes: 9 additions & 0 deletions docs/traffic-policy/rollout.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ Check every node of the cell:
which the cloud operator writes. An attachment without them is never bound
on any node, and denies everything once enforced.

`galactic-router` needs `NET_ADMIN` and `BPF`, as `config/galactic-router/`
grants, and not `CAP_SYS_ADMIN`: it reads back the snapshots it bound before
a restart from their pins (see
[Traffic policy on the node](node.md#what-it-applies)). The first restart
after upgrading from a release that did not pin snapshots republishes every
snapshot bound on the node, so their rule counters start again from zero.
Until each one is republished, its rules can count into rows another snapshot
was given.

## Steps

1. **Install the cell controller.** Apply `config/galactic-controller/` (its
Expand Down
48 changes: 48 additions & 0 deletions internal/captest/captest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Copyright 2026 Datum Cloud, Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

// Package captest runs test code with fewer capabilities than the root test
// process has, to check that code works under a container's narrower set.
//
// It is a regular importable package rather than a test file, since one
// package's test files cannot import another's.
package captest

import (
"runtime"
"testing"

"golang.org/x/sys/unix"
)

// WithoutSysAdmin runs fn on an OS thread whose effective capabilities lack
// CAP_SYS_ADMIN, as galactic-router's container does, and waits for it.
// Capabilities are per thread, so fn must make its system calls from its own
// goroutine: a goroutine fn starts runs on other threads, with the full set.
// Since fn does not run on the test goroutine, it reports failures with
// t.Error rather than t.Fatal. The thread exits with fn, so the
// rest of the test keeps the full set.
func WithoutSysAdmin(t *testing.T, fn func()) {
t.Helper()
done := make(chan struct{})
go func() {
defer close(done)
// Never unlocked: the runtime destroys a locked thread when its
// goroutine exits, so no other goroutine inherits the reduced set.
runtime.LockOSThread()
hdr := unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3}
var data [2]unix.CapUserData
if err := unix.Capget(&hdr, &data[0]); err != nil {
t.Errorf("capget: %v", err)
return
}
data[unix.CAP_SYS_ADMIN/32].Effective &^= 1 << (unix.CAP_SYS_ADMIN % 32)
if err := unix.Capset(&hdr, &data[0]); err != nil {
t.Errorf("drop CAP_SYS_ADMIN: %v", err)
return
}
fn()
}()
<-done
}
2 changes: 1 addition & 1 deletion internal/installer/installer.go
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ func startEBPFDatapath(ctx context.Context, m *metrics.Metrics) (ebpfDatapathSta
// wiring below inert.
if objs, ok := datapath.(*prog.UsidObjects); ok {
state.objs = objs
state.trafficPolicy = startTrafficPolicy(objs, policyCfg)
state.trafficPolicy = startTrafficPolicy(objs, attach.PinDir, policyCfg)
state.mssClamp = newMSSClampState(objs.MssClampTable, objs.EncapMtuTable)
state.mssClamp.reconcile()
state.egressGroup.counters = objs.EgressShardCounters
Expand Down
4 changes: 2 additions & 2 deletions internal/installer/trafficpolicy.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ var trafficPolicyModes = map[string]uint32{
// startTrafficPolicy runs the traffic policy preflight and writes the node's
// mode. The NAT locators start unsynced, so until setNATLocators runs an
// encapsulating route's path is unknown and a rule naming a path denies it.
func startTrafficPolicy(objs *prog.UsidObjects, cfg config.TrafficPolicyConfig) *trafficPolicyState {
func startTrafficPolicy(objs *prog.UsidObjects, pinDir string, cfg config.TrafficPolicyConfig) *trafficPolicyState {
s := &trafficPolicyState{
maps: tpmap.FromObjects(objs),
maps: tpmap.FromPinnedObjects(objs, pinDir),
state: tpmap.State{Mode: trafficPolicyModes[cfg.Mode], Mark: cfg.Mark, Capable: true},
}
if err := preflight.CheckTrafficPolicy(cfg.KernelCheck); err != nil {
Expand Down
242 changes: 242 additions & 0 deletions internal/plumbing/ebpf/tpmap/snapshotpin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
// Copyright 2026 Datum Cloud, Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package tpmap

import (
"errors"
"fmt"
"os"
"path/filepath"
"testing"

"github.com/cilium/ebpf"

"go.datum.net/galactic/internal/captest"
"go.datum.net/galactic/internal/plumbing/ebpf/prog"
"go.datum.net/galactic/internal/trafficpolicy"
)

// pinned pins f's traffic policy maps in a fresh bpffs directory and returns
// them opened from there, as galactic-router and the CNI plugins open them.
func (f *fixture) pinned(t *testing.T) (*Maps, string) {
t.Helper()
dir := filepath.Join("/sys/fs/bpf", fmt.Sprintf("galactic-tpmap-test-%d", os.Getpid()))
if err := os.MkdirAll(dir, 0o700); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.RemoveAll(dir) })
for name, mp := range map[string]interface{ Pin(string) error }{
prog.UsidMapTpState: f.objs.TpState,
prog.UsidMapTpIfaceTable: f.objs.TpIfaceTable,
prog.UsidMapTpIfaceAddrTable: f.objs.TpIfaceAddrTable,
prog.UsidMapTpBindingTable: f.objs.TpBindingTable,
prog.UsidMapTpNatLocatorTable: f.objs.TpNatLocatorTable,
prog.UsidMapTpRuleCounters: f.objs.TpRuleCounters,
prog.UsidMapTpFallbackCounters: f.objs.TpFallbackCounters,
prog.UsidMapTpUnattributedCounters: f.objs.TpUnattributedCounters,
prog.UsidMapTpAccountingErrors: f.objs.TpAccountingErrors,
} {
if err := mp.Pin(filepath.Join(dir, name)); err != nil {
t.Fatal(err)
}
}
m, err := OpenPinned(dir)
if err != nil {
t.Fatal(err)
}
t.Cleanup(m.Close)
return m, dir
}

func snapshotPins(t *testing.T, dir string) []string {
t.Helper()
entries, err := os.ReadDir(filepath.Join(dir, snapshotPinDir))
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
t.Fatal(err)
}
var names []string
for _, e := range entries {
names = append(names, e.Name())
}
return names
}

func publishRules(t *testing.T, m *Maps, rules string, base uint32) {
t.Helper()
snap := Snapshot{Token: token, CounterBase: base, Generation: 3}
entries, err := trafficpolicy.Compile(policy(t, rules))
if err != nil {
t.Fatal(err)
}
snap.Entries = entries
if err := m.PublishSnapshot(ifindex, DirEgress, snap); err != nil {
t.Fatal(err)
}
}

// TestReadSnapshotWithoutSysAdmin: a process without CAP_SYS_ADMIN, such as
// galactic-router after a restart, lists and reads back every snapshot bound
// through pinned maps.
func TestReadSnapshotWithoutSysAdmin(t *testing.T) {
f := newFixture(t, ModeAudit)
f.iface(t)
m, dir := f.pinned(t)
publishRules(t, m, `[{"name":"a","action":"Allow"},{"name":"b","action":"Deny"}]`, 5)

captest.WithoutSysAdmin(t, func() {
restarted, err := OpenPinned(dir)
if err != nil {
t.Error(err)
return
}
defer restarted.Close()
keys, err := restarted.BoundKeys()
if err != nil || len(keys) != 1 || keys[0].Ifindex != ifindex || keys[0].Direction != DirEgress {
t.Errorf("BoundKeys = %v, %v; want ifindex %d egress", keys, err, ifindex)
}
snap, ok, err := restarted.ReadSnapshot(ifindex, DirEgress)
if err != nil || !ok {
t.Errorf("ReadSnapshot = %v, %v", ok, err)
return
}
if snap.Token != token || snap.CounterBase != 5 || snap.Generation != 3 || len(snap.Entries) != 2 {
t.Errorf("snapshot = %+v, want token %#x, base 5, generation 3, 2 entries", snap, token)
}
if _, ok, err := restarted.ReadSnapshot(ifindex, DirIngress); ok || err != nil {
t.Errorf("unbound direction: ReadSnapshot = %v, %v; want none", ok, err)
}
})
}

// TestRepublishReplacesPin: each key keeps exactly one pin, the bound one.
func TestRepublishReplacesPin(t *testing.T) {
f := newFixture(t, ModeAudit)
f.iface(t)
m, dir := f.pinned(t)
publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0)
publishRules(t, m, `[{"name":"a","action":"Allow"},{"name":"b","action":"Deny"}]`, 7)
if pins := snapshotPins(t, dir); len(pins) != 1 || pins[0] != fmt.Sprintf("%d-%d", ifindex, DirEgress) {
t.Fatalf("pins = %v, want one for ifindex %d egress", pins, ifindex)
}
captest.WithoutSysAdmin(t, func() {
snap, ok, err := m.ReadSnapshot(ifindex, DirEgress)
if err != nil || !ok || snap.CounterBase != 7 {
t.Errorf("ReadSnapshot = %+v, %v, %v; want the second snapshot", snap, ok, err)
}
})
}

// TestUnbindingRemovesPin: Invalidate and RemoveInterface, which the CNI
// plugins call on DEL, leave no pin holding an unbound snapshot.
func TestUnbindingRemovesPin(t *testing.T) {
f := newFixture(t, ModeAudit)
f.iface(t)
m, dir := f.pinned(t)
publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0)
if err := m.Invalidate(ifindex, DirEgress); err != nil {
t.Fatal(err)
}
if pins := snapshotPins(t, dir); len(pins) != 0 {
t.Errorf("after Invalidate: pins = %v, want none", pins)
}
publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0)
if err := RemovePinnedInterface(dir, ifindex); err != nil {
t.Fatal(err)
}
if pins := snapshotPins(t, dir); len(pins) != 0 {
t.Errorf("after RemovePinnedInterface: pins = %v, want none", pins)
}
// galactic-cni removes a vanished interface through the objects it loaded.
publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0)
if err := FromPinnedObjects(f.objs, dir).RemoveInterface(ifindex); err != nil {
t.Fatal(err)
}
if pins := snapshotPins(t, dir); len(pins) != 0 {
t.Errorf("after RemoveInterface on the loaded objects: pins = %v, want none", pins)
}
}

// TestSweepPins: without CAP_SYS_ADMIN, the sweep keeps the pin of a bound
// snapshot and removes a temporary pin, the pin of an unbound key, and a pin
// whose key is bound to another map.
func TestSweepPins(t *testing.T) {
f := newFixture(t, ModeAudit)
f.iface(t)
m, dir := f.pinned(t)
const other uint32 = 2
publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0)
if err := m.Publish(ifindex, DirIngress, token, 1, nil); err != nil {
t.Fatal(err)
}
if err := m.Publish(other, DirEgress, token, 2, nil); err != nil {
t.Fatal(err)
}
// f.maps manages no pins, so these leave an unbound and a stale pin.
if err := f.maps.Invalidate(ifindex, DirIngress); err != nil {
t.Fatal(err)
}
if err := f.maps.Publish(other, DirEgress, token, 3, nil); err != nil {
t.Fatal(err)
}
leftover, err := ebpf.NewMap(&SnapshotSpec)
if err != nil {
t.Fatal(err)
}
defer leftover.Close() //nolint:errcheck // test handle
if err := leftover.Pin(filepath.Join(dir, snapshotPinDir, "tmp-1-1-0123456789abcdef")); err != nil {
t.Fatal(err)
}
if pins := snapshotPins(t, dir); len(pins) != 4 {
t.Fatalf("pins before the sweep = %v, want 4", pins)
}

captest.WithoutSysAdmin(t, func() {
if err := m.SweepPins(); err != nil {
t.Errorf("SweepPins: %v", err)
}
})
want := fmt.Sprintf("%d-%d", ifindex, DirEgress)
if pins := snapshotPins(t, dir); len(pins) != 1 || pins[0] != want {
t.Errorf("pins after the sweep = %v, want only %s", pins, want)
}
}

// TestUnmatchedSnapshotIsUnreadable: a snapshot bound without a pin, or whose
// pin holds another map, is reported unreadable without CAP_SYS_ADMIN rather
// than read from the wrong map, and is still read by ID with it.
func TestUnmatchedSnapshotIsUnreadable(t *testing.T) {
f := newFixture(t, ModeAudit)
f.iface(t)
m, dir := f.pinned(t)
publishRules(t, m, `[{"name":"a","action":"Allow"}]`, 0)
// f.maps has no pin directory, so this binding leaves the pin stale.
publishRules(t, f.maps, `[{"name":"a","action":"Allow"},{"name":"b","action":"Deny"}]`, 9)
if pins := snapshotPins(t, dir); len(pins) != 1 {
t.Fatalf("pins = %v, want the stale one", pins)
}
unreadable := func() {
captest.WithoutSysAdmin(t, func() {
if _, err := m.BoundKeys(); err != nil {
t.Errorf("BoundKeys: %v", err)
}
_, _, err := m.ReadSnapshot(ifindex, DirEgress)
if !errors.Is(err, ErrSnapshotUnreadable) {
t.Errorf("ReadSnapshot err = %v, want ErrSnapshotUnreadable", err)
}
})
}
unreadable()
if snap, ok, err := m.ReadSnapshot(ifindex, DirEgress); err != nil || !ok || snap.CounterBase != 9 {
t.Errorf("with CAP_SYS_ADMIN: ReadSnapshot = %+v, %v, %v; want the bound snapshot", snap, ok, err)
}

if err := os.Remove(filepath.Join(dir, snapshotPinDir, fmt.Sprintf("%d-%d", ifindex, DirEgress))); err != nil {
t.Fatal(err)
}
unreadable()
}
Loading
Loading