Skip to content
Draft
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
27 changes: 22 additions & 5 deletions pkg/ebpf/gadgets/common/enforcement/bindings.go
Original file line number Diff line number Diff line change
Expand Up @@ -660,8 +660,14 @@ func (b *Bindings) bind(c Binding) error {
if err := check(); err != nil {
if errors.Is(err, ErrContainerGone) {
// Gone: nothing to protect; drop it as a failed fresh bind.
// A failed delete of its entry is not a benign
// disappearance: its error does not match
// ErrContainerGone, so start and retryMoves (which skip a
// gone container) report it, and the entry and any
// recorded move stay until a retry removes them
// (CodeRabbit #1160 4802841890).
if derr := b.members.Delete(id.CgroupID); derr != nil && !errors.Is(derr, ebpf.ErrKeyNotExist) {
return errors.Join(err, derr)
return fmt.Errorf("removing the binding of a gone container (%v): %w", err, derr)
}
delete(b.adopted, id.CgroupID)
delete(b.active, id.CgroupID)
Expand Down Expand Up @@ -814,9 +820,17 @@ func (b *Bindings) bind(c Binding) error {
// reason: remove the entry it wrote, so the cgroup is as before
// the call and the caller sees the error. A container that is
// gone needs no protection; a startup replay skips it, and keeps
// an unrecorded Strict pending binding (see start).
if derr := b.members.Delete(id.CgroupID); derr != nil {
// an unrecorded Strict pending binding (see start). A gone
// container whose entry could not be removed is not skipped:
// the error does not match ErrContainerGone (CodeRabbit #1160
// 4802841890). An entry already absent (ErrKeyNotExist: an
// in-place replacement raced the old instance's unbind of the
// same cgroup) is removed, as in the preflight.
if derr := b.members.Delete(id.CgroupID); derr != nil && !errors.Is(derr, ebpf.ErrKeyNotExist) {
b.keepFailed(c, checked)
if errors.Is(err, ErrContainerGone) {
return fmt.Errorf("removing the binding of a gone container (%v): %w", err, derr)
}
return errors.Join(err, derr)
}
delete(b.active, id.CgroupID)
Expand Down Expand Up @@ -1505,9 +1519,12 @@ func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witn
// hold). Not a start failure: the pending entry is kept and c
// recorded (keepRefusedMove), never c installed.
err = b.keepRefusedMove(c, v)
case errors.Is(err, ErrCredUnrecorded):
case errors.Is(err, ErrCredUnrecorded) && c.Slot == PendingSlot:
// A Strict pending c whose walk could not record every task
// (only a walk with pending semantics reports it).
// (only a walk with pending semantics reports it). Never a
// real-slot c, whatever the case order: keepUnrecorded would
// install it without its credentials; such an error fails
// the start (copilot-19 review LOW 3).
err = b.keepUnrecorded(c)
case distrusted && errors.Is(err, ErrIoUringHeld) && c.Slot == PendingSlot && c.Strict:
// The take-over found a ring. Not a start failure: a
Expand Down
146 changes: 146 additions & 0 deletions pkg/ebpf/gadgets/common/enforcement/pending_followups_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
// Copyright 2026 The Kubescape Authors
// SPDX-License-Identifier: Apache-2.0

package enforcement

import (
"errors"
"fmt"
"testing"

"github.com/cilium/ebpf"
)

// A live bind of a cgroup with a refused start move, to another Strict slot,
// whose preflight cannot record every credential (ErrCredUnrecorded, not a
// held ring) records the newer wish (hadMove): the pending entry stays, the
// newer slot is unconfirmed, and a heal moves the cgroup there once the
// record has room, never to the older wish (copilot-19 review LOW 1, M3).
func TestBindAttemptReplacesRefusedMoveOnUnrecordedCreds(t *testing.T) {
c9 := ContainerIdentity{Runtime: "containerd", ID: "c9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"}
pendingValue := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked}
full := true
f := newPublishFixtureWith(t, func(f *publishFixture) {
f.members.data[c9.CgroupID] = pendingValue
f.b.config.InitialPublications = []Publication{f.publication(1, 10, true), f.publication(2, 20, true)}
f.b.desired[selector(c9)] = Binding{Container: c9, Slot: 1}
f.b.recordCreds = func(_ uint64, _ string, flags, slot uint32) (bool, error) {
if full {
return false, fullRecordFor(flags, slot)
}
return false, nil
}
f.armed = &fakeMap{typ: ebpf.TaskStorage}
f.witness = fakeWitness{0: 2}
})
if f.b.moves[c9.CgroupID] != (Binding{Container: c9, Slot: 1}) {
t.Fatalf("fixture: a refused start move to slot 1: %+v", f.b.moves)
}
kept := f.members.data[c9.CgroupID]
newer := Binding{Container: c9, Slot: 2}
if err := f.b.Bind(newer); !errors.Is(err, ErrCredUnrecorded) {
t.Fatalf("Bind: %v", err)
}
if f.b.moves[c9.CgroupID] != newer || f.b.RingUnconfirmed(1) != 0 || f.b.RingUnconfirmed(2) != 1 {
t.Fatalf("moves %+v, unconfirmed slot 1 %d, slot 2 %d", f.b.moves, f.b.RingUnconfirmed(1), f.b.RingUnconfirmed(2))
}
if v := f.members.data[c9.CgroupID]; v != kept {
t.Fatalf("the pending entry stays: %+v, was %+v", v, kept)
}
full = false
if err := f.b.HealNode(); err != nil {
t.Fatal(err)
}
if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != 2 || len(f.b.moves) != 0 {
t.Fatalf("the heal moves the cgroup to the newer wish: %+v, moves %+v", v, f.b.moves)
}
}

// A heal's retry of a refused move whose cgroup is gone removes its entry;
// a failed delete is not a benign disappearance: the heal fails (the error
// does not match ErrContainerGone) and the entry and the move record stay
// until a retry removes them (CodeRabbit #1160 4802841890).
func TestRetriedMoveOfGoneCgroupFailedDeleteFailsHeal(t *testing.T) {
ring := true
f, c9 := refusedMoveFixture(t, &ring)
f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, ErrContainerGone }
f.members.deleteErr = errors.New("busy")
err := f.b.HealNode()
if err == nil || errors.Is(err, ErrContainerGone) {
t.Fatalf("HealNode: %v, want a failure that is not a gone container", err)
}
if _, ok := f.b.moves[c9.CgroupID]; !ok {
t.Fatalf("the move record stays: %+v", f.b.moves)
}
if _, ok := f.members.data[c9.CgroupID]; !ok {
t.Fatal("the entry stays while its delete fails")
}
f.members.deleteErr = nil
if err := f.b.HealNode(); err != nil {
t.Fatalf("HealNode after the delete succeeds: %v", err)
}
if _, ok := f.members.data[c9.CgroupID]; ok || len(f.b.moves) != 0 {
t.Fatalf("entry %v, moves %+v", f.members.data, f.b.moves)
}
}

// A startup bind of a gone container whose entry cannot be removed fails the
// start: only a gone container that leaves nothing behind is skipped
// (TestStartSkipsGoneContainer; CodeRabbit #1160 4802841890).
func TestStartGoneContainerFailedDeleteFailsStart(t *testing.T) {
b, policy, members, _ := newFixture(t, func(Map) error { return nil })
b.armExisting = func(Map, string) error { return ErrContainerGone }
members.deleteErr = errors.New("busy")
err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil)
if err == nil || errors.Is(err, ErrContainerGone) {
t.Fatalf("start: %v, want a failure that is not a gone container", err)
}
}

// start never installs a real-slot binding through keepUnrecorded: a walk
// that reports ErrCredUnrecorded for one (no Strict pending semantics
// produce it today; the fake does) fails the start, and nothing is written
// for it (copilot-19 review LOW 3).
func TestStartNeverKeepsUnrecordedRealSlot(t *testing.T) {
c := ContainerIdentity{Runtime: "containerd", ID: "c71", CgroupID: 71, CgroupPath: "/workloads.slice/c71"}
b, policy, members, _ := newFixture(t, func(Map) error { return nil })
b.config.StrictSlot = func(uint32) bool { return true }
b.config.InitialBindings = nil
clear(b.desired)
b.desired[selector(c)] = Binding{Container: c, Slot: 1}
b.armExisting = func(Map, string) error { return nil }
b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) {
return false, fmt.Errorf("%w: 1 tasks (record full or over quota)", ErrCredUnrecorded)
}
err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil)
if !errors.Is(err, ErrCredUnrecorded) {
t.Fatalf("start: %v, want the unrecorded walk to fail it", err)
}
if v, ok := members.data[c.CgroupID]; ok {
t.Fatalf("a real-slot binding was installed: %+v", v)
}
if _, ok := b.active[c.CgroupID]; ok {
t.Fatal("a real-slot binding is active")
}
}

// A startup bind of a gone container whose entry is already deleted
// (ErrKeyNotExist: an in-place replacement raced the old instance's unbind
// of the same cgroup) is skipped like any gone container: the start does not
// fail, and nothing of it stays active (rev-c fu1 review MEDIUM).
func TestStartGoneContainerAlreadyDeletedIsSkipped(t *testing.T) {
b, policy, members, _ := newFixture(t, func(Map) error { return nil })
b.armExisting = func(Map, string) error {
// The old instance unbinds the same cgroup meanwhile: the entry
// this bind wrote is gone, and its delete finds no key.
delete(members.data, identity.CgroupID)
members.deleteErr = fmt.Errorf("delete: %w", ebpf.ErrKeyNotExist)
return ErrContainerGone
}
if err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil); err != nil {
t.Fatalf("start: %v, want the already deleted gone container skipped", err)
}
if len(b.active) != 0 || len(members.data) != 0 {
t.Fatalf("active %+v, entries %v", b.active, members.data)
}
}
18 changes: 18 additions & 0 deletions pkg/sandboxpolicy/igbackend/adoptedpending_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"

"github.com/kubescape/node-agent/pkg/ebpf/gadgets/common/enforcement"
"github.com/kubescape/node-agent/pkg/sandboxpolicy"
)

// TestAdoptedPending (Copilot #1176 4802130614, part B): the read-back of a
Expand All @@ -29,6 +30,23 @@ func TestAdoptedPending(t *testing.T) {
if _, err := b.AdoptedPending(0, time.Now().Add(time.Minute)); err == nil {
t.Fatal("an unresolved cgroup while a Strict mark remains answered")
}
// A cgroup this run holds (a pod record) is not an adopted mark this
// run does not hold, even while the instance still lists an adopted
// Strict pending entry on it (the holds exclusion).
held := uint64(podCgroup + 2)
heldMark := strictMark
heldMark.Container.CgroupID = held
i.entries[held], i.adopted[held] = heldMark, true
b.pods["held"] = &podBinding{pod: sandboxpolicy.PodBinding{PodUID: "held", CgroupID: held}}
if strict, err := b.AdoptedPending(held, time.Now().Add(time.Minute)); strict || err != nil {
t.Fatalf("a held cgroup with an adopted Strict pending entry: %v %v", strict, err)
}
delete(b.pods, "held")
if strict, err := b.AdoptedPending(held, time.Now().Add(time.Minute)); !strict || err != nil {
t.Fatalf("fixture: the same entry, not held: %v %v", strict, err)
}
delete(i.entries, held)
delete(i.adopted, held)
// Synchronize proves the pod: keepPending drops the mark.
b.SetStartGate(true)
b.SetNRISynced(1, map[uint64]bool{podCgroup: true})
Expand Down
85 changes: 85 additions & 0 deletions pkg/sandboxpolicy/igbackend/markpod_oldpod_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package igbackend

import (
"context"
"errors"
"fmt"
"strings"
"testing"

"github.com/kubescape/node-agent/pkg/sandboxpolicy"
)

// TestMarkPodOnARecordThatOwesAnUnbind (#1176 S2 follow-up): after a move
// whose unbind of the old cgroup failed (oldPod), MarkPod refuses both
// cgroups: the old one because the record now holds the new one, the new
// one because the owed unbind goes before any write and still fails. It
// never binds the new cgroup. Once the unbind succeeds, MarkPod retries it
// (oldPod cleared, the old entry gone) and still refuses a mark over the
// failed bind (errEntryNotCovering); EnsurePodBound then binds the target.
func TestMarkPodOnARecordThatOwesAnUnbind(t *testing.T) {
ctx := context.Background()
key, _ := Combination(strictPlan)
moved := testPodBinding("u", podCgroup+1, strictPlan)
for _, before := range []bool{true, false} {
t.Run(fmt.Sprintf("before the delete %v", before), func(t *testing.T) {
b, e := newGate(t)
i := e.last()
mustMark(t, b, strictPlan, seq(5, 5))
if err := b.EnsurePodBound(ctx, "u"); err != nil {
t.Fatal(err)
}
fail := func(err error) {
if before {
i.unbindBeforeErr = err
} else {
i.unbindErr = err
}
}
fail(errors.New("unbind"))
if err := b.BindPodsAt(ctx, []sandboxpolicy.PodBinding{moved}, seq(9, 9)); err == nil {
t.Fatal("the unbind fails")
}
if p := b.pods["u"]; p == nil || p.oldPod == nil || p.oldPod.CgroupID != podCgroup || p.pod.CgroupID != podCgroup+1 {
t.Fatalf("fixture: a record that owes the old cgroup's unbind: %+v", p)
}

// The old cgroup: the record holds the new one.
if err := b.MarkPod(ctx, gatePod(strictPlan), seq(10, 10)); err == nil || !strings.Contains(err.Error(), "its record holds cgroup") {
t.Fatalf("MarkPod of the old cgroup: %v", err)
}
// The new cgroup: the owed unbind runs first and fails.
if err := b.MarkPod(ctx, moved, seq(10, 10)); err == nil || !strings.Contains(err.Error(), "unbinding its previous cgroup") {
t.Fatalf("MarkPod of the new cgroup while the unbind fails: %v", err)
}
if i.binds[podCgroup+1] != 0 || b.pods["u"].oldPod == nil {
t.Fatalf("nothing binds the new cgroup while the old one's unbind fails: %+v", b.pods["u"])
}
if c := b.ConfirmPod("u", podCgroup+1, strictPlan); c.State == sandboxpolicy.PodSectionConfirmed {
t.Fatalf("ConfirmPod %+v", c)
}

// The unbind succeeds: MarkPod retries it, and still writes
// no mark over the failed bind.
fail(nil)
if err := b.MarkPod(ctx, moved, seq(10, 10)); !errors.Is(err, errEntryNotCovering) {
t.Fatalf("MarkPod after the unbind succeeds: %v", err)
}
if _, ok := i.entries[podCgroup]; ok || b.pods["u"].oldPod != nil {
t.Fatalf("MarkPod retried the owed unbind: entries %v, record %+v", i.entries, b.pods["u"])
}
if i.binds[podCgroup+1] != 0 {
t.Fatal("MarkPod bound the new cgroup")
}
if err := b.EnsurePodBound(ctx, "u"); err != nil {
t.Fatal(err)
}
if i.entries[podCgroup+1].Slot != b.slots[key] {
t.Fatalf("the target is bound: %+v", i.entries[podCgroup+1])
}
if c := b.ConfirmPod("u", podCgroup+1, strictPlan); c.State != sandboxpolicy.PodSectionConfirmed {
t.Fatalf("ConfirmPod %+v", c)
}
})
}
}
13 changes: 7 additions & 6 deletions pkg/sandboxpolicy/integration/nrigate.go
Original file line number Diff line number Diff line change
Expand Up @@ -349,10 +349,10 @@ var _ startgate.Gate = (*nriGate)(nil)
// EnableNRIStartGate turns the NRI start gate on. While the build constant
// is false (startgate.Buildable), it returns startgate.ErrNotBuildable and
// changes nothing: no gate, no goroutine, no socket. Otherwise it checks
// that node-agent shares the host PID namespace (HostPIDNamespace, by PID
// namespace inode), enables the pod gate (enableStartGate, which refuses
// once Start ran) and creates the plugin; Start runs it after the informers
// synced. Call it once, before Start, from the goroutine that calls Start
// that host.HostRoot/proc (a hostPath mount of the node's /proc) is a procfs
// of node-agent's own PID namespace (HostPIDNamespace: statfs, then NSpid),
// enables the pod gate (enableStartGate, which refuses once Start ran) and
// creates the plugin; Start runs it after the informers synced. Call it once, before Start, from the goroutine that calls Start
// (S3 review v3 R2).
func (s *Service) EnableNRIStartGate(ctx context.Context) error {
if !startgate.Buildable() {
Expand Down Expand Up @@ -750,8 +750,9 @@ func (n *nriGate) ClassificationSeq(ctx context.Context) sandboxpolicy.Seq {

// Registration is the node-level registration gate (design §6, v5): the
// pod gate is enabled (enableStartGate, with its cgroup-gone self-test),
// node-agent shares the host PID namespace, restart survival is on (a mark
// must outlive node-agent), and the informers synced once. The lifetime
// procRoot is a procfs of node-agent's own PID namespace
// (HostPIDNamespace), restart survival is on (a mark must outlive
// node-agent), and the informers synced once. The lifetime
// lock (L2) and the lift marker belong to S6, which adds them here; the
// build constant keeps the gate off until S9, after S6.
func (n *nriGate) Registration() error {
Expand Down
28 changes: 25 additions & 3 deletions pkg/sandboxpolicy/integration/nrigate_copilot8_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,15 @@ func c8Proc(t *testing.T, nspid string) string {
// the procfs's namespace down to this process's): exactly one level, equal
// to this process's PID. A procfs of an ancestor namespace where the
// numbers coincide lists two levels and is refused; an unprovable one
// (no NSpid) is refused.
// (no NSpid) is refused. The fake trees are not a procfs, so they go
// through samePIDNamespace, the file proof HostPIDNamespace runs once its
// statfs passed (TestHostPIDNamespaceNeedsAProcfs).
func TestCopilot8PIDNamespaceOfTheProcfs(t *testing.T) {
pid := strconv.Itoa(os.Getpid())
if err := HostPIDNamespace("/proc"); err != nil {
t.Fatalf("this process's own procfs: %v", err)
}
if err := HostPIDNamespace(c8Proc(t, pid)); err != nil {
if err := samePIDNamespace(c8Proc(t, pid)); err != nil {
t.Fatalf("one level, this PID: %v", err)
}
for name, nspid := range map[string]string{
Expand All @@ -95,8 +97,28 @@ func TestCopilot8PIDNamespaceOfTheProcfs(t *testing.T) {
"no NSpid line": "",
"another PID at one level": "1",
} {
if err := HostPIDNamespace(c8Proc(t, nspid)); err == nil || !strings.Contains(err.Error(), "not node-agent's PID namespace") && !strings.Contains(err.Error(), "NSpid") {
if err := samePIDNamespace(c8Proc(t, nspid)); err == nil || !strings.Contains(err.Error(), "not node-agent's PID namespace") && !strings.Contains(err.Error(), "NSpid") {
t.Errorf("%s: %v, want refused", name, err)
}
}
}

// TestHostPIDNamespaceNeedsAProcfs (rev-a, Copilot #1176 round 8 LOW 1): a
// directory that is not a procfs is refused even when its files pass the
// NSpid proof (a crafted self link and self/status): HostPIDNamespace
// requires PROC_SUPER_MAGIC on procRoot first.
func TestHostPIDNamespaceNeedsAProcfs(t *testing.T) {
crafted := c8Proc(t, strconv.Itoa(os.Getpid()))
if err := samePIDNamespace(crafted); err != nil {
t.Fatalf("fixture: the crafted files pass the file proof: %v", err)
}
if err := HostPIDNamespace(crafted); err == nil || !strings.Contains(err.Error(), "is not a procfs") {
t.Fatalf("a crafted non-procfs directory: %v, want refused as not a procfs", err)
}
if err := HostPIDNamespace(filepath.Join(t.TempDir(), "missing")); err == nil || !strings.Contains(err.Error(), "statfs") {
t.Fatalf("a missing procRoot: %v, want the statfs error", err)
}
if err := HostPIDNamespace("/proc"); err != nil {
t.Fatalf("this process's procfs: %v", err)
}
}
Loading