Skip to content
Draft
10 changes: 10 additions & 0 deletions docs/features/sandbox-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,16 @@ mount), with a manifest of the published slots (policies, revision digest,
generation). Without a host bpffs, restart survival is off and a warning is
logged.

**One node-agent per node at a time.** Restart survival assumes that the
previous node-agent on the node has exited before the new one starts: the
DaemonSet must update with `maxSurge: 0` (the default). The start gate relies
on this too. When it cannot read the previous run's pinned sets, it refuses
the containers of pods that are Unselected, not start-gated or exempt. With
the NRI start gate on, it narrows that refusal to pods older than node-agent's
own container: a pod cgroup created after that container cannot carry a mark
of the previous run. With overlapping node-agents, the old one could still
mark newer pods, so do not set `maxSurge` above 0.

- **Restore.** At start each owner validates the pinned sets (manifest, section,
boot, links and maps of the set) and restores the state maps of a valid set
before its first instance starts. A set is removed at start only for a proven
Expand Down
15 changes: 13 additions & 2 deletions pkg/sandboxpolicy/classify.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,21 @@ type ClassifyRequest struct {
}

const (
configSourceAnnotation = "kubernetes.io/config.source"
// ConfigSourceAnnotation is the kubelet's pod source annotation
// (StaticPod).
ConfigSourceAnnotation = "kubernetes.io/config.source"
configMirrorAnnotation = "kubernetes.io/config.mirror"
)

// StaticPod is the start gate's static-pod rule, on the runtime's pod
// annotations: kubernetes.io/config.source is set and is not "api". A static
// pod is looked up through its mirror pod, whose kubernetes.io/config.mirror
// names its kubelet UID (ClassifyPod); a missing or "api" source never is.
func StaticPod(annotations map[string]string) bool {
src := annotations[ConfigSourceAnnotation]
return src != "" && src != "api"
}

// ClassifyPod classifies a pod for the start gate. It reads only the
// classification snapshot and the PodSource, never c.mu, so it does not wait
// on a reconcile or the API server (except through src.Fetch, bounded by
Expand Down Expand Up @@ -281,7 +292,7 @@ func (c *Controller) ClassifyPod(ctx context.Context, req ClassifyRequest, src P
if err != nil {
return unknown(Seq{Config: configSeq, Input: src.InputEpoch()}, "%v", err)
}
static := req.Pod.Annotations[configSourceAnnotation] != "" && req.Pod.Annotations[configSourceAnnotation] != "api"
static := StaticPod(req.Pod.Annotations)
matches := func(f PodFacts) bool {
if static {
return f.Annotations[configMirrorAnnotation] == string(req.Pod.UID) && req.Pod.UID != ""
Expand Down
6 changes: 3 additions & 3 deletions pkg/sandboxpolicy/classify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func (f *fakePods) source() PodSource {
// regular container "app" and the label app=test.
func testPod(namespace, name string) (NRIPod, PodFacts) {
uid := types.UID(namespace + "-" + name + "-uid")
return NRIPod{UID: uid, Namespace: namespace, Name: name, Annotations: map[string]string{configSourceAnnotation: "api"}},
return NRIPod{UID: uid, Namespace: namespace, Name: name, Annotations: map[string]string{ConfigSourceAnnotation: "api"}},
PodFacts{UID: uid, Labels: map[string]string{"app": "test"}, Containers: []PodContainer{{Name: "app", Kind: "regular"}}, NamespaceLabels: map[string]string{"team": "red"}}
}

Expand Down Expand Up @@ -248,7 +248,7 @@ func TestClassifyStaticPods(t *testing.T) {
c := syncedController(t, privPolicy("priv", "kube-system"))
pod, facts := testPod("kube-system", "etcd-node")
pod.UID = "static-hash"
pod.Annotations = map[string]string{configSourceAnnotation: "file"}
pod.Annotations = map[string]string{ConfigSourceAnnotation: "file"}
mirror := facts
mirror.UID = "mirror-uid"
for _, tc := range []struct {
Expand All @@ -274,7 +274,7 @@ func TestClassifyStaticPods(t *testing.T) {
}
// A pod whose UID equals the mirror's would match only as an API pod.
apiPod := pod
apiPod.Annotations = map[string]string{configSourceAnnotation: "api"}
apiPod.Annotations = map[string]string{ConfigSourceAnnotation: "api"}
m := mirror
m.Annotations = map[string]string{configMirrorAnnotation: "static-hash"}
if got := classifyOne(t, c, apiPod, m); got.Class != PodUnknown {
Expand Down
130 changes: 130 additions & 0 deletions pkg/sandboxpolicy/igbackend/fu2_gate_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package igbackend

import (
"errors"
"testing"
"time"

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

// TestFU2SurvivalOffIsPinnedSetsKept (batch 17 follow-up, the cgroup-ID
// watermark): restart survival that could not read the previous runs' sets
// answers AdoptedPending with an error that wraps
// sandboxpolicy.ErrPinnedSetsKept, the one SectionBackend narrows by its
// watermark. Any other error does not wrap it.
func TestFU2SurvivalOffIsPinnedSetsKept(t *testing.T) {
b, _ := newGate(t)
off := errors.New("privilege restart survival off for this run, pinned sets kept: EIO")
b.pins, b.survivalOff = nil, off
_, err := b.AdoptedPending(podCgroup, time.Now().Add(time.Minute))
if !errors.Is(err, sandboxpolicy.ErrPinnedSetsKept) || !errors.Is(err, off) {
t.Fatalf("survival off: %v, want ErrPinnedSetsKept and the cause", err)
}
b2, _ := newGate(t)
b2.instance = nil
b2.pins.settled = false
if _, err := b2.AdoptedPending(podCgroup, time.Now().Add(time.Minute)); err == nil || errors.Is(err, sandboxpolicy.ErrPinnedSetsKept) {
t.Fatalf("no instance: %v, want an error that is not ErrPinnedSetsKept", err)
}
}

// TestFU2ProveNRICgroup (rev-a MEDIUM on #1176 4802130614): a cgroup
// Synchronize held back only for sandboxes removed since is proven for that
// Synchronize by this run's classification at or after its sequence, for
// that same completion, with the gate on (owner batch 12). Once proven, the
// previous run's Strict pending mark on it is covered.
func TestFU2ProveNRICgroup(t *testing.T) {
const other = podCgroup + 1
for _, tt := range []struct {
name string
setup func(b *PrivilegeBackend)
epoch uint64
seq sandboxpolicy.Seq
want bool
}{
{name: "at Synchronize's sequence", epoch: 1, seq: seq(3, 3), want: true,
setup: func(b *PrivilegeBackend) { b.SetStartGate(true); b.SetNRISynced(1, nil); b.SetNRISyncSeq(1, seq(3, 3)) }},
{name: "after it", epoch: 1, seq: seq(3, 4), want: true,
setup: func(b *PrivilegeBackend) { b.SetStartGate(true); b.SetNRISynced(1, nil); b.SetNRISyncSeq(1, seq(3, 3)) }},
{name: "before it", epoch: 1, seq: seq(3, 2),
setup: func(b *PrivilegeBackend) { b.SetStartGate(true); b.SetNRISynced(1, nil); b.SetNRISyncSeq(1, seq(3, 3)) }},
{name: "incomparable", epoch: 1, seq: seq(4, 2),
setup: func(b *PrivilegeBackend) { b.SetStartGate(true); b.SetNRISynced(1, nil); b.SetNRISyncSeq(1, seq(3, 3)) }},
{name: "no sequence for the completion", epoch: 1, seq: seq(3, 3),
setup: func(b *PrivilegeBackend) { b.SetStartGate(true); b.SetNRISynced(1, nil) }},
{name: "another completion", epoch: 1, seq: seq(3, 3),
setup: func(b *PrivilegeBackend) {
b.SetStartGate(true)
b.SetNRISynced(2, nil)
b.SetNRISyncSeq(2, seq(3, 3))
}},
{name: "disconnected", epoch: 1, seq: seq(3, 3),
setup: func(b *PrivilegeBackend) {
b.SetStartGate(true)
b.SetNRISynced(1, nil)
b.SetNRISyncSeq(1, seq(3, 3))
b.SetNRIDisconnected(1)
}},
{name: "gate off", epoch: 1, seq: seq(3, 3),
setup: func(b *PrivilegeBackend) { b.SetNRISynced(1, nil); b.SetNRISyncSeq(1, seq(3, 3)) }},
{name: "not synced", epoch: 1, seq: seq(3, 3),
setup: func(b *PrivilegeBackend) { b.SetStartGate(true) }},
} {
t.Run(tt.name, func(t *testing.T) {
b, _ := newGate(t)
tt.setup(b)
if got := b.ProveNRICgroup(tt.epoch, podCgroup, tt.seq, time.Now().Add(time.Minute)); got != tt.want {
t.Fatalf("ProveNRICgroup = %v, want %v", got, tt.want)
}
b.mu.Lock()
covered, otherCovered := b.pendingCovered(podCgroup, true, true), b.pendingCovered(other, true, true)
b.mu.Unlock()
if covered != tt.want || otherCovered {
t.Fatalf("pending mark covered %v (other cgroup %v), want %v (false)", covered, otherCovered, tt.want)
}
})
}
b, _ := newGate(t)
b.SetStartGate(true)
b.SetNRISynced(1, nil)
b.SetNRISyncSeq(1, seq(3, 3))
if b.ProveNRICgroup(1, 0, seq(3, 3), time.Now().Add(time.Minute)) {
t.Fatal("cgroup 0 was proven")
}
}

// TestFU2ProveNRICgroupBusy (PR #1231 Copilot 4812087571): with the owner
// mutex held (a hold worker compiling or publishing a slot), the prove
// returns false by its deadline and records nothing; once the mutex is
// free, the same prove is recorded.
func TestFU2ProveNRICgroupBusy(t *testing.T) {
b, _ := newGate(t)
b.SetStartGate(true)
b.SetNRISynced(1, nil)
b.SetNRISyncSeq(1, seq(3, 3))
b.mu.Lock()
done := make(chan bool, 1)
start := time.Now()
go func() { done <- b.ProveNRICgroup(1, podCgroup, seq(3, 3), time.Now().Add(50*time.Millisecond)) }()
select {
case got := <-done:
if got {
t.Fatal("a prove with the owner busy was recorded")
}
case <-time.After(10 * time.Second):
b.mu.Unlock()
t.Fatal("the prove waited for the owner past its deadline")
}
if waited := time.Since(start); waited < 50*time.Millisecond {
t.Fatalf("the prove gave up after %v, before its deadline", waited)
}
proven := b.nriProven[podCgroup] // mu is held here
b.mu.Unlock()
if proven {
t.Fatal("a busy prove recorded the cgroup")
}
if !b.ProveNRICgroup(1, podCgroup, seq(3, 3), time.Now()) {
t.Fatal("with the owner free, a passed deadline still gets one try")
}
}
39 changes: 34 additions & 5 deletions pkg/sandboxpolicy/igbackend/nodeowner.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,10 @@ type podBinding struct {
// Status reports it faulted, never confirmed (CodeRabbit #1165
// 4806793247), until a call applies the input.
refusedPlan bool
// refusedSeq is the sequence of the listing that set refusedPlan (nil:
// a BindPods without one). A MarkPod at a strictly newer sequence that
// leaves the record holding its plan clears both (clearRefusedPlan).
refusedSeq *sandboxpolicy.Seq
// confirmed: the binding judges every task of the pod's containers. With
// arming, only when it was bound in the current instance before any
// container of the pod started (a pod binding arms no running task).
Expand Down Expand Up @@ -382,6 +386,28 @@ func (p *podBinding) admits(seq *sandboxpolicy.Seq, loosen, raise, sameSet bool)

// advance keeps the newest sequence that wrote the record: it never lowers
// lastSeq (a sequence-neutral bind at an older sequence keeps it).
// refusePlan records that a listing at seq (nil: BindPods) asked for a plan
// the record does not hold (refusedPlan).
func (p *podBinding) refusePlan(seq *sandboxpolicy.Seq) {
p.refusedPlan, p.refusedSeq = true, nil
if seq != nil {
at := *seq
p.refusedSeq = &at
}
}

// clearRefusedPlan clears refusedPlan after a MarkPod at seq left the record
// holding the mark's plan: that classification is newer than the refused
// listing, so the record holds the plan the input asks for now. Only a
// strictly newer seq clears it: an equal or incomparable one may be the
// refused listing's own input (another set at an equal sequence, owner batch
// 16), and a listing without a sequence is only cleared by the next listing.
func (p *podBinding) clearRefusedPlan(seq sandboxpolicy.Seq) {
if p.refusedPlan && p.refusedSeq != nil && seq.Compare(*p.refusedSeq) == sandboxpolicy.SeqNewer {
p.refusedPlan, p.refusedSeq = false, nil
}
}

func (p *podBinding) advance(seq *sandboxpolicy.Seq) {
if p.sequenced && seq != nil && seq.Compare(p.lastSeq) == sandboxpolicy.SeqNewer {
p.lastSeq = *seq
Expand Down Expand Up @@ -1510,7 +1536,7 @@ func (b *nodeOwner[C]) bindPods(ctx context.Context, pods []sandboxpolicy.PodBin
refused := 0
stale := func(p sandboxpolicy.PodBinding) {
if current := b.pods[p.PodUID]; current != nil {
current.refusedPlan = true
current.refusePlan(seq)
}
if seq == nil {
refused++
Expand All @@ -1522,7 +1548,7 @@ func (b *nodeOwner[C]) bindPods(ctx context.Context, pods []sandboxpolicy.PodBin
// Each listed pod's refusal is decided again by this call (stale).
for uid := range wanted {
if current := b.pods[uid]; current != nil {
current.refusedPlan = false
current.refusedPlan, current.refusedSeq = false, nil
}
}
// The gone proof is I/O under mu: checked for missing pods once every
Expand Down Expand Up @@ -1775,7 +1801,7 @@ func (b *nodeOwner[C]) bindPods(ctx context.Context, pods []sandboxpolicy.PodBin
// #1162 round 8): refused, the mark stays. Decided just
// before the unbind and bind (rev-b LOW-1): a pod that gets
// no pod bind (its containers started) reports nothing.
errs = append(errs, fmt.Errorf("%s pod %s/%s: an inherited Strict pending mark stays until a proof retires it: %w", b.section.name, p.Namespace, p.PodName, sandboxpolicy.ErrPolicyEntry))
errs = append(errs, fmt.Errorf("%s pod %s/%s: %w", b.section.name, p.Namespace, p.PodName, sandboxpolicy.ErrInheritedStrictMark))
continue
}
unbound := current != nil && current.bindPending
Expand Down Expand Up @@ -1847,7 +1873,7 @@ func (b *nodeOwner[C]) bindPods(ctx context.Context, pods []sandboxpolicy.PodBin
continue // a removal: decided by stale above
}
if current.combination != combination || b.class(current) != b.gateStrict(p.Plan, policies) || current.pod.CgroupID != p.CgroupID {
current.refusedPlan = true
current.refusePlan(seq)
}
}
return errors.Join(append(errs, b.sweep(), b.retire(ctx))...)
Expand Down Expand Up @@ -2050,7 +2076,7 @@ func (b *nodeOwner[C]) MarkPod(_ context.Context, pod sandboxpolicy.PodBinding,
// the cgroup is gone, Synchronize proved the pod Unselected or
// absent, or a committed entry covers it). It keeps denying, and
// its entry stays as it is (Copilot #1162 round 8).
return fmt.Errorf("%s pod %s/%s: an inherited Strict pending mark stays until a proof retires it: %w", b.section.name, pod.Namespace, pod.PodName, sandboxpolicy.ErrPolicyEntry)
return fmt.Errorf("%s pod %s/%s: %w", b.section.name, pod.Namespace, pod.PodName, sandboxpolicy.ErrInheritedStrictMark)
}
// No entry, or a previous run's mark (adopted) that the plan's
// class does not lower, or that a proof retires: this run's mark
Expand Down Expand Up @@ -2090,6 +2116,7 @@ func (b *nodeOwner[C]) MarkPod(_ context.Context, pod sandboxpolicy.PodBinding,
current.pod.Plan, current.strict = pod.Plan, strict
}
current.advance(&seq)
current.clearRefusedPlan(seq)
return nil
}
if current.combination == combination && current.strict == strict {
Expand All @@ -2101,6 +2128,7 @@ func (b *nodeOwner[C]) MarkPod(_ context.Context, pod sandboxpolicy.PodBinding,
}
}
current.advance(&seq)
current.clearRefusedPlan(seq)
return nil
}
if !seq.Admits(current.lastSeq, current.strict && !strict, sameSetOrRaise(current.combination == combination, current.strict, strict)) {
Expand All @@ -2110,6 +2138,7 @@ func (b *nodeOwner[C]) MarkPod(_ context.Context, pod sandboxpolicy.PodBinding,
return err
}
current.advance(&seq)
current.clearRefusedPlan(seq)
return nil
}

Expand Down
9 changes: 7 additions & 2 deletions pkg/sandboxpolicy/igbackend/nodeowner_podgate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,11 @@ func TestMarkPodNeverOverwritesARealSlotEntry(t *testing.T) {
if err == nil || errors.Is(err, sandboxpolicy.ErrPolicyEntry) != tt.wantPolicyEntry {
t.Fatalf("MarkPod: %v, want ErrPolicyEntry %v", err, tt.wantPolicyEntry)
}
// A policy-slot entry is definitive: never the inherited
// mark's sentinel (CodeRabbit #1176 4810415619).
if errors.Is(err, sandboxpolicy.ErrInheritedStrictMark) {
t.Fatalf("MarkPod: %v, an adopted policy-slot entry is not an inherited Strict mark", err)
}
if i.entries[podCgroup] != previous || !i.adopted[podCgroup] || b.pods["u"] != nil {
t.Fatalf("never written over: entry %+v", i.entries[podCgroup])
}
Expand Down Expand Up @@ -488,7 +493,7 @@ func TestMarkPodNeverOverwritesARealSlotEntry(t *testing.T) {
}
err := b.MarkPod(ctx, gatePod(tt.plan), seq(1, 1))
if !tt.takesOver {
if !errors.Is(err, sandboxpolicy.ErrPolicyEntry) || i.entries[podCgroup] != adopted || !i.adopted[podCgroup] || b.pods["u"] != nil {
if !errors.Is(err, sandboxpolicy.ErrInheritedStrictMark) || !errors.Is(err, sandboxpolicy.ErrPolicyEntry) || i.entries[podCgroup] != adopted || !i.adopted[podCgroup] || b.pods["u"] != nil {
t.Fatalf("the Strict mark stays: %v, entry %+v adopted %v", err, i.entries[podCgroup], i.adopted[podCgroup])
}
return
Expand Down Expand Up @@ -1901,7 +1906,7 @@ func TestAuditBindNeverLowersAnAdoptedStrictMark(t *testing.T) {
}
return b.BindPodsAt(ctx, []sandboxpolicy.PodBinding{gatePod(privAuditPlan)}, seq(1, 1))
}
if err := bind(); !errors.Is(err, sandboxpolicy.ErrPolicyEntry) || i.entries[podCgroup] != adopted || b.pods["u"] != nil {
if err := bind(); !errors.Is(err, sandboxpolicy.ErrInheritedStrictMark) || i.entries[podCgroup] != adopted || b.pods["u"] != nil {
t.Fatalf("the Strict mark stays: %v, entry %+v", err, i.entries[podCgroup])
}
b.SetCgroupGone(func(c uint64) bool { return c == podCgroup })
Expand Down
35 changes: 34 additions & 1 deletion pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package igbackend

import "github.com/kubescape/node-agent/pkg/sandboxpolicy"
import (
"time"

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

// SetNRISyncSeq records the classification sequence at which the NRI
// plugin's Synchronize on connection epoch completed (sandboxpolicy
Expand Down Expand Up @@ -38,3 +42,32 @@ func (b *nodeOwner[C]) auditRetires(seq *sandboxpolicy.Seq) bool {
o := seq.Compare(*b.nriSyncSeq)
return o == sandboxpolicy.SeqNewer || o == sandboxpolicy.SeqEqual
}

// ProveNRICgroup adds cgroup to the proof of the Synchronize on epoch
// (nriProven), as if that Synchronize had proved it (sandboxpolicy
// NRICgroupProver; rev-a MEDIUM on #1176 4802130614): Synchronize held the
// cgroup back only for sandboxes that are gone since, and seq is this
// run's classification of its pod that needs no Strict pending mark. It
// counts only at or after Synchronize's sequence (auditRetires, owner
// batch 12), for that same completion. false: not recorded. It waits for
// mu until deadline at most (lockBy; a passed deadline: one try): a hold
// worker may hold mu while it compiles or publishes a slot, and the
// refresh's re-proof pass must not stall behind it (PR #1231 Copilot
// 4812087571). Busy is false too: the caller keeps the cgroup queued.
func (b *nodeOwner[C]) ProveNRICgroup(epoch, cgroup uint64, seq sandboxpolicy.Seq, deadline time.Time) bool {
if !b.lockBy(deadline) {
return false
}
defer b.mu.Unlock()
if cgroup == 0 || b.nriProven == nil || epoch != b.nriEpoch || !b.auditRetires(&seq) {
return false
}
b.nriProven[cgroup] = true
return true
}

var (
_ sandboxpolicy.NRICgroupProver = (*PrivilegeBackend)(nil)
_ sandboxpolicy.NRICgroupProver = (*NetworkBackend)(nil)
_ sandboxpolicy.NRICgroupProver = (*FileBackend)(nil)
)
Loading