From 73d5cae61ba33fb262c17f35b5331a705b28fc0c Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Sat, 5 Dec 2026 16:03:29 +0100 Subject: [PATCH 1/5] fix(nri): close the gate and plugin follow-ups from the NRI gate stack Follow-ups from the reviews of #1176 and #1178, all fail-closed. - Cgroup-ID watermark: when restart survival cannot read the previous run's pins (or an unavailable section kept them), AdoptedPending answers "clear" only for cgroups created after node-agent's own cgroup; older cgroups, cgroup 0 and an unreadable or root watermark still refuse. Assumes one node-agent per node (DaemonSet maxSurge 0), documented in docs/features/sandbox-policy.md. - A cgroup held back at Synchronize by an unproven sibling sandbox is re-proven once that sandbox is gone, from a classification at or after Synchronize's sequence (batch 12). - ErrInheritedStrictMark (wraps ErrPolicyEntry) is retried, never memoized as settled. - A per-pod commit counter refuses a create whose last read-back was overtaken by a newer plan commit (the admission stale window). - Batch 18: a Selected pod with no pod-markable section is unmarked through the shared backoff unless it is Strict with a shape; one helper serves both the refresh and the reclassify path. - An alternating Unknown no longer resets the write backoff. - Stale comments; tests including an end-to-end run through the real section backend and node owner. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- docs/features/sandbox-policy.md | 10 + pkg/sandboxpolicy/igbackend/fu2_gate_test.go | 95 +++ pkg/sandboxpolicy/igbackend/nodeowner.go | 4 +- .../igbackend/nodeowner_podgate_test.go | 9 +- .../igbackend/nodeowner_syncproof.go | 23 + pkg/sandboxpolicy/igbackend/restart.go | 8 +- .../integration/fu2_gate_test.go | 796 ++++++++++++++++++ pkg/sandboxpolicy/integration/nrigate.go | 234 ++++- pkg/sandboxpolicy/integration/podgate.go | 76 +- pkg/sandboxpolicy/integration/service.go | 10 +- pkg/sandboxpolicy/sections.go | 69 +- .../startgate/fu2_reprove_test.go | 89 ++ pkg/sandboxpolicy/startgate/plugin.go | 77 +- pkg/sandboxpolicy/startgate/plugin_test.go | 5 + pkg/sandboxpolicy/types.go | 8 + 15 files changed, 1451 insertions(+), 62 deletions(-) create mode 100644 pkg/sandboxpolicy/igbackend/fu2_gate_test.go create mode 100644 pkg/sandboxpolicy/integration/fu2_gate_test.go create mode 100644 pkg/sandboxpolicy/startgate/fu2_reprove_test.go diff --git a/docs/features/sandbox-policy.md b/docs/features/sandbox-policy.md index 6333787e4b..0ed829665a 100644 --- a/docs/features/sandbox-policy.md +++ b/docs/features/sandbox-policy.md @@ -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 diff --git a/pkg/sandboxpolicy/igbackend/fu2_gate_test.go b/pkg/sandboxpolicy/igbackend/fu2_gate_test.go new file mode 100644 index 0000000000..61fe4e3aae --- /dev/null +++ b/pkg/sandboxpolicy/igbackend/fu2_gate_test.go @@ -0,0 +1,95 @@ +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); 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)) { + t.Fatal("cgroup 0 was proven") + } +} diff --git a/pkg/sandboxpolicy/igbackend/nodeowner.go b/pkg/sandboxpolicy/igbackend/nodeowner.go index 1b50ba9826..eb684e03ef 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner.go @@ -1654,7 +1654,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 @@ -1884,7 +1884,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 diff --git a/pkg/sandboxpolicy/igbackend/nodeowner_podgate_test.go b/pkg/sandboxpolicy/igbackend/nodeowner_podgate_test.go index 9cf22bee3a..bb1b28d8d1 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner_podgate_test.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner_podgate_test.go @@ -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]) } @@ -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 @@ -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 }) diff --git a/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go b/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go index e6dd0ed208..94f0784ddd 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go @@ -38,3 +38,26 @@ 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. +func (b *nodeOwner[C]) ProveNRICgroup(epoch, cgroup uint64, seq sandboxpolicy.Seq) bool { + b.mu.Lock() + 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) +) diff --git a/pkg/sandboxpolicy/igbackend/restart.go b/pkg/sandboxpolicy/igbackend/restart.go index 3a3b44bfb6..ed1c370c1f 100644 --- a/pkg/sandboxpolicy/igbackend/restart.go +++ b/pkg/sandboxpolicy/igbackend/restart.go @@ -1064,7 +1064,8 @@ func (b *nodeOwner[C]) holds(cgroup uint64) bool { // list its adopted entries, or none while restart state remains, cannot // tell: an error (fail-closed), and so is restart survival that could not // read the previous runs' sets (survivalOff: they are kept and may hold -// one; Copilot #1176 4810415561). The old sets that judge with their own +// one; Copilot #1176 4810415561), which wraps +// sandboxpolicy.ErrPinnedSetsKept. The old sets that judge with their own // state (a fresh start: another image or layout, a failed restore, an // unvalidated set) are read too: one of their Strict pending marks denies // whatever this run holds, until Settle prunes it; an unvalidated or @@ -1084,7 +1085,10 @@ func (b *nodeOwner[C]) AdoptedPending(cgroupID uint64, deadline time.Time) (bool defer b.mu.Unlock() if b.pins == nil { if b.survivalOff != nil { - return false, b.survivalOff + // The sets were kept unread: sandboxpolicy.ErrPinnedSetsKept, + // which SectionBackend clears only for a cgroup above its + // watermark. + return false, fmt.Errorf("%w: %w", b.survivalOff, sandboxpolicy.ErrPinnedSetsKept) } return false, nil } diff --git a/pkg/sandboxpolicy/integration/fu2_gate_test.go b/pkg/sandboxpolicy/integration/fu2_gate_test.go new file mode 100644 index 0000000000..0997d6fde3 --- /dev/null +++ b/pkg/sandboxpolicy/integration/fu2_gate_test.go @@ -0,0 +1,796 @@ +package integration + +// Regression tests for the fu2 follow-ups on the gate and the plugin: the +// inherited Strict mark sentinel (CodeRabbit #1176 4810415619), the +// sectionless Selected unmark (owner batch 18), the hold's commit check +// (CodeRabbit #1176 4810415638), the cgroup-ID watermark and the re-proof +// of a cgroup (rev-a MEDIUMs on #1176), end to end through the real node +// owner where it can run unprivileged, and the S5b review v2 C1 and C2 +// probes. + +import ( + "context" + "errors" + "fmt" + "os" + "path/filepath" + "sync" + "sync/atomic" + "testing" + "time" + + privruntime "github.com/kubescape/node-agent/pkg/ebpf/gadgets/enforce_privilege/runtime" + "github.com/kubescape/node-agent/pkg/sandboxpolicy" + "github.com/kubescape/node-agent/pkg/sandboxpolicy/igbackend" + "github.com/kubescape/node-agent/pkg/sandboxpolicy/startgate" + api "github.com/kubescape/storage/pkg/apis/sandbox/v1alpha1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + kubefake "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" +) + +var fu2Req = sandboxpolicy.ClassifyRequest{Pod: sandboxpolicy.NRIPod{UID: "pod-uid", Namespace: "ns", Name: "pod"}} + +// TestFU2InheritedStrictMarkIsRetried (CodeRabbit #1176 4810415619): an +// Audit mark refused by a previous run's Strict pending mark +// (ErrInheritedStrictMark, an ErrPolicyEntry) is not a definitive outcome: +// the payload keeps no memo and the refresh's reclassification retries the +// mark at the same sequence. An adopted policy-slot entry (a plain +// ErrPolicyEntry) still is. +func TestFU2InheritedStrictMarkIsRetried(t *testing.T) { + for _, tc := range []struct { + name string + err error + retry bool + }{ + {name: "inherited Strict mark", err: fmt.Errorf("privilege pod ns/pod: %w", sandboxpolicy.ErrInheritedStrictMark), retry: true}, + {name: "policy-slot entry", err: fmt.Errorf("privilege pod ns/pod: %w", sandboxpolicy.ErrPolicyEntry)}, + } { + t.Run(tc.name, func(t *testing.T) { + s, backend := nriTestService(t) + useAuditPolicy(t, s, backend.fakeGateBackend) + n := readyNRIGate(t, s, backend) + c := n.Classify(t.Context(), fu2Req) + sb, err := n.Sandbox(nriTestPod("sb1", 42)) + if err != nil { + t.Fatal(err) + } + backend.mu.Lock() + backend.markErr = tc.err + backend.mu.Unlock() + if _, err := n.JoinAndMark(t.Context(), sb, c, soon()); err != nil { + t.Fatal(err) + } + wantMemo := c.Seq + if tc.retry { + wantMemo = sandboxpolicy.Seq{} + } + if p := v4Payload(n); p.seq != wantMemo { + t.Fatalf("memo %+v, want %+v", p.seq, wantMemo) + } + n.reclassifyUnbound(t.Context(), nil, c.Seq) + want := 1 + if tc.retry { + want = 2 + } + if got := backend.count("MarkPod"); got != want { + t.Fatalf("MarkPod calls %d, want %d: %v", got, want, backend.calls) + } + }) + } +} + +// fu2SourcesPolicy is an enforce policy with ContainerProfile sources: the +// pod is Selected and Strict, with no section a pod mark holds (sources). +func fu2SourcesPolicy() *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{"apiVersion": api.SchemeGroupVersion.String(), "kind": "SandboxPolicy", "metadata": map[string]any{"name": "sourced", "namespace": "ns", "uid": "sourced-uid", "generation": int64(1)}, + "spec": map[string]any{"selector": map[string]any{"podSelector": map[string]any{}}, "mode": "enforce", "containers": []any{"*"}, + "sources": []any{map[string]any{"containerProfile": map[string]any{"name": "profile"}, "include": []any{"execs"}}}, + "privilege": map[string]any{"default": "allow", "rules": []any{map[string]any{"name": "no-chroot", "action": "deny", "target": map[string]any{"syscall": []any{"chroot"}}}}}}}} +} + +// fu2Mode returns p with its mode set. +func fu2Mode(p *unstructured.Unstructured, mode string) *unstructured.Unstructured { + _ = unstructured.SetNestedField(p.Object, mode, "spec", "mode") + return p +} + +// fu2ExecOnlyPolicy is an exec-only policy: Selected, no section a pod mark +// holds, no shape; Strict in enforce mode. +func fu2ExecOnlyPolicy(mode string) *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{"apiVersion": api.SchemeGroupVersion.String(), "kind": "SandboxPolicy", "metadata": map[string]any{"name": "exec", "namespace": "ns", "uid": "exec-uid", "generation": int64(1)}, + "spec": map[string]any{"selector": map[string]any{"podSelector": map[string]any{}}, "mode": mode, "containers": []any{"*"}, "exec": map[string]any{"default": "deny"}}}} +} + +// TestFU2AuditSourcesSharesUnmarkBackoff (owner batch 18; Copilot #1178 +// 4802098741): a pod whose policy turns into an Audit one with sources +// (Selected, not Strict, no section, a shape) loses its older mark through +// the reclassification and unmarkDeselected alike, and both share one +// backoff for that outcome: with a failing unmark, two refreshes try it, +// then nothing until the retry is due. (The Strict exec-only case is +// TestCopilot10ExecOnlyReplacementSharesUnmarkBackoff.) +func TestFU2AuditSourcesSharesUnmarkBackoff(t *testing.T) { + s, inner := nriTestService(t) + backend := &c3UnmarkFailBackend{nriTestBackend: inner} + s.backend = backend + s.inputEpoch.Store(1) + n := readyNRIGate(t, s, inner) + s.nriGate = n + clock := v4Clock(n) + refresh := func() { + s.bindPods(t.Context()) + s.gate.Load().wait() + } + refresh() + sb, err := n.Sandbox(nriTestPod("sb1", 42)) + if err != nil { + t.Fatal(err) + } + if _, err := n.JoinAndMark(t.Context(), sb, n.Classify(t.Context(), fu2Req), soon()); err != nil { + t.Fatal(err) + } + c3UsePolicies(t, s, inner.fakeGateBackend, fu2Mode(fu2SourcesPolicy(), "audit")) + s.inputEpoch.Add(1) + if c := n.Classify(t.Context(), fu2Req); c.Class != sandboxpolicy.PodSelected || c.Strict || len(c.Sections) != 0 || c.Shape&sandboxpolicy.ShapeSources == 0 { + t.Fatalf("setup: Audit sources classification %+v", c) + } + backend.fail.Store(true) + refresh() + refresh() + if p := v4Payload(n); p.fails != 2 || !p.retryAt.After(*clock) { + t.Fatalf("no shared backoff after 2 failed unmarks: payload %+v", p) + } + before := backend.unmarks.Load() + for range 5 { + refresh() + } + if got := backend.unmarks.Load() - before; got != 0 { + t.Fatalf("5 refreshes mid-backoff at one sequence: %d UnmarkPod, want 0", got) + } + backend.fail.Store(false) + *clock = clock.Add(time.Minute) + refresh() + if n.HoldsMark("pod-uid") || inner.rec("pod-uid") != nil { + t.Fatalf("after the backoff, the unmark did not go through: %v", inner.callNames()) + } +} + +// TestFU2UnmarkPathsAgree (owner batch 18 read fail-closed, rev-b HIGH-1 +// and LOW-3): the refresh's unmarkDeselected (a pod only the API path +// bound) and the reclassification (an NRI-marked pod the API path does not +// send) decide a Selected pod with no section a pod mark holds alike, for +// the four combinations of Strict and shape: the mark goes unless the pod +// is Strict with a shape. +func TestFU2UnmarkPathsAgree(t *testing.T) { + for _, tc := range []struct { + name string + policy func() *unstructured.Unstructured + strict bool + shape bool + }{ + {name: "audit, no shape", policy: func() *unstructured.Unstructured { return fu2ExecOnlyPolicy("audit") }}, + {name: "strict, no shape", policy: func() *unstructured.Unstructured { return fu2ExecOnlyPolicy("enforce") }, strict: true}, + {name: "audit, sources", policy: func() *unstructured.Unstructured { return fu2Mode(fu2SourcesPolicy(), "audit") }, shape: true}, + {name: "strict, sources", policy: fu2SourcesPolicy, strict: true, shape: true}, + } { + want := !tc.strict || !tc.shape + t.Run(tc.name+"/reclassify", func(t *testing.T) { + s, backend := nriTestService(t) + n := readyNRIGate(t, s, backend) + s.nriGate = n + sb, err := n.Sandbox(nriTestPod("sb1", 42)) + if err != nil { + t.Fatal(err) + } + if _, err := n.JoinAndMark(t.Context(), sb, n.Classify(t.Context(), fu2Req), soon()); err != nil { + t.Fatal(err) + } + c3UsePolicies(t, s, backend.fakeGateBackend, tc.policy()) + s.inputEpoch.Add(1) + c := n.Classify(t.Context(), fu2Req) + if c.Class != sandboxpolicy.PodSelected || len(c.Sections) != 0 || c.Strict != tc.strict || (c.Shape != 0) != tc.shape { + t.Fatalf("setup: classification %+v", c) + } + s.podSeq = &c.Seq + for range 3 { + s.bindPodPlans(t.Context(), nil, nil, nil, nil, false) + } + if got := backend.count("UnmarkPod") > 0 && !n.HoldsMark("pod-uid"); got != want { + t.Fatalf("unmarked %v, want %v: calls %v", got, want, backend.calls) + } + }) + t.Run(tc.name+"/refresh", func(t *testing.T) { + b, s, client := deselectService(t) + if _, err := client.Resource(sandboxpolicy.PolicyGVR).Namespace("ns").Create(t.Context(), tc.policy(), metav1.CreateOptions{}); err != nil { + t.Fatal(err) + } + deletePolicy(t, client, "priv") + resync(t, s) + if got := b.rec("pod-uid") == nil && b.rec("pod2-uid") == nil; got != want { + t.Fatalf("unmarked %v, want %v: calls %v", got, want, b.callNames()) + } + }) + } +} + +// fu2CommitBackend runs after (afterRead) or before (beforeRead) each +// hold read-back a commit of the pod, as a refresh's bind returning then. +type fu2CommitBackend struct { + *fakeGateBackend + gate *podGate + afterRead, beforeRead atomic.Bool +} + +func (b *fu2CommitBackend) commit() { + b.gate.afterBind([]sandboxpolicy.PodBinding{{PodUID: "pod-uid"}}, b.gate.releases) +} + +func (b *fu2CommitBackend) EnsurePodBound(ctx context.Context, uid types.UID, plan sandboxpolicy.Plan) []sandboxpolicy.PodSectionResult { + res := b.fakeGateBackend.EnsurePodBound(ctx, uid, plan) + if b.beforeRead.Load() { + b.commit() + } + return res +} + +func (b *fu2CommitBackend) ConfirmPod(uid types.UID, cgroupID uint64, plan sandboxpolicy.Plan) []sandboxpolicy.PodSectionConfirmation { + res := b.fakeGateBackend.ConfirmPod(uid, cgroupID, plan) + if b.afterRead.Load() { + b.commit() + } + return res +} + +// TestFU2HoldRefusesAfterACommit (CodeRabbit #1176 4810415638): a hold +// that ends at its deadline returns its last read-back only while no +// write of the pod's plan landed after that read; otherwise none, with +// errCommittedAfterRead, so the create is refused. A commit before the +// read is in it: the read-back is returned. +func TestFU2HoldRefusesAfterACommit(t *testing.T) { + for _, tc := range []struct { + name string + before, after bool + wantCommitRefuse bool + }{ + {name: "no commit"}, + {name: "commit before the read", before: true}, + {name: "commit after the read", after: true, wantCommitRefuse: true}, + } { + t.Run(tc.name, func(t *testing.T) { + b := &fu2CommitBackend{fakeGateBackend: newFakeGateBackend()} + g := newPodGate(t.Context(), b, nil) + b.gate = g + c := selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p1", api.ModeEnforce)) + if _, err := g.JoinAndMark(t.Context(), testSandbox("sb1"), c, soon()); err != nil { + t.Fatal(err) + } + b.beforeRead.Store(tc.before) + b.afterRead.Store(tc.after) + // Another plan than the record's: never Confirmed, so the hold + // runs to its deadline. + other := selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p9", api.ModeEnforce)) + confs, err := g.HoldUntilConfirmed(t.Context(), "pod-uid", "sb1", other, time.Now().Add(60*time.Millisecond)) + if !errors.Is(err, errWorkDeadline) { + t.Fatalf("hold: %v, want errWorkDeadline", err) + } + if got := errors.Is(err, errCommittedAfterRead); got != tc.wantCommitRefuse || (len(confs) == 0) != tc.wantCommitRefuse { + t.Fatalf("hold: %+v %v, want refused for a later commit: %v", confs, err, tc.wantCommitRefuse) + } + g.wait() + }) + } +} + +// TestFU2CommitsCount (CodeRabbit #1176 4810415638): a mark, an unmark and +// a refresh's bind of the pod each count a commit once they returned. +func TestFU2CommitsCount(t *testing.T) { + b := newFakeGateBackend() + g := newPodGate(t.Context(), b, nil) + commits := func() uint64 { + g.podMu.Lock() + defer g.podMu.Unlock() + return g.pods["pod-uid"].commits + } + c := selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p1", api.ModeEnforce)) + if _, err := g.JoinAndMark(t.Context(), testSandbox("sb1"), c, soon()); err != nil { + t.Fatal(err) + } + if got := commits(); got != 1 { + t.Fatalf("after a mark: %d commits, want 1", got) + } + g.afterBind([]sandboxpolicy.PodBinding{{PodUID: "pod-uid"}, {PodUID: "other"}}, g.releases) + if got := commits(); got != 2 { + t.Fatalf("after a refresh's bind: %d commits, want 2", got) + } + if err := g.Unmark(t.Context(), testSandbox("sb1"), sandboxpolicy.Seq{Config: 2, Input: 2}, soon()); err != nil { + t.Fatal(err) + } + if got := commits(); got != 3 { + t.Fatalf("after an unmark: %d commits, want 3", got) + } + if _, err := g.HoldUntilConfirmed(t.Context(), "pod-uid", "sb1", c, time.Now().Add(30*time.Millisecond)); err == nil { + t.Fatal("setup: the unmarked pod confirmed") + } + if got := commits(); got != 3 { + t.Fatalf("a hold counted a commit: %d, want 3", got) + } + g.wait() +} + +// fu2NoEngine is a privilege engine that never starts an instance: the +// end-to-end tests below need the node owner's restart and proof state +// only. +type fu2NoEngine struct{} + +func (fu2NoEngine) Start(context.Context, string, privruntime.Config) (igbackend.PrivilegeInstance, error) { + return nil, errors.New("no instance in this test") +} + +// fu2RealBackend is a SectionBackend over the real privilege node owner, +// with restart survival off after a read failure when off (its pin root's +// section path is a file, so the previous runs' sets cannot be read). +func fu2RealBackend(t *testing.T, off bool) (*sandboxpolicy.SectionBackend, *igbackend.PrivilegeBackend) { + t.Helper() + priv, err := igbackend.NewPrivilege(fu2NoEngine{}, nil, "fu2") + if err != nil { + t.Fatal(err) + } + if off { + root := t.TempDir() + if err := os.WriteFile(filepath.Join(root, sandboxpolicy.SectionPrivilege), nil, 0o600); err != nil { + t.Fatal(err) + } + if err := priv.RestartSurvival(root); err == nil { + t.Fatal("setup: restart survival read a file as its pin root") + } + } + sb, err := sandboxpolicy.NewSectionBackend(newFakeGateBackend(), priv, nil) + if err != nil { + t.Fatal(err) + } + return sb, priv +} + +// TestFU2WatermarkThroughRealNodeOwner (batch 17 follow-up; rev-a's +// untested wiring): nriGate.AdoptedStrict → SectionBackend.AdoptedPending +// → the real node owner's AdoptedPending. With restart survival off after +// a read failure, or a section unavailable with its pinned sets kept, a +// pod cgroup is refused (an error), unless its ID is above the watermark +// taken from node-agent's own cgroup: no previous run can have marked it. +// Cgroup 0 and cgroups at or below the watermark stay refused; an unread +// watermark narrows nothing. +func TestFU2WatermarkThroughRealNodeOwner(t *testing.T) { + for _, kept := range []bool{false, true} { + t.Run(fmt.Sprintf("network section kept %v", kept), func(t *testing.T) { + back, _ := fu2RealBackend(t, true) + if kept { + back.WithNetwork(nil, keptPins(errors.New("network image not loaded"), true)) + } + s, _ := nriTestService(t) + s.backend = back + n := s.newNRIGate(back, "/proc") + ask := func(cgroup uint64) (bool, error) { + return n.AdoptedStrict(startgate.Sandbox{UID: "pod-uid", CgroupID: cgroup}, soon()) + } + for _, cgroup := range []uint64{0, 400, 500} { + if strict, err := ask(cgroup); strict || !errors.Is(err, sandboxpolicy.ErrPinnedSetsKept) { + t.Fatalf("no watermark, cgroup %d: %v %v, want ErrPinnedSetsKept", cgroup, strict, err) + } + } + // An unread watermark: reported, nothing narrowed. + var reported []error + s.options.OnError = func(err error) { reported = append(reported, err) } + s.setCgroupWatermark(func(uint32) ([]byte, error) { return nil, errors.New("EPERM") }) + if strict, err := ask(500); strict || err == nil || len(reported) != 1 { + t.Fatalf("unread watermark: %v %v, reports %v", strict, err, reported) + } + // A root cgroup read: reported, nothing narrowed (rev-b LOW-1). + s.podCgroupID = func(string) (uint64, error) { return 1, nil } + s.setCgroupWatermark(func(uint32) ([]byte, error) { return []byte("0::/\n"), nil }) + if strict, err := ask(500); strict || err == nil || len(reported) != 2 { + t.Fatalf("root-cgroup watermark: %v %v, reports %v", strict, err, reported) + } + // node-agent's own cgroup is ID 400. + s.podCgroupID = func(path string) (uint64, error) { + if path != "/kubepods.slice/node-agent.scope" { + return 0, fmt.Errorf("no cgroup %s", path) + } + return 400, nil + } + s.setCgroupWatermark(func(uint32) ([]byte, error) { return []byte("0::/kubepods.slice/node-agent.scope\n"), nil }) + if strict, err := ask(500); strict || err != nil { + t.Fatalf("a cgroup above the watermark: %v %v, want clear", strict, err) + } + for _, cgroup := range []uint64{0, 399, 400} { + if strict, err := ask(cgroup); strict || !errors.Is(err, sandboxpolicy.ErrPinnedSetsKept) { + t.Fatalf("cgroup %d at or below the watermark: %v %v, want ErrPinnedSetsKept", cgroup, strict, err) + } + } + }) + } + // Restart survival that was never enabled has no previous run's marks + // to read: clear for every cgroup, as before. + back, _ := fu2RealBackend(t, false) + if strict, err := back.AdoptedPending(0, soon()); strict || err != nil { + t.Fatalf("no restart state: %v %v", strict, err) + } +} + +// TestFU2OwnCgroupID: the watermark is the ID of the cgroup node-agent's +// own process is in, read in the host cgroup namespace; a path outside it, +// a missing ID or a read error gives none. +func TestFU2OwnCgroupID(t *testing.T) { + id := func(path string) (uint64, error) { + if path == "/a" { + return 9, nil + } + if path == "/zero" { + return 0, nil + } + return 0, errors.New("no such cgroup") + } + var pid uint32 + read := func(data string, err error) func(uint32) ([]byte, error) { + return func(p uint32) ([]byte, error) { pid = p; return []byte(data), err } + } + if got, err := ownCgroupID(read("0::/a\n", nil), id); got != 9 || err != nil || pid != uint32(os.Getpid()) { + t.Fatalf("own cgroup: %d %v (pid %d)", got, err, pid) + } + // The root cgroup is no watermark (rev-b LOW-1), even with an ID. + root := func(path string) (uint64, error) { + if path == "/" { + return 1, nil + } + return id(path) + } + if got, err := ownCgroupID(read("0::/\n", nil), root); got != 0 || err == nil { + t.Fatalf("the root cgroup as a watermark: %d %v", got, err) + } + for _, r := range []func(uint32) ([]byte, error){read("0::/../a\n", nil), read("0::/zero\n", nil), read("0::/b\n", nil), read("", errors.New("EPERM")), read("1:cpu:/a\n", nil)} { + if got, err := ownCgroupID(r, id); got != 0 || err == nil { + t.Fatalf("a watermark from a bad read: %d %v", got, err) + } + } + if _, err := ownCgroupID(nil, id); err == nil { + t.Fatal("no reader") + } +} + +// TestFU2ReproveThroughRealNodeOwner (rev-a MEDIUM on #1176 4802130614, +// end to end): a cgroup queued for a re-proof (ReproveCgroup) is proven by +// the refresh's classification of its pod (Unselected) only once the real +// node owner has Synchronize's sequence for that epoch; until then it stays +// queued. +func TestFU2ReproveThroughRealNodeOwner(t *testing.T) { + back, _ := fu2RealBackend(t, false) + s, exec := nriTestService(t) + s.backend = back + useNoPolicy(t, s, exec.fakeGateBackend) + n := s.newNRIGate(back, "/proc") + if err := s.enableStartGate(t.Context(), startGateSyscalls()); err != nil { + t.Fatal(err) + } + n.gate = s.gate.Load() + sb := startgate.Sandbox{UID: "pod-uid", Namespace: "ns", Name: "pod", ID: "sb1", CgroupID: 77, CgroupPath: nriTestPodPath} + if err := n.JoinUnselected(sb); err != nil { + t.Fatal(err) + } + syncSeq := n.ClassificationSeq(t.Context()) + n.SetNRISynced(1, nil) + n.ReproveCgroup(1, sb) + queued := func() bool { + n.mu.Lock() + defer n.mu.Unlock() + _, ok := n.reprove[77] + return ok + } + n.reclassifyUnbound(t.Context(), nil, syncSeq) + if !queued() { + t.Fatal("proven without Synchronize's sequence") + } + n.SetNRISyncSeq(1, syncSeq) + n.reclassifyUnbound(t.Context(), nil, syncSeq) + if queued() { + t.Fatal("not proven at Synchronize's sequence") + } +} + +// fu2Prover answers ProveNRICgroup with answer and records the calls. +type fu2Prover struct { + *nriTestBackend + mu sync.Mutex + calls []string + answer bool +} + +func (p *fu2Prover) ProveNRICgroup(epoch, cgroup uint64, seq sandboxpolicy.Seq) bool { + p.mu.Lock() + defer p.mu.Unlock() + p.calls = append(p.calls, fmt.Sprintf("%d:%d:%d/%d", epoch, cgroup, seq.Config, seq.Input)) + return p.answer +} + +func (p *fu2Prover) count() int { + p.mu.Lock() + defer p.mu.Unlock() + return len(p.calls) +} + +// TestFU2ReproveRules (rev-a MEDIUM on #1176 4802130614): the re-proof +// proves only what Synchronize would have: an Unselected pod, or a +// Selected one with no section and not Strict, that the gate holds no mark +// for. Anything else stays queued; an item of an older Synchronize, or of +// a pod the gate no longer has, is dropped unasked. +func TestFU2ReproveRules(t *testing.T) { + setup := func(t *testing.T, policy func(*Service, *nriTestBackend)) (*nriGate, *fu2Prover, startgate.Sandbox) { + s, backend := nriTestService(t) + if policy != nil { + policy(s, backend) + } + n := readyNRIGate(t, s, backend) + prover := &fu2Prover{nriTestBackend: backend, answer: true} + n.sync = prover + sb, err := n.Sandbox(nriTestPod("sb1", 42)) + if err != nil { + t.Fatal(err) + } + n.SetNRISynced(1, nil) + return n, prover, sb + } + queued := func(n *nriGate) bool { + n.mu.Lock() + defer n.mu.Unlock() + _, ok := n.reprove[77] + return ok + } + unselected := func(s *Service, b *nriTestBackend) { useNoPolicy(t, s, b.fakeGateBackend) } + audit := func(s *Service, b *nriTestBackend) { useAuditPolicy(t, s, b.fakeGateBackend) } + auditSources := func(s *Service, b *nriTestBackend) { + c3UsePolicies(t, s, b.fakeGateBackend, fu2Mode(fu2SourcesPolicy(), "audit")) + } + for _, tc := range []struct { + name string + policy func(*Service, *nriTestBackend) + mark bool // the gate holds a mark of the pod + answer bool + proven bool + }{ + {name: "unselected", policy: unselected, answer: true, proven: true}, + {name: "audit sectionless", policy: auditSources, answer: true, proven: true}, + {name: "unselected, the backend refuses", policy: unselected}, + {name: "strict with a section", answer: true}, + {name: "audit with a section", policy: audit, answer: true}, + {name: "strict sources", policy: func(s *Service, b *nriTestBackend) { c3UsePolicies(t, s, b.fakeGateBackend, fu2SourcesPolicy()) }, answer: true}, + {name: "unselected, a mark held", policy: unselected, mark: true, answer: true}, + } { + t.Run(tc.name, func(t *testing.T) { + n, prover, sb := setup(t, tc.policy) + prover.answer = tc.answer + if tc.mark { + n.gate.podMu.Lock() + n.gate.sent["pod-uid"] = []uint64{77} + n.gate.podMu.Unlock() + } + if err := n.JoinUnselected(sb); err != nil { + t.Fatal(err) + } + n.ReproveCgroup(1, sb) + n.reclassifyUnbound(t.Context(), nil, sandboxpolicy.Seq{}) + if queued(n) == tc.proven { + t.Fatalf("queued %v, calls %v, classification %+v", queued(n), prover.calls, n.Classify(t.Context(), fu2Req)) + } + wantCalls := 0 + if tc.proven || tc.policy != nil && !tc.mark && !tc.answer { + wantCalls = 1 + } + if prover.count() != wantCalls { + t.Fatalf("ProveNRICgroup calls %v, want %d", prover.calls, wantCalls) + } + }) + } + // rev-b LOW-4: an exempt pod that a policy selects (ExemptButSelected, + // class Unselected) is proven as Synchronize proves it. + t.Run("exempt but selected", func(t *testing.T) { + n, prover, sb := setup(t, nil) + n.source.ExemptionKey = "sandbox.kubescape.io/exempt" + sb.Annotations = map[string]string{"sandbox.kubescape.io/exempt": "true"} + c := n.Classify(t.Context(), sandboxpolicy.ClassifyRequest{Pod: sandboxpolicy.NRIPod{UID: sb.UID, Namespace: sb.Namespace, Name: sb.Name, Annotations: sb.Annotations}}) + if c.Class != sandboxpolicy.PodUnselected || !c.Exempt || !c.ExemptButSelected { + t.Fatalf("setup: exempt classification %+v", c) + } + if err := n.JoinUnselected(sb); err != nil { + t.Fatal(err) + } + n.ReproveCgroup(1, sb) + n.reclassifyUnbound(t.Context(), nil, sandboxpolicy.Seq{}) + if queued(n) || prover.count() != 1 { + t.Fatalf("an ExemptButSelected pod: queued %v, calls %v", queued(n), prover.calls) + } + }) + t.Run("older synchronize", func(t *testing.T) { + n, prover, sb := setup(t, unselected) + if err := n.JoinUnselected(sb); err != nil { + t.Fatal(err) + } + n.ReproveCgroup(1, sb) + n.SetNRISynced(2, nil) + n.reclassifyUnbound(t.Context(), nil, sandboxpolicy.Seq{}) + if queued(n) || prover.count() != 0 { + t.Fatalf("an older Synchronize's item: queued %v, calls %v", queued(n), prover.calls) + } + }) + t.Run("pod gone", func(t *testing.T) { + n, prover, sb := setup(t, unselected) + n.ReproveCgroup(1, sb) + n.reclassifyUnbound(t.Context(), nil, sandboxpolicy.Seq{}) + if queued(n) || prover.count() != 0 { + t.Fatalf("a pod with no gate entry: queued %v, calls %v", queued(n), prover.calls) + } + }) + t.Run("no cgroup", func(t *testing.T) { + n, _, sb := setup(t, unselected) + sb.CgroupID = 0 + n.ReproveCgroup(1, sb) + n.mu.Lock() + defer n.mu.Unlock() + if len(n.reprove) != 0 { + t.Fatalf("cgroup 0 queued: %v", n.reprove) + } + }) +} + +// fu2SectionDownBackend fails MarkPod, BindPodsAt and UnmarkPod, writing +// nothing, while down() holds, as a section whose instance is not ready +// (the S5b review v2 probe P1's backend). +type fu2SectionDownBackend struct { + *nriTestBackend + down func() bool +} + +func (b *fu2SectionDownBackend) MarkPod(ctx context.Context, pod sandboxpolicy.PodBinding, seq sandboxpolicy.Seq) []sandboxpolicy.PodSectionResult { + if b.down() { + b.record("MarkPod down") + return []sandboxpolicy.PodSectionResult{{Section: sandboxpolicy.SectionPrivilege, Strict: strictPlan(pod.Plan), Err: errors.New("privilege: instance not ready")}} + } + return b.nriTestBackend.MarkPod(ctx, pod, seq) +} + +func (b *fu2SectionDownBackend) BindPodsAt(ctx context.Context, pods []sandboxpolicy.PodBinding, seq sandboxpolicy.Seq) error { + if b.down() { + b.record("BindPodsAt down") + return errors.New("privilege: instance not ready") + } + return b.nriTestBackend.BindPodsAt(ctx, pods, seq) +} + +func (b *fu2SectionDownBackend) UnmarkPod(ctx context.Context, uid types.UID, cgroup uint64, seq sandboxpolicy.Seq) error { + if b.down() { + b.record("UnmarkPod down") + return errors.New("privilege: instance not ready") + } + return b.nriTestBackend.UnmarkPod(ctx, uid, cgroup, seq) +} + +// TestFU2WriteFailStrengthenViaMerge (S5b review v2 C1, probe P1 ported): +// an NRI-only Audit-marked pod whose policy turns enforce while its section +// is down (MarkPod and BindPodsAt fail and write nothing) is Strict on the +// first refresh after the section recovers, whatever the outage, because +// merge resends the stored plan; the reclassification's own retry may +// still be far off. The refresh sequence is the realistic one, equal to +// the reclassification's classification sequence. +func TestFU2WriteFailStrengthenViaMerge(t *testing.T) { + for _, outage := range []time.Duration{10 * time.Second, 45 * time.Second, 85 * time.Second, 150 * time.Second} { + start := time.Unix(1_000_000, 0) + clock := start + s, backend := nriTestService(t) + useAuditPolicy(t, s, backend) + n := readyNRIGate(t, s, backend) + s.nriGate = n + n.now = func() time.Time { return clock } + c := n.Classify(t.Context(), fu2Req) + sb, err := n.Sandbox(nriTestPod("sb1", 42)) + if err != nil { + t.Fatal(err) + } + if _, err := n.JoinAndMark(t.Context(), sb, c, soon()); err != nil { + t.Fatal(err) + } + idx := s.pods.Core().V1().Pods().Informer().GetIndexer() + _ = idx.Delete(&corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod", Namespace: "ns", UID: "pod-uid"}}) + n.gate.backend = &fu2SectionDownBackend{nriTestBackend: backend, down: func() bool { return clock.Sub(start) < outage }} + fresh, _ := nriTestService(t) + s.Controller = fresh.Controller // enforce + s.inputEpoch.Add(1) + c2 := n.Classify(t.Context(), fu2Req) + if !c2.Strict { + t.Fatalf("classification %+v", c2) + } + seq := c2.Seq + s.podSeq = &seq + at := time.Duration(-1) + for range 80 { + s.bindPodPlans(context.Background(), nil, nil, nil, nil, false) + if strictRecordV4(backend) { + at = clock.Sub(start) + break + } + clock = clock.Add(5 * time.Second) + } + if at != outage { + t.Fatalf("outage %v: Strict at +%v, want +%v (the first refresh after recovery)", outage, at, outage) + } + } +} + +// TestFU2UnknownFlapKeepsBackoff (S5b review v2 C2, probe P2 ported to +// an Audit write, which backs off): an NRI-only pod whose GET fails on +// every other refresh and whose Audit mark keeps failing at one sequence +// is written on the backoff schedule, as for a steady failure, not on every +// refresh where the GET answers: an Unknown leaves the schedule alone. +// Unknown itself is still never delayed: the pod is classified (a GET) on +// every refresh. +func TestFU2UnknownFlapKeepsBackoff(t *testing.T) { + start := time.Unix(1_000_000, 0) + clock := start + s, backend := nriTestService(t) + c3UsePolicies(t, s, backend.fakeGateBackend, c3Policy("audit", "audit", "chroot", nil)) + n := readyNRIGate(t, s, backend) + s.nriGate = n + n.now = func() time.Time { return clock } + c := n.Classify(t.Context(), fu2Req) + sb, err := n.Sandbox(nriTestPod("sb1", 42)) + if err != nil { + t.Fatal(err) + } + if _, err := n.JoinAndMark(t.Context(), sb, c, soon()); err != nil { + t.Fatal(err) + } + idx := s.pods.Core().V1().Pods().Informer().GetIndexer() + _ = idx.Delete(&corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod", Namespace: "ns", UID: "pod-uid"}}) + var gets atomic.Int32 + fu2GetReactor(s, func() bool { + gets.Add(1) + return (clock.Sub(start)/(5*time.Second))%2 == 1 + }) + c3UsePolicies(t, s, backend.fakeGateBackend, c3Policy("audit", "audit", "mount", nil)) + s.inputEpoch.Add(1) + c2 := n.Classify(t.Context(), fu2Req) + if c2.Class != sandboxpolicy.PodSelected || c2.Strict { + t.Fatalf("setup: changed Audit classification %+v", c2) + } + seq := sandboxpolicy.Seq{Config: c2.Seq.Config + 100, Input: s.inputEpoch.Load()} + s.podSeq = &seq + backend.mu.Lock() + backend.markErr = errors.New("privilege: instance not ready") + backend.mu.Unlock() + gets.Store(0) + before := backend.count("MarkPod") + for range 30 { + s.bindPodPlans(context.Background(), nil, nil, nil, nil, false) + clock = clock.Add(5 * time.Second) + } + marks := backend.count("MarkPod") - before + t.Logf("30 refreshes over 150 s, GET down on every other one: MarkPod %d, GETs %d", marks, gets.Load()) + // A steady failure gives 5 to 7 writes over 150 s (TestReviewV4Section + // FailureBacksOff); clearing on Unknown gave 15. + if marks > 7 { + t.Fatalf("an alternating Unknown defeats the backoff: %d MarkPod over 150 s, want at most 7", marks) + } + if gets.Load() < 30 { + t.Fatalf("Unknown was delayed: %d GETs over 30 refreshes", gets.Load()) + } +} + +// fu2GetReactor fails the pod GETs while down() holds. +func fu2GetReactor(s *Service, down func() bool) { + s.options.Kubernetes.(*kubefake.Clientset).PrependReactor("get", "pods", func(k8stesting.Action) (bool, runtime.Object, error) { + if down() { + return true, nil, errors.New("transient API error") + } + return false, nil, nil + }) +} diff --git a/pkg/sandboxpolicy/integration/nrigate.go b/pkg/sandboxpolicy/integration/nrigate.go index a1a520a862..3b5b73291a 100644 --- a/pkg/sandboxpolicy/integration/nrigate.go +++ b/pkg/sandboxpolicy/integration/nrigate.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "maps" + "os" "path/filepath" "slices" "strings" @@ -17,6 +18,7 @@ import ( "github.com/kubescape/go-logger" "github.com/kubescape/go-logger/helpers" "github.com/kubescape/node-agent/pkg/sandboxpolicy" + "github.com/kubescape/node-agent/pkg/sandboxpolicy/igbackend" "github.com/kubescape/node-agent/pkg/sandboxpolicy/startgate" sandboxapi "github.com/kubescape/storage/pkg/apis/sandbox/v1alpha1" "golang.org/x/sys/unix" @@ -106,6 +108,24 @@ type nriGate struct { // unmarked, when set, runs after an Unmark's gate write succeeded and // before its metadata update (tests). unmarked func(uid types.UID) + // syncEpoch is the epoch of the last completed Synchronize + // (SetNRISynced), and reprove the pod cgroups to prove for a completed + // Synchronize after it (ReproveCgroup), by cgroup ID. An entry goes + // once proven, once its pod has no gate entry (prune), or once it is + // not of syncEpoch (a later Synchronize proved what it could). Under + // mu. + syncEpoch uint64 + reprove map[uint64]reproveItem + reproveGen uint64 +} + +// reproveItem is a pod cgroup to prove again: the Synchronize it is for, +// and the pod to classify. +type reproveItem struct { + epoch uint64 + pod sandboxpolicy.NRIPod + // gen tells a queued item from a later one for the same cgroup. + gen uint64 } // bumpLocked gives m a new generation. Runs under mu. @@ -306,8 +326,8 @@ type nriPayload struct { seq sandboxpolicy.Seq // fails counts the pod's failed marks or unmarks in a row at failSeq, // and retryAt is the earliest time of the next try (S5 review v4 V4-2). - // A definitive outcome, an Unknown classification or a new mark clears - // them. + // A definitive outcome or a new mark clears them; an Unknown + // classification leaves them (S5b review v2 C2). fails int failSeq sandboxpolicy.Seq retryAt time.Time @@ -366,6 +386,7 @@ func (s *Service) enableNRIStartGate(ctx context.Context, sys handleSyscalls, pr if err := HostPIDNamespace(procRoot); err != nil { return fmt.Errorf("start gate: %w", err) } + s.setCgroupWatermark(func(pid uint32) ([]byte, error) { return igbackend.ReadHostProcessCgroup(procRoot, pid) }) n := s.newNRIGate(syncer, procRoot) plugin, err := startgate.NewPlugin(n, startgate.Options{ SocketPath: socket, @@ -386,6 +407,57 @@ func (s *Service) enableNRIStartGate(ctx context.Context, sys handleSyscalls, pr return nil } +// cgroupWatermarker takes the cgroup-ID watermark +// (sandboxpolicy.SectionBackend.SetCgroupWatermark). +type cgroupWatermarker interface { + SetCgroupWatermark(id uint64) +} + +// setCgroupWatermark gives the backend the ID of node-agent's own cgroup, +// read in the host cgroup namespace (read: /proc//cgroup there) and +// resolved as a pod cgroup is (podCgroupID): no previous run can have +// marked a cgroup above it (SetCgroupWatermark says why). When it cannot +// be read, the backend gets none and narrows nothing (fail-closed), and +// the reason is reported. +func (s *Service) setCgroupWatermark(read func(pid uint32) ([]byte, error)) { + w, ok := s.backend.(cgroupWatermarker) + if !ok { + return + } + id, err := ownCgroupID(read, s.podCgroupID) + if err != nil { + s.report(fmt.Errorf("start gate: node-agent's own cgroup ID not read, so while a previous run's pinned sets cannot be read every Unselected, sectionless and exempt container is refused: %w", err)) + return + } + w.SetCgroupWatermark(id) +} + +// ownCgroupID returns the cgroup ID of node-agent's own process. +func ownCgroupID(read func(pid uint32) ([]byte, error), id func(string) (uint64, error)) (uint64, error) { + if read == nil || id == nil { + return 0, errors.New("no cgroup reader") + } + path, err := processCgroup(read, uint32(os.Getpid())) + if err != nil { + return 0, err + } + if path == "/" { + // The root cgroup is older than every pod cgroup: as a watermark + // it would clear nearly every cgroup. Under Kubernetes node-agent + // is never there, so this is a misread or a hand-run binary: + // no watermark (fail-closed; rev-b LOW-1). + return 0, errors.New("node-agent's own cgroup reads as the root cgroup, which is no watermark") + } + cgroup, err := id(path) + if err != nil { + return 0, fmt.Errorf("cgroup %s: %w", path, err) + } + if cgroup == 0 { + return 0, fmt.Errorf("cgroup %s has no ID", path) + } + return cgroup, nil +} + // newNRIGate builds the gate's sources from the service: the informers (the // classification's Lookup), a bounded API GET for an informer miss (Fetch), // and the pod cgroup resolver with the learned layout. @@ -498,13 +570,14 @@ func (n *nriGate) JoinAndMark(ctx context.Context, sb startgate.Sandbox, c sandb // ErrSandboxRemoved (rev-a round 6b residual LOW). // // The payload's memo is the mark's sequence only when the mark is a - // definitive outcome, by reclassifyUnbound's rule (every section nil or - // ErrPolicyEntry): a failed one stays eligible for the refresh's - // reclassification at that same sequence (CodeRabbit #1176 4810415611). + // definitive outcome, by reclassifyUnbound's rule (every section + // settled: sectionSettled): a failed one stays eligible for the + // refresh's reclassification at that same sequence (CodeRabbit #1176 + // 4810415611). if sb.CgroupID != 0 && !errors.Is(err, errSandboxRemoved) { memo := c.Seq if err != nil || len(res) == 0 || slices.ContainsFunc(res, func(r sandboxpolicy.PodSectionResult) bool { - return r.Err != nil && !errors.Is(r.Err, sandboxpolicy.ErrPolicyEntry) + return !sectionSettled(r.Err) }) { memo = sandboxpolicy.Seq{} } @@ -521,6 +594,29 @@ func (n *nriGate) JoinAndMark(ctx context.Context, sb startgate.Sandbox, c sandb return res, err } +// noPodSections reports whether a classification wants no pod mark: Selected +// with no section a pod mark holds, and either not Strict (Audit, or http +// only: batch 7 F2) or with no shape (exec or http policies only). Owner +// batch 18, read fail-closed (rev-b HIGH-1 on fu2): a Strict pod with a +// shape (sources, different sets per container) keeps its mark, which +// still judges a task whose container binding is missing or failed (an +// unresolved ContainerProfile, a failed bind) under a Strict rule that is +// in force. The refresh (unmarkDeselected) and the reclassification +// (reclassifyUnbound) both use it, so they agree. +func noPodSections(c sandboxpolicy.PodClassification) bool { + return c.Class == sandboxpolicy.PodSelected && len(c.Sections) == 0 && (!c.Strict || c.Shape == 0) +} + +// sectionSettled reports whether a section's mark result is definitive: +// accepted, or an adopted policy-slot entry at least as strict as the plan +// (ErrPolicyEntry), which stays until the refresh's bind moves the pod. An +// inherited Strict pending mark that refused an Audit mark +// (ErrInheritedStrictMark) is not: a proof retires it later, and only a +// retry then writes the Audit mark (CodeRabbit #1176 4810415619). +func sectionSettled(err error) bool { + return err == nil || errors.Is(err, sandboxpolicy.ErrPolicyEntry) && !errors.Is(err, sandboxpolicy.ErrInheritedStrictMark) +} + func (n *nriGate) JoinUnselected(sb startgate.Sandbox) error { return n.gate.JoinUnselected(toGate(sb)) } @@ -690,6 +786,9 @@ func (n *nriGate) followSurvivorLocked(removed startgate.Sandbox, e *gatePod) { } func (n *nriGate) SetNRISynced(epoch uint64, proven map[uint64]bool) { + n.mu.Lock() + n.syncEpoch = max(n.syncEpoch, epoch) + n.mu.Unlock() n.sync.SetNRISynced(epoch, proven) // A converged refresh retires the previous run's pending marks the // proof covers (Settle): run one now rather than at the next tick, so @@ -700,6 +799,81 @@ func (n *nriGate) SetNRISynced(epoch uint64, proven map[uint64]bool) { } } +// ReproveCgroup queues the sandbox's pod cgroup for the proof of the +// Synchronize on epoch (startgate.Gate), which the next refresh tries +// (reproveHeld); a refresh is queued now. No I/O, no wait. +func (n *nriGate) ReproveCgroup(epoch uint64, sb startgate.Sandbox) { + if sb.CgroupID == 0 || sb.UID == "" { + return + } + n.mu.Lock() + if n.reprove == nil { + n.reprove = map[uint64]reproveItem{} + } + n.reproveGen++ + n.reprove[sb.CgroupID] = reproveItem{epoch: epoch, pod: sandboxpolicy.NRIPod{UID: sb.UID, Namespace: sb.Namespace, Name: sb.Name, Annotations: sb.Annotations}, gen: n.reproveGen} + n.mu.Unlock() + if n.s != nil { + n.s.queueRefresh() + } +} + +// reproveHeld tries the proof of each queued cgroup (ReproveCgroup), as +// Synchronize would have proved it: this run's classification of its pod +// is Unselected, or Selected, not Strict and with no section a pod mark +// holds, and the gate holds no mark for the pod. An exempt pod is +// Unselected, ExemptButSelected included, and is proven as Synchronize +// proves it (rev-b LOW-4): the exemption means this run puts no mark on +// it, so an inherited Strict mark would judge only containers the policy +// does not apply to; the conflict itself is admission's (N1 §3) and +// alerts (AlertExemptButSelected). The backend records it +// only at or after that Synchronize's sequence, for that same completion +// (sandboxpolicy.NRICgroupProver, owner batch 12); the next converged +// refresh then retires the previous run's pending marks it covers +// (Settle). Any other answer, an Unknown classification included, leaves +// the cgroup queued for the next refresh (fail-closed: the mark stays). +// Bounded by reclassifyBudget. +func (n *nriGate) reproveHeld(ctx context.Context) { + prover, ok := n.sync.(sandboxpolicy.NRICgroupProver) + n.mu.Lock() + n.gate.podMu.Lock() + for cgroup, it := range n.reprove { + if it.epoch != n.syncEpoch || n.gate.pods[it.pod.UID] == nil { + delete(n.reprove, cgroup) + } + } + n.gate.podMu.Unlock() + todo := maps.Clone(n.reprove) + n.mu.Unlock() + if !ok || len(todo) == 0 { + return + } + deadline := time.Now().Add(reclassifyBudget) + ctx, cancel := context.WithDeadline(ctx, deadline) + defer cancel() + for _, cgroup := range slices.Sorted(maps.Keys(todo)) { + if !time.Now().Before(deadline) { + return + } + it := todo[cgroup] + c := n.Classify(ctx, sandboxpolicy.ClassifyRequest{Pod: it.pod}) + if c.Class != sandboxpolicy.PodUnselected && (c.Class != sandboxpolicy.PodSelected || len(c.Sections) > 0 || c.Strict) { + continue + } + if n.HoldsMark(it.pod.UID) || !prover.ProveNRICgroup(it.epoch, cgroup, c.Seq) { + continue + } + n.mu.Lock() + if q, ok := n.reprove[cgroup]; ok && q.gen == it.gen { + delete(n.reprove, cgroup) + } + n.mu.Unlock() + if n.s != nil { + n.s.queueRefresh() // the converged refresh that retires the mark + } + } +} + // adoptedPendingReader is the backend's read-back of a previous run's // pending marks (sandboxpolicy.AdoptedPendingReader): whether the one on // cgroup is Strict and not yet retired. @@ -774,14 +948,14 @@ func (n *nriGate) Registration() error { // this unmarks it. // // A Selected pod is marked at the new classification, an Unselected one, -// or a Selected one that is not Strict and has no section a mark holds, -// unmarked (which drops its payload), and an Unknown one keeps its mark -// (fail-closed). A pod whose gate entry prune removed is dropped. The refresh stays bounded (S5 review v1 F6): a pod is +// or a Selected one that wants no pod mark (noPodSections), unmarked +// (which drops its payload), and a Strict one with a shape and no section, +// or an Unknown one, keeps its mark (fail-closed). A pod whose gate entry prune removed is dropped. The refresh stays bounded (S5 review v1 F6): a pod is // reclassified only when the refresh's sequence (seq: configSeq and input // epoch) differs from its payload's memo, and the whole pass stops at // reclassifyBudget. The memo advances only on a definitive outcome (S5 // review v3 V3-1, V3-2): an unmark succeeded, or a Selected pod's mark -// succeeded in every section (or it is Strict with no section to mark). An Unknown classification (often a transient GET failure, or the +// succeeded in every section. An Unknown classification (often a transient GET failure, or the // budget expiring mid-GET), a write error, a section's mark failure, or a // budget cut-off leaves the memo unchanged, so a later refresh tries the // pod again. (For a failed section of a Selected pod, merge would also @@ -809,9 +983,11 @@ func (n *nriGate) Registration() error { // reclassifyBudget. An Unknown classification never backs off either (S5b // review v1 B1): only its retry can strengthen an Audit-marked pod that the // API path never lists once the API answers again, so it is retried on -// every refresh and clears any backoff. A definitive outcome or a new mark -// clears it too. +// every refresh. It leaves the backoff of a failing write as it is, which +// holds back only that same write (S5b review v2 C2). A definitive outcome +// or a new mark clears it. func (n *nriGate) reclassifyUnbound(ctx context.Context, bound map[types.UID]bool, seq sandboxpolicy.Seq) { + n.reproveHeld(ctx) n.mu.Lock() var todo []nriPayload // A pod with no gate entry is dead (prune proved its cgroups gone @@ -863,33 +1039,29 @@ func (n *nriGate) reclassifyUnbound(ctx context.Context, bound map[types.UID]boo var results []sandboxpolicy.PodSectionResult results, err = n.mark(ctx, toGate(p.sb), c, deadline) for _, r := range results { - if err == nil && r.Err != nil && !errors.Is(r.Err, sandboxpolicy.ErrPolicyEntry) { + if err == nil && !sectionSettled(r.Err) { err = fmt.Errorf("section %s: %w", r.Section, r.Err) } } - } else if !c.Strict || c.Shape == 0 { - // Audit or http only (batch 7 F2): no section a pod mark - // holds, so an older mark goes, as for an Unselected pod - // (Copilot round 1). So does a Strict one with no shape - // (exec or http policies only): no pod binding is wanted, - // as the refresh's unmarkDeselected decides (Copilot #1165 - // 4796605589), and the unmark here enters the shared - // failure accounting that path's backoff reads (Copilot - // #1178 4802098741). A Strict one with a shape keeps its - // mark (fail-closed): the plugin refuses it (D1). + } else if noPodSections(c) { + // No section a pod mark holds, and nothing a pod mark + // still judges (noPodSections): an older mark goes, as for + // an Unselected pod, through the shared failure accounting + // that the refresh's unmarkDeselected backoff reads + // (Copilot #1178 4802098741). A Strict pod with a shape + // keeps its mark (fail-closed). err = n.Unmark(ctx, p.sb, c.Seq, deadline) } case sandboxpolicy.PodUnselected: err = n.Unmark(ctx, p.sb, c.Seq, deadline) default: - // Unknown: the mark and the memo stay, and the pod is retried on - // the next refresh, with no backoff (S5b review v1 B1). - n.mu.Lock() - if q, ok := n.payloads[p.pod.UID]; ok && q.sb.ID == p.sb.ID { - q.fails, q.failSeq, q.retryAt, q.failKey = 0, sandboxpolicy.Seq{}, time.Time{}, "" - n.payloads[p.pod.UID] = q - } - n.mu.Unlock() + // Unknown: the mark and the memo stay, and the pod is classified + // again on the next refresh, with no backoff (S5b review v1 B1). + // The schedule of a failing write is left as it is: an Unknown + // between two failures of the same write would restart it, and + // a pod whose GET flaps would be written on every refresh (S5b + // review v2 C2). It holds only that same write back: another + // outcome, or a new sequence, is written at once. continue } if err != nil && !errors.Is(err, errSandboxRemoved) { diff --git a/pkg/sandboxpolicy/integration/podgate.go b/pkg/sandboxpolicy/integration/podgate.go index 5d0b47213b..9e81d42229 100644 --- a/pkg/sandboxpolicy/integration/podgate.go +++ b/pkg/sandboxpolicy/integration/podgate.go @@ -55,6 +55,11 @@ var ( errSandboxRemoved = startgate.ErrSandboxRemoved // errNotJoined: the pod has no live sandbox in the gate's set. errNotJoined = errors.New("start gate: the pod sandbox never joined the gate") + // errCommittedAfterRead: a hold ended without every section Confirmed, + // and a write that may change the pod's plan landed after its last + // read-back, so that read-back may not be the plan in force + // (HoldUntilConfirmed; CodeRabbit #1176 4810415638). + errCommittedAfterRead = errors.New("start gate: a write of the pod's plan landed after the last read-back") // errNotSelected: only a Selected pod with a section plan is marked. errNotSelected = errors.New("start gate: only a Selected pod with a section plan is marked") // errNoCgroup: the sandbox's pod cgroup was not resolved (cgroup ID 0). @@ -134,6 +139,17 @@ type gatePod struct { // release kept in unreleased (retryUnreleasedLocked). releaseRetryAt time.Time releaseRetries int + // commits counts the writes that may have changed the pod's plan in + // the backend, each counted once it returned: a mark, an unmark, and a + // refresh's bind that sent the pod (commitLocked). A hold's read-back + // is current while it is unchanged (HoldUntilConfirmed). + commits uint64 +} + +// commitStamp is a pod's commit count as a hold read it, with its entry. +type commitStamp struct { + entry *gatePod + commits uint64 } type tombstone struct { @@ -156,6 +172,8 @@ type gateResult struct { sections []sandboxpolicy.PodSectionResult confirmations []sandboxpolicy.PodSectionConfirmation err error + // stamp is the pod's commit count just before a hold's read-back. + stamp commitStamp } // podWorker runs one pod's jobs in order, one at a time. @@ -456,7 +474,11 @@ func (g *podGate) JoinAndMark(ctx context.Context, sb gateSandbox, c sandboxpoli if removed { return gateResult{err: errSandboxRemoved} } - return gateResult{sections: g.backend.MarkPod(ctx, pod, seq)} + res := gateResult{sections: g.backend.MarkPod(ctx, pod, seq)} + g.podMu.Lock() + g.commitLocked(sb.UID) + g.podMu.Unlock() + return res }, }) g.podMu.Unlock() @@ -536,7 +558,10 @@ func planKey(c sandboxpolicy.PodClassification) string { // the caller's own classification (PodGate.ConfirmPod), again every // holdRetry, until every section is Confirmed or the deadline passes. It // returns the last confirmations it read, with errWorkDeadline (joined with -// the last bind errors) when not every section was Confirmed by then. The +// the last bind errors) when not every section was Confirmed by then; no +// confirmations, with errCommittedAfterRead, when a write that may change +// the pod's plan landed after that read (a refresh's bind, a mark or an +// unmark: gatePod.commits) or the pod was released meanwhile. The // caller decides from the confirmations (a Strict create needs Confirmed, // or Pending with Strict). func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandboxID string, c sandboxpolicy.PodClassification, deadline time.Time) ([]sandboxpolicy.PodSectionConfirmation, error) { @@ -549,7 +574,24 @@ func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandbox plan := classificationPlan(c) key := fmt.Sprintf("hold/%s/%s", sandboxID, planKey(c)) var last []sandboxpolicy.PodSectionConfirmation + var stamp commitStamp var bindErrs []error + // unconfirmed ends the hold with the last read-back, or with none when + // a write of the pod's plan landed after it (CodeRabbit #1176 + // 4810415638): the caller refuses then. The window is the pause + // between two reads (holdRetry) plus one job. + unconfirmed := func(err error) ([]sandboxpolicy.PodSectionConfirmation, error) { + errs := append([]error{err}, bindErrs...) + if last != nil { + g.podMu.Lock() + current := g.pods[uid] == stamp.entry && stamp.entry != nil && !stamp.entry.released && stamp.entry.commits == stamp.commits + g.podMu.Unlock() + if !current { + return nil, errors.Join(append([]error{errCommittedAfterRead}, errs...)...) + } + } + return last, errors.Join(errs...) + } for { g.podMu.Lock() if g.tombstonedLocked(sandboxID) { @@ -573,17 +615,25 @@ func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandbox return gateResult{err: errSandboxRemoved} } bound := g.backend.EnsurePodBound(ctx, uid, plan) - return gateResult{sections: bound, confirmations: g.backend.ConfirmPod(uid, cgroupID, plan)} + // Taken before the read-back: a write counted after it may + // not be in it. + g.podMu.Lock() + stamp := commitStamp{entry: g.pods[uid]} + if stamp.entry != nil { + stamp.commits = stamp.entry.commits + } + g.podMu.Unlock() + return gateResult{sections: bound, confirmations: g.backend.ConfirmPod(uid, cgroupID, plan), stamp: stamp} }}) g.podMu.Unlock() res, err := await(ctx, job, deadline) if err != nil { - return last, errors.Join(append([]error{err}, bindErrs...)...) + return unconfirmed(err) } if res.err != nil { return nil, replyError(res.err) } - last, bindErrs = res.confirmations, nil + last, stamp, bindErrs = res.confirmations, res.stamp, nil for _, r := range res.sections { if r.Err != nil { bindErrs = append(bindErrs, replyError(r.Err)) @@ -597,10 +647,10 @@ func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandbox case <-wait.C: case <-ctx.Done(): wait.Stop() - return last, errors.Join(append([]error{errHandlerGone}, bindErrs...)...) + return unconfirmed(errHandlerGone) } if !time.Now().Before(deadline) { - return last, errors.Join(append([]error{errWorkDeadline}, bindErrs...)...) + return unconfirmed(errWorkDeadline) } } } @@ -730,6 +780,7 @@ func (g *podGate) enqueueUnmarkLocked(uid types.UID, cgroups []uint64, seq sandb err := g.unmarkOwners(ctx, uid, cgroups, seq) g.podMu.Lock() defer g.podMu.Unlock() + g.commitLocked(uid) p := g.pods[uid] if err == nil { // Its binding is gone: the cgroups it covered have nothing @@ -1164,6 +1215,9 @@ func (g *podGate) afterBind(sent []sandboxpolicy.PodBinding, releasesBefore uint g.podMu.Lock() defer g.podMu.Unlock() for _, p := range sent { + // The bind returned: a hold's read-back taken before now may + // predate the plan it committed (HoldUntilConfirmed). + g.commitLocked(p.PodUID) if e := g.pods[p.PodUID]; e != nil && e.released && e.releasedAt > releasesBefore { // This call may have moved the binding to the cgroup it sent. owners := slices.Clone(e.releaseOwners) @@ -1175,6 +1229,14 @@ func (g *podGate) afterBind(sent []sandboxpolicy.PodBinding, releasesBefore uint } } +// commitLocked counts a write that may have changed uid's plan in the +// backend, once it returned (gatePod.commits). Runs under podMu. +func (g *podGate) commitLocked(uid types.UID) { + if p := g.pods[uid]; p != nil { + p.commits++ + } +} + // prune removes the entries and tombstones whose cgroups are proven gone // (by cgroup ID): an entry once every cgroup it tracks (its sandboxes' and // its own) is gone. The proof is I/O: it runs outside podMu. diff --git a/pkg/sandboxpolicy/integration/service.go b/pkg/sandboxpolicy/integration/service.go index 5698000142..bb826aeb81 100644 --- a/pkg/sandboxpolicy/integration/service.go +++ b/pkg/sandboxpolicy/integration/service.go @@ -1486,11 +1486,11 @@ func (s *Service) unmarkDeselected(ctx context.Context, gate *podGate, scheduled return p.facts, namespace == p.ref.Namespace && name == p.ref.Name }, }) - // Selected with no pod-bindable section and no shape a pod binding - // cannot express: only exec or http policies select the pod, so - // no pod binding is wanted any more (Copilot #1165 4796605589). - noPodSections := c.Class == sandboxpolicy.PodSelected && len(c.Sections) == 0 && c.Shape == 0 - if (c.Class == sandboxpolicy.PodUnselected && !c.Exempt) || noPodSections { + // Selected and wanting no pod mark (noPodSections: no pod-bindable + // section, and not Strict or with no shape; Copilot #1165 + // 4796605589; owner batch 18, rev-b HIGH-1): no pod binding is + // wanted any more. The reclassification uses the same rule. + if (c.Class == sandboxpolicy.PodUnselected && !c.Exempt) || noPodSections(c) { // An NRI-marked pod whose unmark keeps failing at this // sequence, for this outcome, waits for the reclassification's // backoff on this path too (Copilot #1178 4792364036). An diff --git a/pkg/sandboxpolicy/sections.go b/pkg/sandboxpolicy/sections.go index dbb9eaa540..2e067de953 100644 --- a/pkg/sandboxpolicy/sections.go +++ b/pkg/sandboxpolicy/sections.go @@ -7,6 +7,7 @@ import ( "sort" "strings" "sync" + "sync/atomic" "time" api "github.com/kubescape/storage/pkg/apis/sandbox/v1alpha1" @@ -43,6 +44,8 @@ type SectionBackend struct { active map[string]sectionPlans // prepareMu guards section.prepared. prepareMu sync.Mutex + // watermark is the cgroup-ID watermark (SetCgroupWatermark; 0: none). + watermark atomic.Uint64 } // section is one section backend next to exec. @@ -429,6 +432,29 @@ type NRISyncSequencer interface { SetNRISyncSeq(epoch uint64, seq Seq) } +// NRICgroupProver is implemented by a pod gate that takes a cgroup into +// the proof of a completed Synchronize after it (rev-a MEDIUM on #1176 +// 4802130614): ProveNRICgroup records cgroup as proven for the Synchronize +// on epoch when seq, this run's classification of its pod needing no +// Strict pending mark, is at or after that Synchronize's sequence (owner +// batch 12). false: not recorded (another completion, no sequence, or an +// older classification). +type NRICgroupProver interface { + ProveNRICgroup(epoch, cgroup uint64, seq Seq) bool +} + +// ProveNRICgroup asks every section whose pod gate takes it +// (NRICgroupProver); true only when each of them recorded it. +func (s *SectionBackend) ProveNRICgroup(epoch, cgroup uint64, seq Seq) bool { + ok := true + for _, sec := range s.sections { + if p, is := sec.backend.(NRICgroupProver); is { + ok = p.ProveNRICgroup(epoch, cgroup, seq) && ok + } + } + return ok +} + // AdoptedPendingReader is implemented by a pod gate that can read back a // previous run's pending marks (Copilot #1176 4802130614): AdoptedPending // reports whether a Strict one that this run does not hold is still on @@ -447,17 +473,52 @@ type AdoptedPendingReader interface { // mark included, and nothing of this run can read them. var ErrPinnedSetsKept = errors.New("the pinned sets of the previous node-agent run are kept and may still enforce") +// SetCgroupWatermark sets the cgroup-ID watermark: no previous node-agent +// run can have marked a cgroup whose ID is above it (rev-a MEDIUM on #1176 +// round 1; owner batch 17 follow-up). Call it once, before the start gate +// runs; 0 (the default) narrows nothing. +// +// Why that holds for the ID of node-agent's own container cgroup, which is +// what the service passes (Service.EnableNRIStartGate): a previous run +// writes a mark only on a cgroup that exists while it runs, and it stopped +// before this container's cgroup was created (the kubelet starts a +// restarted container only after the old one exited, and a DaemonSet +// update with maxSurge 0 creates the new pod only after the old one is +// gone). A cgroup v2 ID is the kernfs node ID, allocated in increasing +// order and never reused (on 64-bit), so every cgroup such a run could +// mark has a lower ID. A watermark that is too high only refuses more; one +// that is too low (a process moved into an older cgroup, or two +// node-agents on one node) would let a marked cgroup through, so the +// service passes the ID of the cgroup it reads node-agent's own process +// in, and nothing when it cannot read it or reads the root cgroup. +// +// Assumption (rev-b LOW-2): one node-agent per node, never two at once: +// the DaemonSet updates with maxSurge 0 (the old pod is gone before the +// new one is created). Restart survival assumes the same. With an overlap, +// the old run could mark a cgroup created after this run's watermark. +func (s *SectionBackend) SetCgroupWatermark(id uint64) { + s.watermark.Store(id) +} + // AdoptedPending asks every section whose backend reads them back // (AdoptedPendingReader): true when any has a Strict one on cgroupID; any // error is an error (fail-closed). An unavailable section whose previous -// runs' pinned sets were kept (ErrPinnedSetsKept) cannot tell: an error -// (Copilot #1176 4810415632). +// runs' pinned sets were kept (ErrPinnedSetsKept), or whose restart +// survival could not read them (an AdoptedPending error wrapping it), +// cannot tell: an error (Copilot #1176 4810415561, 4810415632), except for +// a cgroup above the watermark (SetCgroupWatermark), which no previous run +// can have marked: clear. Cgroup 0 (unresolved) and every cgroup at or +// below the watermark keep the error. func (s *SectionBackend) AdoptedPending(cgroupID uint64, deadline time.Time) (bool, error) { + w := s.watermark.Load() + newer := w != 0 && cgroupID > w var errs []error strict := false for _, sec := range s.sections { if sec.backend == nil && errors.Is(sec.unavailable, ErrPinnedSetsKept) { - errs = append(errs, fmt.Errorf("%s: %w", sec.name, sec.unavailable)) + if !newer { + errs = append(errs, fmt.Errorf("%s: %w", sec.name, sec.unavailable)) + } continue } r, ok := sec.backend.(AdoptedPendingReader) @@ -465,7 +526,7 @@ func (s *SectionBackend) AdoptedPending(cgroupID uint64, deadline time.Time) (bo continue } found, err := r.AdoptedPending(cgroupID, deadline) - if err != nil { + if err != nil && !(newer && errors.Is(err, ErrPinnedSetsKept)) { errs = append(errs, fmt.Errorf("%s: %w", sec.name, err)) } strict = strict || found diff --git a/pkg/sandboxpolicy/startgate/fu2_reprove_test.go b/pkg/sandboxpolicy/startgate/fu2_reprove_test.go new file mode 100644 index 0000000000..412b35aab4 --- /dev/null +++ b/pkg/sandboxpolicy/startgate/fu2_reprove_test.go @@ -0,0 +1,89 @@ +package startgate + +import ( + "slices" + "strings" + "testing" + "time" + + "github.com/containerd/nri/pkg/api" + "github.com/kubescape/node-agent/pkg/sandboxpolicy" +) + +// TestFU2ReproveAfterTheLastHeldSandbox (rev-a MEDIUM on #1176 +// 4802130614): Synchronize does not prove a cgroup that a dead sandbox +// shares with a proven live one. When the last sandbox that held the proof +// back is removed, the gate is asked to prove the cgroup again, for that +// Synchronize's epoch and with the pod's identity; removing a proven +// sandbox, or a held one that is not the last on its cgroup, asks nothing. +// The fake resolves "sb..." to cgroup N. +func TestFU2ReproveAfterTheLastHeldSandbox(t *testing.T) { + g := &classifyByID{fakeGate: fakeGate{dead: map[string]bool{"sb7-dead": true, "sb9-a": true, "sb9-b": true}}, + byID: map[string]sandboxpolicy.PodClassification{"sb7": unselected, "sb8": unselected}} + p := syncPlugin(t, g, 2*time.Second) + p.epoch.Store(3) + pods := []*api.PodSandbox{testPod("sb7"), testPod("sb7-dead"), testPod("sb8"), testPod("sb9-a"), testPod("sb9-b")} + if _, err := p.Synchronize(t.Context(), pods, nil); err != nil { + t.Fatal(err) + } + if !slices.Equal(g.synced, []string{"3:[8]"}) { + t.Fatalf("synced %v, want 3:[8] (7 and 9 held by dead sandboxes)", g.synced) + } + remove := func(id string) { + t.Helper() + if err := p.RemovePodSandbox(t.Context(), testPod(id)); err != nil { + t.Fatal(err) + } + } + remove("sb8") + remove("sb9-a") + if n := g.count("Reprove"); n != 0 { + t.Fatalf("a proven sandbox, or a held one that is not the last, asked for a proof: %v", g.calls) + } + remove("sb7-dead") + if g.count("Reprove 3 sb7-dead 7 pod-uid") != 1 || g.count("Reprove") != 1 { + t.Fatalf("the last held sandbox of cgroup 7: calls %v", g.calls) + } + remove("sb7") + remove("sb9-b") + if g.count("Reprove 3 sb9-b 9 pod-uid") != 1 || g.count("Reprove") != 2 { + t.Fatalf("the last held sandbox of cgroup 9: calls %v", g.calls) + } + // Removed again (a retried RemovePodSandbox): nothing more. + remove("sb9-b") + if g.count("Reprove") != 2 { + t.Fatalf("a repeated removal asked again: %v", g.calls) + } + // The next completed Synchronize replaces the held sandboxes. + p.epoch.Store(4) + if _, err := p.Synchronize(t.Context(), []*api.PodSandbox{testPod("sb7"), testPod("sb7-dead")}, nil); err != nil { + t.Fatal(err) + } + remove("sb7-dead") + if g.count("Reprove 4 sb7-dead 7 pod-uid") != 1 { + t.Fatalf("after the next Synchronize: calls %v", g.calls) + } +} + +// TestFU2StrictSectionlessRefusalKeepsTheMark (rev-b LOW-3): a Strict pod +// with no section a pod mark holds is refused at RunPodSandbox and +// CreateContainer (D1) and the handler leaves its mark. The refresh decides +// it on both of its paths with one rule (owner batch 18 read fail-closed): +// the exec-only one is unmarked, the sources one keeps its mark +// (TestFU2UnmarkPathsAgree in the integration package). +func TestFU2StrictSectionlessRefusalKeepsTheMark(t *testing.T) { + for _, c := range []sandboxpolicy.PodClassification{withShape(sel(true), sandboxpolicy.ShapeSources), noSections(sel(true))} { + g := &fakeGate{classes: []sandboxpolicy.PodClassification{c}, holdsMark: true, heldStrict: true} + var alerts []Alert + p := configured(t, g, &alerts) + if err := p.RunPodSandbox(t.Context(), testPod("sb1")); err == nil || !strings.Contains(err.Error(), "D1") { + t.Fatalf("RunPodSandbox: %v, want a D1 refusal", err) + } + if _, _, err := p.CreateContainer(t.Context(), testPod("sb1"), testContainer("app")); err == nil || !strings.Contains(err.Error(), "D1") { + t.Fatalf("CreateContainer: %v, want a D1 refusal", err) + } + if n := g.count("Unmark"); n != 0 { + t.Fatalf("a refusing handler unmarked the pod: %v", g.calls) + } + } +} diff --git a/pkg/sandboxpolicy/startgate/plugin.go b/pkg/sandboxpolicy/startgate/plugin.go index 4d30242305..6ded1dc8bf 100644 --- a/pkg/sandboxpolicy/startgate/plugin.go +++ b/pkg/sandboxpolicy/startgate/plugin.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "maps" "net" "path" "slices" @@ -131,6 +132,15 @@ type Gate interface { // no live joined sandbox left, whatever the error. ReleaseSandbox(ctx context.Context, sb Sandbox, deadline time.Time) (last bool, err error) SetNRISynced(epoch uint64, proven map[uint64]bool) + // ReproveCgroup asks for the cgroup of sb (its CgroupID) to be proven + // for the Synchronize on epoch, as that Synchronize would have proved + // it, once the sandboxes that held its proof back are all removed + // (rev-a MEDIUM on #1176 4802130614: otherwise a previous run's Strict + // pending mark on it is never retired). The proof comes only from a + // later classification of the pod that needs no Strict pending mark, + // at or after that Synchronize's sequence (owner batch 12); until + // then nothing changes. It takes no I/O and does not wait. + ReproveCgroup(epoch uint64, sb Sandbox) // ClassificationSeq is the classification sequence now (the // snapshot's configSeq and the input epoch, the space every mark and // bind carries); a classification that starts after it is at or after @@ -188,8 +198,10 @@ const ( // StateFaulted: the last decision refused the pod (a mark or a // confirmation failed, or an unsupported Strict shape). StateFaulted PodState = "Faulted" - // StateNotStartGated: a Selected Audit pod with no section a pod mark - // can hold (sources, exec only, or different sets per container). + // StateNotStartGated: a Selected pod that is not Strict for the gate + // (Audit policies, or an enforce policy whose only section is http: + // owner batch 7 F2) with no section a pod mark can hold (sources, exec + // or http only, or different sets per container). StateNotStartGated PodState = "NotStartGated" // StateAuditDegraded: an Audit section admitted on its pending mark // (owner decision D9(a)): the accounting is degraded until it binds. @@ -233,6 +245,15 @@ type Plugin struct { // registered: a Synchronize completed on the current connection (the // runtime registered the plugin); Run then resets its backoff. registered atomic.Bool + + // held are the sandboxes the last completed Synchronize (on heldEpoch) + // did not prove, by sandbox ID, with their pod cgroup: they held their + // cgroup's proof back. RemovePodSandbox drops one; when the last on a + // cgroup goes, the gate is asked to prove the cgroup again + // (Gate.ReproveCgroup). The next completed Synchronize replaces them. + heldMu sync.Mutex + held map[string]uint64 + heldEpoch uint64 } // NewPlugin returns the plugin, or ErrNotBuildable while the build constant @@ -388,7 +409,9 @@ func podName(pod *api.PodSandbox) string { type sandboxOutcome struct { err error // cgroup is the sandbox's resolved pod cgroup (0: not resolved); - // proven: the pod is Unselected and the gate holds no mark for it. + // proven: the pod is Unselected, or Selected, not Strict and with no + // section a pod mark holds, and the gate holds no mark for it (its + // unmark succeeded). cgroup uint64 proven bool } @@ -422,6 +445,14 @@ func stale(results []sandboxpolicy.PodSectionResult, err error) bool { // does not make a pod Strict (sandboxpolicy classification, batch 7 F2), so // such a pod starts as NotStartGated; next to another section, only that // section is gated, and StartGatePods says nothing about http. +// +// The handlers that refuse on it (reportSandbox, admitContainer) leave the +// pod's mark as it is: the handler decides only the sandbox or container it +// was asked about, and it fails closed. The refresh decides the mark with +// one rule on both of its paths (integration noPodSections; owner batch 18 +// read fail-closed): a Strict pod with no section and no shape (exec +// policies only) is unmarked through the shared backoff; one with a shape +// keeps its mark, which still judges its tasks. func strictRefusal(c sandboxpolicy.PodClassification) error { if !c.Strict { return nil @@ -660,8 +691,9 @@ func (p *Plugin) reportSandbox(ctx context.Context, pod *api.PodSandbox, deadlin return out } if len(c.Sections) == 0 { - // Audit only (a Strict one was refused above): nothing a pod - // mark holds; Audit never blocks. An older mark (a Strict one) + // Not Strict for the gate (Audit, or an enforce policy whose + // only section is http: batch 7 F2; a Strict one was refused + // above): nothing a pod mark holds, and it never blocks. An older mark (a Strict one) // goes first, as for an Unselected pod: the pod is never // admitted as not start-gated while it still denies (D9(a); // Copilot #1176 4792357641). @@ -715,9 +747,10 @@ func (p *Plugin) reportSandbox(ctx context.Context, pod *api.PodSandbox, deadlin // sandbox was classified and every Selected one marked (owner decision // D10(a): one Unknown or unmarkable pod fails it, so the plugin does not // register and the node refuses creates until it is fixed). Only then does -// it record the epoch as synced, with proven: the cgroups of Unselected -// pods the gate holds no mark for (never one a Selected or Unknown sandbox -// also names). +// it record the epoch as synced, with proven: the cgroups of the pods that +// are Unselected, or Selected with no section a pod mark holds and not +// Strict, that the gate holds no mark for (never one another sandbox that +// is not proven also names: a Selected, Unknown or dead one). func (p *Plugin) Synchronize(ctx context.Context, pods []*api.PodSandbox, containers []*api.Container) ([]*api.ContainerUpdate, error) { err := p.synchronize(ctx, p.epoch.Load(), pods, containers) if err == nil { @@ -763,8 +796,9 @@ func (p *Plugin) synchronize(ctx context.Context, epoch uint64, pods []*api.PodS wg.Wait() proven := map[uint64]bool{} held := map[uint64]bool{} + heldBy := map[string]uint64{} var errs []error - for _, o := range outcomes { + for i, o := range outcomes { if o.err != nil { errs = append(errs, o.err) } @@ -775,6 +809,7 @@ func (p *Plugin) synchronize(ctx context.Context, epoch uint64, pods []*api.PodS proven[o.cgroup] = true } else { held[o.cgroup] = true + heldBy[pods[i].GetId()] = o.cgroup } } if len(errs) > 0 { @@ -786,6 +821,9 @@ func (p *Plugin) synchronize(ctx context.Context, epoch uint64, pods []*api.PodS for id := range held { delete(proven, id) } + p.heldMu.Lock() + p.held, p.heldEpoch = heldBy, epoch + p.heldMu.Unlock() p.gate.SetNRISynced(epoch, proven) // With no classification snapshot yet (Config 0: configSeq counts from // the first snapshot) the bound proves nothing: no sequence, so no @@ -846,6 +884,7 @@ func (p *Plugin) RemovePodSandbox(ctx context.Context, pod *api.PodSandbox) erro } sb, _ := p.gate.Sandbox(pod) last, err := p.gate.ReleaseSandbox(ctx, sb, deadline) + p.reproveAfter(sb) // The pod's status goes with its last sandbox, whatever the release // answers (F7): S2 retries a failed unbind on its own. A surviving // sandbox keeps it (CodeRabbit #1176 4810415652). @@ -861,6 +900,26 @@ func (p *Plugin) RemovePodSandbox(ctx context.Context, pod *api.PodSandbox) erro return nil } +// reproveAfter drops a removed sandbox from the ones the last Synchronize +// held (Plugin.held), and asks the gate to prove its cgroup again when it +// was the last of them on that cgroup (Gate.ReproveCgroup). The sandbox is +// tombstoned, whatever its release answered: it runs nothing. Any other +// sandbox of the cgroup was proven, or joined after Synchronize (its own +// mark is this run's). +func (p *Plugin) reproveAfter(sb Sandbox) { + p.heldMu.Lock() + cgroup, ok := p.held[sb.ID] + delete(p.held, sb.ID) + last := ok && !slices.Contains(slices.Collect(maps.Values(p.held)), cgroup) + epoch := p.heldEpoch + p.heldMu.Unlock() + if !last { + return + } + sb.CgroupID, sb.CgroupPath = cgroup, "" + p.gate.ReproveCgroup(epoch, sb) +} + // ContainerInPodCgroup reports whether the container would not get a cgroup // of its own under the pod cgroup (the D1 shape "container in the pod // cgroup"). A path the gate cannot place under the pod cgroup counts as in diff --git a/pkg/sandboxpolicy/startgate/plugin_test.go b/pkg/sandboxpolicy/startgate/plugin_test.go index 8973446e36..80e0cd93d3 100644 --- a/pkg/sandboxpolicy/startgate/plugin_test.go +++ b/pkg/sandboxpolicy/startgate/plugin_test.go @@ -179,6 +179,11 @@ func (g *fakeGate) SetNRISynced(epoch uint64, proven map[uint64]bool) { g.synced = append(g.synced, fmt.Sprintf("%d:%v", epoch, ids)) } +// ReproveCgroup records the call. +func (g *fakeGate) ReproveCgroup(epoch uint64, sb Sandbox) { + g.record("Reprove %d %s %d %s", epoch, sb.ID, sb.CgroupID, sb.UID) +} + // ClassificationSeq answers syncSeq and records the call, in order. func (g *fakeGate) ClassificationSeq(context.Context) sandboxpolicy.Seq { g.record("ClassificationSeq") diff --git a/pkg/sandboxpolicy/types.go b/pkg/sandboxpolicy/types.go index eaa05e6228..3a42e76a3c 100644 --- a/pkg/sandboxpolicy/types.go +++ b/pkg/sandboxpolicy/types.go @@ -284,6 +284,14 @@ var ErrStaleSequence = errors.New("stale sequence: a newer classification wrote // a failed bind, another plan, a looser class) is an ordinary error. var ErrPolicyEntry = errors.New("the pod cgroup holds an entry on a policy slot; a pending mark never replaces it") +// ErrInheritedStrictMark is the ErrPolicyEntry case of a previous run's +// Strict pending mark that an Audit write would lower while no proof retires +// it (errors.Is matches both). Unlike an adopted policy-slot entry, it goes +// once a proof comes (Synchronize, or this run's classification at or after +// it), so a caller that memoizes a definitive outcome must retry it +// (CodeRabbit #1176 4810415619). +var ErrInheritedStrictMark = fmt.Errorf("an inherited Strict pending mark stays until a proof retires it: %w", ErrPolicyEntry) + // PodSectionState is how far one section protects a pod (PodGate.ConfirmPod). type PodSectionState int From 5359922fd3fd4d050e23b0bd6090346da643f661 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Sat, 5 Dec 2026 16:25:44 +0100 Subject: [PATCH 2/5] fix(nri): close the pod gate and Service follow-ups Follow-ups from the reviews of #1165 and the re-merge review, all fail-closed. - One cgroup walk serves all of a refresh's pathless gone checks; only a successful walk is reused (at most 0.5 s), a failed walk decides nothing and is not cached. - One uncached mirror re-read per refresh covers every static unmark. - MarkPod clears refusedPlan only at a strictly newer sequence with the wanted plan, so status never claims protection it did not hold. - sandboxpolicy.StaticPod and ConfigSourceAnnotation are the single static-pod rule (ClassifyPod, the Service and toGate). - Service.Close closes the gate before the fence join; gate.close returns nil once no worker is left. - TestServiceReportsUnexpectedExporterExit no longer hangs (its own OnError blocked on a 1-slot channel) and runs in the normal suite. - Tests: the merge/bind window (deterministic), fence-aware Close retries, static pod -> mirror -> unmark end to end, an http-only policy through classification and the plugin; session-local references removed from test comments. Co-Authored-By: Claude Opus 5.5 Docs-exempt: internal fixes and tests in the unreleased NRI start gate stack Signed-off-by: Matthias Bertschy --- pkg/sandboxpolicy/classify.go | 15 +- pkg/sandboxpolicy/classify_test.go | 6 +- pkg/sandboxpolicy/igbackend/nodeowner.go | 35 +++- .../igbackend/statusrefused_s3_test.go | 50 ++++++ .../integration/cgroupgone_linux.go | 93 +++++++--- .../integration/cgroupgone_linux_test.go | 106 +++++++++-- .../integration/gateoff_golden_test.go | 3 +- pkg/sandboxpolicy/integration/nrigate.go | 11 +- .../integration/nrigate_fu2b_vmtest_test.go | 125 +++++++++++++ .../integration/nrigate_static_test.go | 9 +- pkg/sandboxpolicy/integration/podgate.go | 16 +- .../integration/podgate_finishedjob_test.go | 3 +- .../podgate_fu2b_close_linux_test.go | 83 +++++++++ .../integration/podgate_fu2b_test.go | 164 ++++++++++++++++++ pkg/sandboxpolicy/integration/service.go | 50 ++++-- pkg/sandboxpolicy/integration/service_test.go | 28 ++- 16 files changed, 711 insertions(+), 86 deletions(-) create mode 100644 pkg/sandboxpolicy/integration/nrigate_fu2b_vmtest_test.go create mode 100644 pkg/sandboxpolicy/integration/podgate_fu2b_close_linux_test.go create mode 100644 pkg/sandboxpolicy/integration/podgate_fu2b_test.go diff --git a/pkg/sandboxpolicy/classify.go b/pkg/sandboxpolicy/classify.go index 3d3bf1a26e..4fc8f6d3a4 100644 --- a/pkg/sandboxpolicy/classify.go +++ b/pkg/sandboxpolicy/classify.go @@ -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 @@ -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 != "" diff --git a/pkg/sandboxpolicy/classify_test.go b/pkg/sandboxpolicy/classify_test.go index 3a834853b9..309ae3e89c 100644 --- a/pkg/sandboxpolicy/classify_test.go +++ b/pkg/sandboxpolicy/classify_test.go @@ -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"}} } @@ -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 { @@ -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 { diff --git a/pkg/sandboxpolicy/igbackend/nodeowner.go b/pkg/sandboxpolicy/igbackend/nodeowner.go index 1b50ba9826..64a1910a3f 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner.go @@ -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). @@ -308,6 +312,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 @@ -1433,7 +1459,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++ @@ -1445,7 +1471,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 @@ -1726,7 +1752,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))...) @@ -1924,6 +1950,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 { @@ -1935,6 +1962,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)) { @@ -1944,6 +1972,7 @@ func (b *nodeOwner[C]) MarkPod(_ context.Context, pod sandboxpolicy.PodBinding, return err } current.advance(&seq) + current.clearRefusedPlan(seq) return nil } diff --git a/pkg/sandboxpolicy/igbackend/statusrefused_s3_test.go b/pkg/sandboxpolicy/igbackend/statusrefused_s3_test.go index 23b40bc160..37157bbd6e 100644 --- a/pkg/sandboxpolicy/igbackend/statusrefused_s3_test.go +++ b/pkg/sandboxpolicy/igbackend/statusrefused_s3_test.go @@ -81,3 +81,53 @@ func TestUnappliedPlanIsNotConfirmed(t *testing.T) { t.Fatalf("A asked again: confirmed %d faulted %d", len(confirmed), len(faulted)) } } + +// S3 follow-up (coderabbit-1165-r2-review-s3.md LOW): a MarkPod that leaves +// the record holding its plan, at a sequence newer than the refused +// listing's, clears the fault at once instead of at the next listing. A +// mark at the refused listing's own sequence does not: it may carry the +// input that listing refused (owner batch 16). +func TestMarkPodClearsRefusedPlan(t *testing.T) { + ctx := context.Background() + for name, tc := range map[string]struct { + bind bool // the record is bound to its slot (else a pending mark) + }{ + "bound": {bind: true}, + "pending": {}, + } { + t.Run(name, func(t *testing.T) { + b, _ := newGate(t) + if err := b.Prepare(ctx, []sandboxpolicy.Plan{strictPlan, strictPlan2}); err != nil { + t.Fatal(err) + } + mustMark(t, b, strictPlan, seq(5, 5)) + if tc.bind { + if err := b.EnsurePodBound(ctx, "u"); err != nil { + t.Fatal(err) + } + } + if err := b.BindPodsAt(ctx, []sandboxpolicy.PodBinding{gatePod(strictPlan2)}, seq(5, 5)); !errors.Is(err, sandboxpolicy.ErrStaleSequence) { + t.Fatalf("setup: another set at an equal sequence must be refused: %v", err) + } + if _, faulted := b.BoundPodPlans(); len(faulted) != 1 { + t.Fatalf("setup: the refusal must fault the pod: %d", len(faulted)) + } + mustMark(t, b, strictPlan, seq(5, 5)) + if _, faulted := b.BoundPodPlans(); len(faulted) != 1 { + t.Fatal("a mark at the refused listing's own sequence cleared the fault") + } + mustMark(t, b, strictPlan, seq(6, 6)) + if b.pods["u"].refusedPlan { + t.Fatal("a newer mark applied the record's plan; the fault stays until the next listing") + } + // A pending mark is faulted anyway ("pending mark"). + wantConfirmed, wantFaulted := 0, 1 + if tc.bind { + wantConfirmed, wantFaulted = 1, 0 + } + if confirmed, faulted := b.BoundPodPlans(); len(confirmed) != wantConfirmed || len(faulted) != wantFaulted { + t.Fatalf("after the newer mark: confirmed %d faulted %d", len(confirmed), len(faulted)) + } + }) + } +} diff --git a/pkg/sandboxpolicy/integration/cgroupgone_linux.go b/pkg/sandboxpolicy/integration/cgroupgone_linux.go index 0767ef4212..bbbf97695d 100644 --- a/pkg/sandboxpolicy/integration/cgroupgone_linux.go +++ b/pkg/sandboxpolicy/integration/cgroupgone_linux.go @@ -39,10 +39,10 @@ type handleSyscalls struct { // pathID is cgroupID: the cgroup ID (inode) of the cgroup v2 directory // rel under root, for the live veto. pathID func(root, rel string) (uint64, error) - // findID is findCgroupID: the path (relative to root) of the cgroup v2 - // directory whose ID is id, searched over the whole hierarchy; for an - // ID with no noted path, before it is called gone. nil: no search. - findID func(root string, id uint64) (rel string, found bool, err error) + // walkIDs is walkCgroupIDs: the path (relative to root) of every cgroup + // v2 directory of the hierarchy, by ID; for the IDs with no noted path, + // before one is called gone. nil: no search. + walkIDs func(root string) (map[uint64]string, error) // now is the clock of the two-check rule. now func() time.Time } @@ -73,10 +73,10 @@ var linuxHandleSyscalls = handleSyscalls{ c := uint(unix.CAP_DAC_READ_SEARCH) return data[c/32].Effective&(1<<(c%32)) != 0, nil }, - close: unix.Close, - pathID: cgroupID, - findID: findCgroupID, - now: time.Now, + close: unix.Close, + pathID: cgroupID, + walkIDs: walkCgroupIDs, + now: time.Now, } // goneConfirmAfter is the least time between the two ESTALE answers that @@ -125,6 +125,45 @@ type cgroupGoneChecker struct { // failures counts the checks that could not decide (logged on the // first one only, so a missing capability does not flood the log). failures atomic.Uint64 + // walk is the last search of the hierarchy (walkIDs) for the pathless + // verdicts: the gate refresh checks every ID in one pass, so one walk + // serves all of its pathless IDs. Guarded by probe. + walk cgroupWalk +} + +// cgroupWalk is one successful search of the cgroup v2 hierarchy: when it +// started, and the directories it found by ID (nil: none kept). +type cgroupWalk struct { + at time.Time + ids map[uint64]string +} + +// walkReuse is how long a search of the hierarchy serves other pathless +// verdicts: less than goneConfirmAfter, so a reused search always started +// after the first ESTALE answer of the ID it decides (that answer is at +// least goneConfirmAfter before the verdict); the ID existed before then, +// so a directory with it that was live at the search was found. It is much +// shorter than the refresh period (5 s). Only a successful search is +// reused. +const walkReuse = goneConfirmAfter / 2 + +// findPathless is the search of a pathless verdict (walkIDs): the +// directory with id, from a successful search that started within +// walkReuse, or a new one. A failed search is never kept: it decides +// nothing, and the next pathless verdict searches again (rev-a LOW 2). +// Runs under probe, outside mu. +func (c *cgroupGoneChecker) findPathless(id uint64) (string, bool, error) { + now := c.sys.now() + if c.walk.ids == nil || now.Sub(c.walk.at) >= walkReuse || now.Before(c.walk.at) { + ids, err := c.sys.walkIDs(c.root) + if err != nil { + c.walk = cgroupWalk{} + return "", false, err + } + c.walk = cgroupWalk{at: now, ids: ids} + } + rel, found := c.walk.ids[id] + return rel, found, nil } // newCgroupGoneChecker opens the cgroup v2 root at root (the host's @@ -233,13 +272,13 @@ func (c *cgroupGoneChecker) forgetPaths(old map[uint64]notedPath, now time.Time) } } -// findCgroupID searches the cgroup v2 hierarchy under root for the -// directory whose inode (the cgroup ID) is id, and returns its path -// relative to root ("/" prefixed). A descendant removed during the walk is -// skipped; a root that cannot be searched (missing, not a directory) and -// any other error stop it (undecided: CodeRabbit #1165 4806793317). -func findCgroupID(root string, id uint64) (string, bool, error) { - var rel string +// walkCgroupIDs searches the cgroup v2 hierarchy under root and returns the +// path relative to root ("/" prefixed) of every directory, by inode (the +// cgroup ID). A descendant removed during the walk is skipped; a root that +// cannot be searched (missing, not a directory) and any other error stop it +// (undecided: CodeRabbit #1165 4806793317). +func walkCgroupIDs(root string) (map[uint64]string, error) { + ids := map[uint64]string{} err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil { if errors.Is(err, fs.ErrNotExist) && path != root { @@ -264,20 +303,20 @@ func findCgroupID(root string, id uint64) (string, bool, error) { if !ok { return fmt.Errorf("%s: no inode", path) } - if st.Ino == id { - r, err := filepath.Rel(root, path) - if err != nil { - return err - } - rel = "/" + r - return fs.SkipAll + r, err := filepath.Rel(root, path) + if err != nil { + return err + } + if r == "." { + r = "" } + ids[st.Ino] = "/" + r return nil }) if err != nil { - return "", false, err + return nil, err } - return rel, rel != "", nil + return ids, nil } // selfTest proves the check can answer on this node before the gate uses it @@ -414,15 +453,17 @@ func (c *cgroupGoneChecker) gone(id uint64) bool { if cur, ok := c.paths[id]; ok != hadPath || cur != checked { return false } - if !hadPath && c.sys.findID != nil { + if !hadPath && c.sys.walkIDs != nil { // No path ever named this ID (an adopted mark no join or bind // noted): the ESTALE answers are the only evidence, and // allocation pressure can repeat them for a live cgroup // (Copilot #1165 4799124503). Independent evidence: no // directory of the hierarchy has this ID. A search that cannot // finish decides nothing; a directory found is noted (its veto). + // One search serves every pathless verdict of a refresh + // (findPathless). c.mu.Unlock() - rel, found, err := c.sys.findID(c.root, id) + rel, found, err := c.findPathless(id) c.mu.Lock() if err != nil || found { if found { diff --git a/pkg/sandboxpolicy/integration/cgroupgone_linux_test.go b/pkg/sandboxpolicy/integration/cgroupgone_linux_test.go index 8ed55147ab..3c4f0d4830 100644 --- a/pkg/sandboxpolicy/integration/cgroupgone_linux_test.go +++ b/pkg/sandboxpolicy/integration/cgroupgone_linux_test.go @@ -679,11 +679,14 @@ func TestCgroupGonePathlessNeedsAbsence(t *testing.T) { openByHandle: func(int, unix.FileHandle, int) (int, error) { return -1, unix.ESTALE }, close: func(int) error { return nil }, pathID: func(string, string) (uint64, error) { return 0, unix.ENOENT }, - findID: func(root string, id uint64) (string, bool, error) { - if root != "/cg" || id != 7 { - t.Fatalf("findID(%q, %d)", root, id) + walkIDs: func(root string) (map[uint64]string, error) { + if root != "/cg" { + t.Fatalf("walkIDs(%q)", root) } - return tc.rel, tc.found, tc.err + if tc.found { + return map[uint64]string{1: "/", 7: tc.rel}, tc.err + } + return map[uint64]string{1: "/"}, tc.err }, now: func() time.Time { return clock }, } @@ -706,8 +709,8 @@ func TestCgroupGonePathlessNeedsAbsence(t *testing.T) { } } -// findCgroupID finds a directory by its inode under root. -func TestFindCgroupID(t *testing.T) { +// walkCgroupIDs finds every directory by its inode under root. +func TestWalkCgroupIDs(t *testing.T) { root := t.TempDir() dir := filepath.Join(root, "kubepods", "pod-a") if err := os.MkdirAll(dir, 0o755); err != nil { @@ -717,18 +720,18 @@ func TestFindCgroupID(t *testing.T) { if err := unix.Stat(dir, &st); err != nil { t.Fatal(err) } - rel, found, err := findCgroupID(root, st.Ino) - if err != nil || !found || rel != "/kubepods/pod-a" { - t.Fatalf("findCgroupID: %q %v %v", rel, found, err) + ids, err := walkCgroupIDs(root) + if err != nil || ids[st.Ino] != "/kubepods/pod-a" || len(ids) != 3 { + t.Fatalf("walkCgroupIDs: %v %v", ids, err) } - if _, found, err := findCgroupID(root, st.Ino+1000000); err != nil || found { - t.Fatalf("an absent ID: %v %v", found, err) + if _, found := ids[st.Ino+1000000]; found { + t.Fatal("an absent ID was found") } } // CodeRabbit #1165 4806793317: a root that cannot be searched decides // nothing (an error, never "absent"); a descendant that vanishes is skipped. -func TestFindCgroupIDRootUnsearchable(t *testing.T) { +func TestWalkCgroupIDsRootUnsearchable(t *testing.T) { dir := t.TempDir() file := filepath.Join(dir, "file") if err := os.WriteFile(file, nil, 0o644); err != nil { @@ -739,12 +742,83 @@ func TestFindCgroupIDRootUnsearchable(t *testing.T) { t.Fatal(err) } for name, root := range map[string]string{"missing": filepath.Join(dir, "missing"), "a file": file, "a symlink": link} { - if _, found, err := findCgroupID(root, 12345); err == nil || found { - t.Errorf("%s root: found %v, err %v; want an error", name, found, err) + if ids, err := walkCgroupIDs(root); err == nil || ids != nil { + t.Errorf("%s root: ids %v, err %v; want an error", name, ids, err) } } } +// S3 follow-up (copilot-1165-missed-review-s3.md LOW): the pathless +// verdicts of one refresh share one successful search of the hierarchy; a +// search older than walkReuse is not reused. A failed search decides +// nothing and is never reused (rev-a LOW 2): the next check searches again. +func TestCgroupGonePathlessSearchIsBatched(t *testing.T) { + clock := time.Date(2026, 11, 24, 0, 0, 0, 0, time.UTC) + walks := 0 + var walkErr error + present := map[uint64]string{1: "/"} + sys := handleSyscalls{ + openRoot: func(string) (int, error) { return 3, nil }, + fstatfsType: func(int) (int64, error) { return unix.CGROUP2_SUPER_MAGIC, nil }, + openByHandle: func(int, unix.FileHandle, int) (int, error) { return -1, unix.ESTALE }, + close: func(int) error { return nil }, + pathID: func(string, string) (uint64, error) { return 0, unix.ENOENT }, + walkIDs: func(string) (map[uint64]string, error) { + walks++ + if walkErr != nil { + return nil, walkErr + } + return present, nil + }, + now: func() time.Time { return clock }, + } + c, err := newCgroupGoneChecker("/cg", sys) + if err != nil { + t.Fatal(err) + } + ids := []uint64{7, 8, 9, 10} + for _, id := range ids { + c.gone(id) + } + // One refresh whose searches fail: nothing is gone, and each check + // searches again (a failure is not reused). + walkErr = unix.ENOMEM + clock = clock.Add(2 * goneConfirmAfter) + for _, id := range ids[:2] { + if c.gone(id) { + t.Fatalf("gone(%d) from a search that failed", id) + } + } + if walks != 2 { + t.Fatalf("two checks after a failed search walked %d times, want 2 (a failure must not be reused)", walks) + } + // The search works again at the same instant: the next check searches + // (no failure kept), and its result serves the rest of the refresh. + walkErr = nil + present[9] = "/kubepods/nine" + for _, id := range ids { + if got, want := c.gone(id), id != 9; got != want { + t.Fatalf("gone(%d) = %v, want %v", id, got, want) + } + } + if walks != 3 { + t.Fatalf("one refresh's pathless verdicts walked %d times in all, want 3 (one successful search shared)", walks) + } + c.mu.Lock() + noted := c.paths[9].path + c.mu.Unlock() + if noted != "/kubepods/nine" { + t.Fatalf("the found directory was not noted: %q", noted) + } + // A successful search older than walkReuse is not reused. + clock = clock.Add(walkReuse) + c.gone(11) + clock = clock.Add(2 * goneConfirmAfter) + if !c.gone(11) || walks != 4 { + t.Fatalf("a search older than walkReuse: walks %d, want 4", walks) + } +} + // CodeRabbit #1165 4806793333: a path noted while the search runs is kept; // the search's own result does not overwrite it. func TestCgroupGoneSearchKeepsANotedPath(t *testing.T) { @@ -756,9 +830,9 @@ func TestCgroupGoneSearchKeepsANotedPath(t *testing.T) { openByHandle: func(int, unix.FileHandle, int) (int, error) { return -1, unix.ESTALE }, close: func(int) error { return nil }, pathID: func(string, string) (uint64, error) { return 0, unix.ENOENT }, - findID: func(string, uint64) (string, bool, error) { + walkIDs: func(string) (map[uint64]string, error) { c.notePath(7, "/noted") // a join notes the cgroup during the search - return "/scanned", true, nil + return map[uint64]string{7: "/scanned"}, nil }, now: func() time.Time { return clock }, } diff --git a/pkg/sandboxpolicy/integration/gateoff_golden_test.go b/pkg/sandboxpolicy/integration/gateoff_golden_test.go index 5d61033254..0d075d2b31 100644 --- a/pkg/sandboxpolicy/integration/gateoff_golden_test.go +++ b/pkg/sandboxpolicy/integration/gateoff_golden_test.go @@ -163,8 +163,7 @@ func gateOffScenario(t *testing.T) []string { } // gateOffGolden is gateOffScenario's log at HEAD 98c0a432 (before S3), -// recorded by running this file in a scratch copy of that commit -// (n2-evidence/s3/gateoff-golden-head.log). +// recorded by running this file in a scratch copy of that commit. const gateOffGolden = `-- bindPods BindPods [pod-uid/ns/pod cgroup=77 path=/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-podpod_uid.slice plan=[policy-uid:enforce:priv=true] started=false] -- bindPods diff --git a/pkg/sandboxpolicy/integration/nrigate.go b/pkg/sandboxpolicy/integration/nrigate.go index a1a520a862..5017a36030 100644 --- a/pkg/sandboxpolicy/integration/nrigate.go +++ b/pkg/sandboxpolicy/integration/nrigate.go @@ -445,13 +445,12 @@ func (n *nriGate) Classify(ctx context.Context, req sandboxpolicy.ClassifyReques return n.s.Controller.ClassifyPod(ctx, req, n.source) } -// toGate converts the plugin's sandbox. Static follows ClassifyPod's rule: the -// payload's kubernetes.io/config.source is set and is not "api". Only a static -// pod's entry may be correlated with a mirror pod (staticPodMirrors), so a -// missing or "api" source never correlates. +// toGate converts the plugin's sandbox. Static is ClassifyPod's rule +// (sandboxpolicy.StaticPod). Only a static pod's entry may be correlated +// with a mirror pod (staticPodMirrors), so a missing or "api" source never +// correlates. func toGate(sb startgate.Sandbox) gateSandbox { - src := sb.Annotations[configSourceAnnotation] - return gateSandbox{UID: sb.UID, Namespace: sb.Namespace, Name: sb.Name, SandboxID: sb.ID, CgroupID: sb.CgroupID, CgroupPath: sb.CgroupPath, Static: src != "" && src != "api"} + return gateSandbox{UID: sb.UID, Namespace: sb.Namespace, Name: sb.Name, SandboxID: sb.ID, CgroupID: sb.CgroupID, CgroupPath: sb.CgroupPath, Static: sandboxpolicy.StaticPod(sb.Annotations)} } // Sandbox resolves the payload's pod cgroup. A joined sandbox keeps the diff --git a/pkg/sandboxpolicy/integration/nrigate_fu2b_vmtest_test.go b/pkg/sandboxpolicy/integration/nrigate_fu2b_vmtest_test.go new file mode 100644 index 0000000000..e8bbf01781 --- /dev/null +++ b/pkg/sandboxpolicy/integration/nrigate_fu2b_vmtest_test.go @@ -0,0 +1,125 @@ +//go:build startgate_vmtest + +package integration + +import ( + "errors" + "strings" + "testing" + + nriapi "github.com/containerd/nri/pkg/api" + "github.com/kubescape/node-agent/pkg/sandboxpolicy" + "github.com/kubescape/node-agent/pkg/sandboxpolicy/startgate" + "k8s.io/client-go/informers" + kubefake "k8s.io/client-go/kubernetes/fake" +) + +// readyPlugin is a configured plugin over n. +func readyPlugin(t *testing.T, n *nriGate) *startgate.Plugin { + t.Helper() + p, err := startgate.NewPlugin(n, startgate.Options{}) + if err != nil { + t.Fatal(err) + } + if _, err := p.Configure(t.Context(), "", "containerd", "v2.3.7"); err != nil { + t.Fatal(err) + } + return p +} + +// S5 follow-up (s5-static-review.md): a static pod end to end. The plugin's +// RunPodSandbox joins it with its NRI payload (kubernetes.io/config.source: +// file, under its kubelet UID), classified through its mirror pod. Its last +// policy goes; a refresh lists the mirror pod (another UID, whose +// kubernetes.io/config.mirror names the kubelet UID) as Unselected, and the +// gate's mark is removed through that mirror (unmarkDeselected). The +// service's own NRI reclassification is left out (s.nriGate unset), so only +// the mirror correlation can unmark it. +func TestStaticPodNRIJoinUnmarkedThroughMirror(t *testing.T) { + b := newFakeGateBackend() + s, client := gateTestServiceClient(t, b) + backend := &nriTestBackend{fakeGateBackend: b} + s.backend = backend + if err := s.options.Kubernetes.(*kubefake.Clientset).Tracker().Add(mirrorPod("ns", "static-node", "mirror-uid")); err != nil { + t.Fatal(err) + } + s.pods = informers.NewSharedInformerFactory(s.options.Kubernetes, 0) + s.namespaces = s.pods + s.inputEpoch.Store(1) + n := readyNRIGate(t, s, backend) + const staticPath = "/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-podstatic_uid.slice" + n.resolve = func(pod podSandbox) (string, uint64, error) { + if pod.UID != "static-uid" || pod.PausePID != 42 { + return "", 0, errors.New("pause process: no PID") + } + return staticPath, 95, nil + } + p := readyPlugin(t, n) + pod := &nriapi.PodSandbox{Id: "sbs", Uid: "static-uid", Namespace: "ns", Name: "static-node", Pid: 42, + Annotations: map[string]string{sandboxpolicy.ConfigSourceAnnotation: "file"}, Linux: &nriapi.LinuxPodSandbox{CgroupParent: "kubepods-besteffort-podstatic_uid.slice"}} + if err := p.RunPodSandbox(t.Context(), pod); err != nil { + t.Fatalf("RunPodSandbox of the static pod: %v", err) + } + if r := b.rec("static-uid"); r == nil || r.cgroup != 95 || !r.strict { + t.Fatalf("the static pod was not marked Strict on its cgroup: %+v (%v)", r, b.callNames()) + } + g := s.gate.Load() + g.podMu.Lock() + static := g.pods["static-uid"] != nil && g.pods["static-uid"].sandbox.Static + g.podMu.Unlock() + if !static { + t.Fatal("the NRI payload's config.source did not mark the entry static") + } + // A refresh while the policy selects it keeps the mark. + s.inputEpoch.Store(5) + resync(t, s) + if b.rec("static-uid") == nil { + t.Fatalf("a refresh unmarked a selected static pod: %v", b.callNames()) + } + deletePolicy(t, client, "priv") + s.inputEpoch.Store(10) + resync(t, s) + b.mu.Lock() + unmarks := 0 + for _, call := range b.calls { + if strings.HasPrefix(call, "UnmarkPod static-uid ") { + unmarks++ + } + } + b.mu.Unlock() + if r := b.rec("static-uid"); r != nil || unmarks != 1 { + t.Fatalf("the deselected static pod kept its mark: %+v (%v)", r, b.callNames()) + } +} + +// Re-merge review v1 R3: an enforce policy whose only section is http, +// end to end: classified Selected, not Strict, with no section a pod mark +// holds (owner batch 7 F2), and admitted by the plugin as NotStartGated, +// sandbox and container, with no mark written. +func TestHTTPOnlyPolicyThroughPlugin(t *testing.T) { + s, backend := nriTestService(t) + useHTTPOnlyPolicy(t, s, backend.fakeGateBackend) + n := readyNRIGate(t, s, backend) + c := n.Classify(t.Context(), sandboxpolicy.ClassifyRequest{Pod: sandboxpolicy.NRIPod{UID: "pod-uid", Namespace: "ns", Name: "pod"}}) + if c.Class != sandboxpolicy.PodSelected || c.Strict || len(c.Sections) != 0 || len(c.Policies) != 1 || c.Policies[0].UID != "http-uid" { + t.Fatalf("classification of an http-only pod: %+v", c) + } + p := readyPlugin(t, n) + if err := p.RunPodSandbox(t.Context(), nriTestPod("sb1", 42)); err != nil { + t.Fatalf("RunPodSandbox: %v", err) + } + ctr := &nriapi.Container{Id: "c-app", Name: "app", PodSandboxId: "sb1", Linux: &nriapi.LinuxContainer{CgroupsPath: "kubepods-besteffort-podpod_uid.slice:cri-containerd:c-app"}} + if _, _, err := p.CreateContainer(t.Context(), nriTestPod("sb1", 42), ctr); err != nil { + t.Fatalf("CreateContainer: %v", err) + } + if err := p.StartContainer(t.Context(), nriTestPod("sb1", 42), ctr); err != nil { + t.Fatalf("StartContainer: %v", err) + } + if backend.count("MarkPod") != 0 || backend.rec("pod-uid") != nil { + t.Fatalf("an http-only pod was marked: %v", backend.callNames()) + } + st := p.Status() + if len(st) != 1 || st[0].UID != "pod-uid" || st[0].State != startgate.StateNotStartGated || len(st[0].Policies) != 1 || st[0].Policies[0] != "http-uid" { + t.Fatalf("status: %+v", st) + } +} diff --git a/pkg/sandboxpolicy/integration/nrigate_static_test.go b/pkg/sandboxpolicy/integration/nrigate_static_test.go index 49c767ae0c..d4d376bc4b 100644 --- a/pkg/sandboxpolicy/integration/nrigate_static_test.go +++ b/pkg/sandboxpolicy/integration/nrigate_static_test.go @@ -3,6 +3,7 @@ package integration import ( "testing" + "github.com/kubescape/node-agent/pkg/sandboxpolicy" "github.com/kubescape/node-agent/pkg/sandboxpolicy/startgate" ) @@ -16,10 +17,10 @@ func TestToGateStatic(t *testing.T) { want bool }{ {"no annotations", nil, false}, - {"empty source", map[string]string{configSourceAnnotation: ""}, false}, - {"api", map[string]string{configSourceAnnotation: "api"}, false}, - {"file", map[string]string{configSourceAnnotation: "file"}, true}, - {"http", map[string]string{configSourceAnnotation: "http"}, true}, + {"empty source", map[string]string{sandboxpolicy.ConfigSourceAnnotation: ""}, false}, + {"api", map[string]string{sandboxpolicy.ConfigSourceAnnotation: "api"}, false}, + {"file", map[string]string{sandboxpolicy.ConfigSourceAnnotation: "file"}, true}, + {"http", map[string]string{sandboxpolicy.ConfigSourceAnnotation: "http"}, true}, } { t.Run(tc.name, func(t *testing.T) { sb := startgate.Sandbox{UID: "u", Namespace: "ns", Name: "n", ID: "sb", CgroupID: 7, CgroupPath: "/p", Annotations: tc.annotations} diff --git a/pkg/sandboxpolicy/integration/podgate.go b/pkg/sandboxpolicy/integration/podgate.go index 5d0b47213b..2cc941fe9f 100644 --- a/pkg/sandboxpolicy/integration/podgate.go +++ b/pkg/sandboxpolicy/integration/podgate.go @@ -1368,9 +1368,20 @@ func (e *gatePod) releasePending() bool { // close stops the gate: no new job is queued, the workers' context is // canceled, and it waits for the workers (each finishes its current job: // the backend returns on the canceled context) until ctx ends. The -// service calls it before it closes the backend. +// service calls it before it closes the backend. Workers that have stopped +// are never reported as running, whatever ctx says (re-merge review v1 F3): +// a worker leaves workers, under podMu, after its last job, and none starts +// once the gate is closed. func (g *podGate) close(ctx context.Context) error { g.stop() + idle := func() bool { + g.podMu.Lock() + defer g.podMu.Unlock() + return len(g.workers) == 0 + } + if idle() { + return nil + } done := make(chan struct{}) go func() { g.running.Wait() @@ -1380,6 +1391,9 @@ func (g *podGate) close(ctx context.Context) error { case <-done: return nil case <-ctx.Done(): + if idle() { + return nil + } return fmt.Errorf("start gate: workers still running at close: %w", ctx.Err()) } } diff --git a/pkg/sandboxpolicy/integration/podgate_finishedjob_test.go b/pkg/sandboxpolicy/integration/podgate_finishedjob_test.go index fc2a4352fe..89ab4dbb11 100644 --- a/pkg/sandboxpolicy/integration/podgate_finishedjob_test.go +++ b/pkg/sandboxpolicy/integration/podgate_finishedjob_test.go @@ -8,8 +8,7 @@ import ( // A request enqueued once a job with its key has finished (its waiters see // it done) runs a new job: it never joins the finished one and takes its -// old result (n2-review/s3-flake-unmark-stale.md: a retried unmark was -// dropped). Deterministic: the test holds podMu from before the job returns, +// old result (a flake: a retried unmark was dropped). Deterministic: the test holds podMu from before the job returns, // so the worker cannot take its next turn; the old worker closed done // without podMu and left the job current. func TestPodGateFinishedJobIsNotJoined(t *testing.T) { diff --git a/pkg/sandboxpolicy/integration/podgate_fu2b_close_linux_test.go b/pkg/sandboxpolicy/integration/podgate_fu2b_close_linux_test.go new file mode 100644 index 0000000000..b2e1f6bedd --- /dev/null +++ b/pkg/sandboxpolicy/integration/podgate_fu2b_close_linux_test.go @@ -0,0 +1,83 @@ +//go:build linux + +package integration + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + rf "github.com/inspektor-gadget/inspektor-gadget/gadgets/enforce_exec/restartfence" + "github.com/kubescape/node-agent/pkg/sandboxpolicy" + api "github.com/kubescape/storage/pkg/apis/sandbox/v1alpha1" +) + +// Re-merge review v1 F4: the pod gate under the fence-aware Close. A failed +// arm returns with the backend kept and the gate stopped; a retry whose +// gate.close runs out of ctx (a worker still writing) keeps the backend +// too; the next retry closes the backend only after the worker stopped. +func TestPodGateFenceAwareCloseRetries(t *testing.T) { + writer := &stopRecordingWriter{} + s, _, _ := stopTestService(t, writer) + calls := []string{} + armErr := errors.New("arm failed") + f := &startupFenceFake{calls: &calls, snapshot: rf.Snapshot{Owner: 17}, armErr: armErr} + s.execFence = newExecFenceManager(t.Context(), "unused", "unused", "unused", func(context.Context, string) (execFenceStartup, error) { return f, nil }) + s.uninstallDecided = true + s.refresh(t.Context()) // the exec policies, for the stop report + b := newFakeGateBackend() + s.backend = b + if err := s.enableStartGate(t.Context(), startGateSyscalls()); err != nil { + t.Fatal(err) + } + g := s.gate.Load() + // A worker that keeps writing after its context is canceled. + b.markGate, b.markEntered = make(chan struct{}), make(chan struct{}, 1) + c := selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p1", api.ModeEnforce)) + if _, err := g.JoinAndMark(t.Context(), testSandbox("A"), c, time.Now().Add(20*time.Millisecond)); !errors.Is(err, errWorkDeadline) { + t.Fatal(err) + } + <-b.markEntered + workersDone := false + b.onClose = func() { + g.podMu.Lock() + workersDone = len(g.workers) == 0 + g.podMu.Unlock() + } + + // 1. The arm fails: nothing closes, the gate is stopped. + if err := s.Close(t.Context()); !errors.Is(err, armErr) { + t.Fatalf("Close with a failing arm = %v", err) + } + if b.closes != 0 || g.ctx.Err() == nil { + t.Fatalf("after a failed arm: backend closes %d, gate stopped %v", b.closes, g.ctx.Err() != nil) + } + if _, err := g.JoinAndMark(t.Context(), testSandbox("A"), c, soon()); !errors.Is(err, errGateClosed) { + t.Fatalf("work after a failed arm: %v", err) + } + + // 2. The arm passes, but the worker still writes when ctx ends. + f.armErr = nil + short, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) + defer cancel() + if err := s.Close(short); err == nil || !strings.Contains(err.Error(), "workers still running") { + t.Fatalf("Close with a running worker = %v", err) + } + if b.closes != 0 { + t.Fatal("the backend closed while a gate worker was still writing") + } + + // 3. The worker stops: the retry closes the backend, after it. + close(b.markGate) + if err := s.Close(t.Context()); err != nil { + t.Fatal(err) + } + if b.closes != 1 || !workersDone { + t.Fatalf("final Close: backend closes %d, workers done at close %v", b.closes, workersDone) + } + if got := stopReasons(writer); len(got) != 1 || got[0] != sandboxpolicy.AgentStoppingUnconfirmedReason { + t.Fatalf("stop reports %v: one, unconfirmed (written at the failed arm)", got) + } +} diff --git a/pkg/sandboxpolicy/integration/podgate_fu2b_test.go b/pkg/sandboxpolicy/integration/podgate_fu2b_test.go new file mode 100644 index 0000000000..49d1c6e9ea --- /dev/null +++ b/pkg/sandboxpolicy/integration/podgate_fu2b_test.go @@ -0,0 +1,164 @@ +package integration + +import ( + "context" + "fmt" + "runtime" + "slices" + "strings" + "testing" + "time" + + "github.com/kubescape/node-agent/pkg/sandboxpolicy" + api "github.com/kubescape/storage/pkg/apis/sandbox/v1alpha1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + kubefake "k8s.io/client-go/kubernetes/fake" +) + +// S3 follow-up (coderabbit-1165-review-s3.md LOW, "a refresh can still bind +// a retired cgroup"): a refresh's merge records cgroup 77 in sent, and an +// older unmark covering 77 is queued while its BindPodsAt runs. The unmark +// never runs between the merge and the write (writeMu): it runs after the +// newer bind, so it cannot retire 77 while the backend still holds it. +// Whatever the order, a cgroup the backend's record holds stays an owner. +func TestRefreshMergeBindWindowIsClosed(t *testing.T) { + b, s, _ := deselectService(t) + g := s.gate.Load() + first := *s.podSeq + older := sandboxpolicy.Seq{Config: first.Config, Input: 2} + b.onBindAt = func() { + b.onBindAt = nil + // After the merge recorded 77: an older Unselected unmark is queued. + g.unmarkDeselected("pod-uid", older) + // Wait, by state and not by time (rev-a LOW 1), until its worker + // either runs the unmark during the refresh's write or is parked + // on writeMu behind it: one of the two always happens. + for deadline := time.Now().Add(10 * time.Second); b.count("UnmarkPod") == 0 && !drainParkedOnWriteMu(g); runtime.Gosched() { + if time.Now().After(deadline) { + t.Error("the unmark's worker neither ran nor waited for writeMu") + break + } + } + b.record("BindPodsAt-end") + } + s.inputEpoch.Store(3) + s.bindPods(t.Context()) + g.wait() + if s.podSeq.Compare(older) != sandboxpolicy.SeqNewer { + t.Fatalf("setup: the refresh %+v must be newer than the unmark %+v", *s.podSeq, older) + } + calls := b.callNames() + if end, unmark := slices.Index(calls, "BindPodsAt-end"), slices.Index(calls, "UnmarkPod"); unmark >= 0 && unmark < end { + t.Fatalf("the unmark ran between the refresh's merge and its write: %v", calls) + } + g.podMu.Lock() + owners := g.ownersLocked("pod-uid", 0) + g.podMu.Unlock() + if r := b.rec("pod-uid"); r != nil && !slices.Contains(owners, r.cgroup) { + t.Fatalf("the backend holds cgroup %d, which the gate retired (owners %v): a release would leak it (%v)", r.cgroup, owners, calls) + } +} + +// drainParkedOnWriteMu reports whether a worker of gate g (podGate.drain, +// whose receiver the traceback prints) is blocked in writeMu.RLock. +func drainParkedOnWriteMu(g *podGate) bool { + buf := make([]byte, 1<<22) + buf = buf[:runtime.Stack(buf, true)] + self := fmt.Sprintf("(*podGate).drain(%p", g) + for _, stack := range strings.Split(string(buf), "\n\n") { + if strings.Contains(stack, self) && strings.Contains(stack, "(*RWMutex).RLock") { + return true + } + } + return false +} + +// staticMirrorPod is an API pod on this node that claims kubelet UID kubelet. +func staticMirrorPod(name string, uid, kubelet types.UID) *corev1.Pod { + return &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "ns", UID: uid, Annotations: map[string]string{corev1.MirrorPodAnnotationKey: string(kubelet), sandboxpolicy.ConfigSourceAnnotation: "file"}}, + Spec: corev1.PodSpec{NodeName: "node", Containers: []corev1.Container{{Name: "app"}}}, Status: corev1.PodStatus{Phase: corev1.PodRunning}} +} + +// deselectStatics joins n static pods (kubelet UIDs static-), each with +// its mirror pod, deletes the last policy and runs a newer refresh. It +// returns the pod lists that refresh made, and whether every static pod was +// unmarked. +func deselectStatics(t *testing.T, n int) (int, bool) { + t.Helper() + b := newFakeGateBackend() + s, client := gateTestServiceClient(t, b) + kube := s.options.Kubernetes.(*kubefake.Clientset) + for i := range n { + if err := kube.Tracker().Add(staticMirrorPod(fmt.Sprintf("static-%d-node", i), types.UID(fmt.Sprintf("mirror-%d", i)), types.UID(fmt.Sprintf("static-%d", i)))); err != nil { + t.Fatal(err) + } + } + s.inputEpoch.Store(1) + if err := s.enableStartGate(t.Context(), startGateSyscalls()); err != nil { + t.Fatal(err) + } + g := s.gate.Load() + for i := range n { + sb := gateSandbox{UID: types.UID(fmt.Sprintf("static-%d", i)), Namespace: "ns", Name: fmt.Sprintf("static-%d-node", i), SandboxID: fmt.Sprintf("sb%d", i), + CgroupID: uint64(95 + i), CgroupPath: fmt.Sprintf("/kubepods/podstatic_%d", i), Static: true} + if _, err := g.JoinAndMark(t.Context(), sb, selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p1", api.ModeEnforce)), soon()); err != nil { + t.Fatal(err) + } + } + deletePolicy(t, client, "priv") + lists := func() int { + count := 0 + for _, a := range kube.Actions() { + if a.GetVerb() == "list" && a.GetResource().Resource == "pods" { + count++ + } + } + return count + } + s.inputEpoch.Store(10) + before := lists() + resync(t, s) + all := true + for i := range n { + all = all && b.rec(types.UID(fmt.Sprintf("static-%d", i))) == nil + } + return lists() - before, all +} + +// S3 follow-up (coderabbit-1165-r2-review-s3.md LOW): the uncached mirror +// re-read before a static pod's unmark is one read per refresh, whatever +// the number of static pods it unmarks. +func TestStaticUnmarkRereadIsBatched(t *testing.T) { + one, ok := deselectStatics(t, 1) + if !ok { + t.Fatal("setup: the static pod was not unmarked") + } + three, ok := deselectStatics(t, 3) + if !ok { + t.Fatal("three static pods: not all unmarked") + } + if three != one { + t.Fatalf("pod lists of a refresh that unmarks 3 static pods: %d, with one: %d; the re-read must be one per refresh", three, one) + } +} + +// Re-merge review v1 F3: close after every worker stopped is done, even +// with a ctx that has ended (Close's budget spent by the steps before it). +// The wait's select must not pick ctx.Done over workers that are gone. +func TestPodGateCloseAfterWorkersStoppedIsDone(t *testing.T) { + ended, cancel := context.WithCancel(t.Context()) + cancel() + for i := range 200 { + b := newFakeGateBackend() + g := newPodGate(t.Context(), b, nil) + if _, err := g.JoinAndMark(t.Context(), testSandbox("A"), selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p1", api.ModeEnforce)), soon()); err != nil { + t.Fatal(err) + } + g.wait() + if err := g.close(ended); err != nil { + t.Fatalf("run %d: close reported stopped workers as running: %v", i, err) + } + } +} diff --git a/pkg/sandboxpolicy/integration/service.go b/pkg/sandboxpolicy/integration/service.go index 5698000142..1ab251edda 100644 --- a/pkg/sandboxpolicy/integration/service.go +++ b/pkg/sandboxpolicy/integration/service.go @@ -1469,7 +1469,7 @@ func (s *Service) unmarkDeselected(ctx context.Context, gate *podGate, scheduled if uid != b.PodUID { // Classified as ClassifyPod classifies a static pod: from // its mirror pod, which names the kubelet UID. - p.ref.Annotations = map[string]string{configSourceAnnotation: "file"} + p.ref.Annotations = map[string]string{sandboxpolicy.ConfigSourceAnnotation: "file"} p.facts.Annotations = map[string]string{corev1.MirrorPodAnnotationKey: string(uid)} } pods[uid] = p @@ -1477,6 +1477,13 @@ func (s *Service) unmarkDeselected(ctx context.Context, gate *podGate, scheduled } p.facts.Containers = append(p.facts.Containers, sandboxpolicy.PodContainer{Name: b.ContainerName, Kind: b.Kind}) } + // recheck: the static pods to unmark through a mirror claim, by kubelet + // UID, with their mirror pod and sequence. + type recheck struct { + mirror types.UID + seq sandboxpolicy.Seq + } + rechecks := map[types.UID]recheck{} for _, uid := range order { p := pods[uid] c := s.Controller.ClassifyPod(ctx, sandboxpolicy.ClassifyRequest{Pod: p.ref}, sandboxpolicy.PodSource{ @@ -1498,21 +1505,32 @@ func (s *Service) unmarkDeselected(ctx context.Context, gate *podGate, scheduled if n := s.nriGate; n != nil && n.backingOff(uid, c.Seq, outcomeKey(c)) { continue } - // A static pod's mirror claim may be up to mirrorCacheTTL old: - // before its unmark it is read again, uncached, and must still - // be the only claim (CodeRabbit #1165 4806793402). - if p.mirror != uid && s.staticPodMirrors(ctx, map[types.UID]nriIdentity{uid: candidates[uid]}, epoch, true)[p.mirror] != uid { + if p.mirror != uid { + rechecks[uid] = recheck{mirror: p.mirror, seq: c.Seq} continue } gate.unmarkDeselected(uid, c.Seq) } } + if len(rechecks) == 0 { + return + } + // A static pod's mirror claim may be up to mirrorCacheTTL old: before + // its unmark it is read again, uncached, and must still be the only + // claim (CodeRabbit #1165 4806793402). One uncached read serves every + // static pod of this refresh. + ids := make(map[types.UID]nriIdentity, len(rechecks)) + for uid := range rechecks { + ids[uid] = candidates[uid] + } + fresh := s.staticPodMirrors(ctx, ids, epoch, true) + for uid, r := range rechecks { + if fresh[r.mirror] == uid { + gate.unmarkDeselected(uid, r.seq) + } + } } -// configSourceAnnotation is the kubelet's pod source annotation: a value -// other than "api" marks a static pod (sandboxpolicy.ClassifyPod). -const configSourceAnnotation = "kubernetes.io/config.source" - // staticPodMirrors maps the mirror pod (API UID) of each NRI candidate that // the NRI payload marks static (gateSandbox.Static) to the candidate's // kubelet UID. A mirror pod counts only @@ -2099,20 +2117,22 @@ func (s *Service) Close(ctx context.Context) error { // exits, so enforcement goes on until then. s.removePinsOnUninstall() reportStop(fenced) - // Only now, after the fence is armed, the pins are handled and - // AgentStopping is written, join the fence retirement consumer (its ctx - // was cancelled above). It never blocks shutdown: a consumer stuck in an - // IG call is logged and left to the process exit. - s.joinFenceRetirement(ctx, retireDone) if gate := s.gate.Load(); gate != nil && !s.backendClosed { // The pod gate's workers write to the backend: stop them first. // When they do not stop within ctx, Close returns without closing // the backend (S3 review v2 N5); a later Close retries both, and - // gate.close is idempotent. + // gate.close is idempotent. Before the fence join, which may spend + // ctx (re-merge review v1 F3): the workers were canceled above and + // use nothing the fence retirement consumer holds. if err := gate.close(ctx); err != nil { return err } } + // Only now, after the fence is armed, the pins are handled and + // AgentStopping is written, join the fence retirement consumer (its ctx + // was cancelled above). It never blocks shutdown: a consumer stuck in an + // IG call is logged and left to the process exit. + s.joinFenceRetirement(ctx, retireDone) if !s.backendClosed { if err := s.backend.Close(ctx); err != nil { return err diff --git a/pkg/sandboxpolicy/integration/service_test.go b/pkg/sandboxpolicy/integration/service_test.go index 600fa1e37e..71d5146b2a 100644 --- a/pkg/sandboxpolicy/integration/service_test.go +++ b/pkg/sandboxpolicy/integration/service_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "strings" + "sync" "sync/atomic" "testing" "time" @@ -449,19 +450,34 @@ func TestServiceReportsUnexpectedExporterExit(t *testing.T) { if err := s.exporter.Run(stopped); !errors.Is(err, context.Canceled) { t.Fatalf("prepare stopped exporter: %v", err) } + // Start also reports what the host gives it (a /sys/fs/bpf pin this + // user cannot read or remove, ...): OnError never blocks, and only the + // exporter's exit is waited for. reported := make(chan error, 1) - s.options.OnError = func(err error) { reported <- err } + var others []error + var othersMu sync.Mutex + s.options.OnError = func(err error) { + if err != nil && strings.Contains(err.Error(), "sandbox verdict exporter") { + select { + case reported <- err: + default: + } + return + } + othersMu.Lock() + others = append(others, err) + othersMu.Unlock() + } s.snapshot = func(context.Context) ([]sandboxpolicy.Binding, error) { return nil, nil } if err := s.Start(t.Context()); err != nil { t.Fatal(err) } select { - case err := <-reported: - if err == nil || !strings.Contains(err.Error(), "sandbox verdict exporter") { - t.Fatalf("missing exporter failure context: %v", err) - } + case <-reported: case <-time.After(time.Second): - t.Fatal("unexpected exporter exit was not reported") + othersMu.Lock() + defer othersMu.Unlock() + t.Fatalf("unexpected exporter exit was not reported (other reports: %v)", others) } if err := s.Close(t.Context()); err != nil { t.Fatal(err) From ed2e942699f7b46de1ef6437a6bc1ece8381514c Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Sat, 5 Dec 2026 17:45:06 +0100 Subject: [PATCH 3/5] fix(nri): refuse holds while a plan write is in flight; rotate re-proofs Copilot on #1231 (047d6c5d). - podGate counts each pod's started, unfinished writes (the mark job, the unmark job and the refresh's BindPodsAt). A hold whose wait expires while one is outstanding returns no confirmation, so the create is refused instead of admitted on a cached Strict read-back that the write may already have replaced. The commit is counted before the write ends, and every count is ended by defer (4811942032). - reproveHeld walks its queue with a rotating cursor and checks its budget on the gate's clock, so one slow lookup cannot starve the cgroups behind it (4811942065). Co-Authored-By: Claude Opus 5.5 Docs-exempt: internal fixes in the unreleased NRI start gate stack Signed-off-by: Matthias Bertschy --- .../integration/fu2_gate_test.go | 196 ++++++++++++++++++ pkg/sandboxpolicy/integration/nrigate.go | 28 ++- pkg/sandboxpolicy/integration/podgate.go | 81 +++++++- pkg/sandboxpolicy/integration/service.go | 16 +- 4 files changed, 303 insertions(+), 18 deletions(-) diff --git a/pkg/sandboxpolicy/integration/fu2_gate_test.go b/pkg/sandboxpolicy/integration/fu2_gate_test.go index 0997d6fde3..cd2131b414 100644 --- a/pkg/sandboxpolicy/integration/fu2_gate_test.go +++ b/pkg/sandboxpolicy/integration/fu2_gate_test.go @@ -794,3 +794,199 @@ func fu2GetReactor(s *Service, down func() bool) { return false, nil, nil }) } + +// TestFU2HoldRefusesWhileABindRuns (PR #1231 Copilot 4811942032): a +// refresh's BindPodsAt of the pod has started (it may already have +// replaced the pod's mark) and blocks; a hold that expires meanwhile must +// not return its cached read-back: no confirmations, errCommittedAfterRead, +// so the create is refused. +func TestFU2HoldRefusesWhileABindRuns(t *testing.T) { + s, backend := nriTestService(t) + n := readyNRIGate(t, s, backend) + s.nriGate = n + c := n.Classify(t.Context(), fu2Req) + sb, err := n.Sandbox(nriTestPod("sb1", 42)) + if err != nil { + t.Fatal(err) + } + if _, err := n.JoinAndMark(t.Context(), sb, c, soon()); err != nil { + t.Fatal(err) + } + s.podSeq = &c.Seq + entered, release := make(chan struct{}), make(chan struct{}) + var once sync.Once + backend.onBindAt = func() { once.Do(func() { close(entered); <-release }) } + type held struct { + confs []sandboxpolicy.PodSectionConfirmation + err error + } + done := make(chan held, 1) + // Another plan than the record's: never Confirmed, so the hold runs to + // its deadline. + other := selected(c.Seq, gatePolicy("p9", api.ModeEnforce)) + go func() { + confs, err := n.gate.HoldUntilConfirmed(t.Context(), "pod-uid", "sb1", other, time.Now().Add(400*time.Millisecond)) + done <- held{confs, err} + }() + for wait := time.Now().Add(5 * time.Second); backend.count("ConfirmPod") == 0; { + if time.Now().After(wait) { + t.Fatal("setup: the hold never read back") + } + time.Sleep(time.Millisecond) + } + bound := make(chan struct{}) + go func() { + defer close(bound) + s.bindPodPlans(context.Background(), nil, nil, nil, nil, false) + }() + <-entered + h := <-done + close(release) + <-bound + n.gate.wait() + if len(h.confs) != 0 || !errors.Is(h.err, errCommittedAfterRead) { + t.Fatalf("a hold that expired while a bind of the pod ran: %+v %v, want no confirmations and errCommittedAfterRead", h.confs, h.err) + } + n.gate.podMu.Lock() + left := len(n.gate.writing) + n.gate.podMu.Unlock() + if left != 0 { + t.Fatalf("writes left in flight after the bind returned: %d", left) + } +} + +// TestFU2ReproveRotates (PR #1231 Copilot 4811942065): a queued cgroup +// whose pod lookup takes the whole re-proof budget does not starve the +// rest of the queue: the next pass resumes after it, so the later cgroups +// are proven within two refreshes, and the slow one is still tried. The +// budget runs on the gate's clock, which the slow lookup moves past it, so +// no wall time decides the outcome (rev-b MEDIUM: a 50 ms budget flaked +// under -race). +func TestFU2ReproveRotates(t *testing.T) { + s, backend := nriTestService(t) + kube := s.options.Kubernetes.(*kubefake.Clientset) + for _, name := range []string{"pod-b", "pod-c"} { + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "ns", UID: types.UID(name + "-uid")}, Spec: corev1.PodSpec{NodeName: "node", Containers: []corev1.Container{{Name: "app"}}}} + if err := kube.Tracker().Add(pod); err != nil { + t.Fatal(err) + } + } + var clock atomic.Int64 // the gate's clock, in nanoseconds + clock.Store(time.Unix(1_000_000, 0).UnixNano()) + var slowGets atomic.Int32 + kube.PrependReactor("get", "pods", func(a k8stesting.Action) (bool, runtime.Object, error) { + if a.(k8stesting.GetAction).GetName() != "pod-a" { + return false, nil, nil + } + // A lookup that takes twice the budget. + slowGets.Add(1) + clock.Add(int64(2 * reclassifyBudget)) + return true, nil, errors.New("slow API") + }) + useNoPolicy(t, s, backend.fakeGateBackend) + n := readyNRIGate(t, s, backend) + n.now = func() time.Time { return time.Unix(0, clock.Load()) } + prover := &fu2Prover{nriTestBackend: backend, answer: true} + n.sync = prover + n.SetNRISynced(1, nil) + for i, name := range []string{"pod-a", "pod-b", "pod-c"} { + sb := startgate.Sandbox{UID: types.UID(name + "-uid"), Namespace: "ns", Name: name, ID: "sb-" + name, CgroupID: uint64(10 * (i + 1)), CgroupPath: "/kubepods/" + name} + if err := n.JoinUnselected(sb); err != nil { + t.Fatal(err) + } + n.ReproveCgroup(1, sb) + } + queued := func(cgroup uint64) bool { + n.mu.Lock() + defer n.mu.Unlock() + _, ok := n.reprove[cgroup] + return ok + } + n.reclassifyUnbound(t.Context(), nil, sandboxpolicy.Seq{}) + if slowGets.Load() != 1 || !queued(10) || !queued(20) || !queued(30) { + t.Fatalf("the first pass: %d slow lookups, queued 10 %v, 20 %v, 30 %v; want 1 and all queued (the budget went on the first)", slowGets.Load(), queued(10), queued(20), queued(30)) + } + n.reclassifyUnbound(t.Context(), nil, sandboxpolicy.Seq{}) + if queued(20) || queued(30) || !queued(10) { + t.Fatalf("after 2 refreshes: queued 10 %v, 20 %v, 30 %v (calls %v); want only the slow 10", queued(10), queued(20), queued(30), prover.calls) + } + if slowGets.Load() != 2 { + t.Fatalf("the slow cgroup was not tried again after the rest: %d lookups, want 2", slowGets.Load()) + } +} + +// fu2BlockBackend blocks MarkPod or UnmarkPod (block names which) after +// the inner write, until release is closed: a write that changed the pod +// and has not returned. +type fu2BlockBackend struct { + *fakeGateBackend + block string + entered, release chan struct{} + once sync.Once +} + +func (b *fu2BlockBackend) hold(call string) { + if b.block == call { + b.once.Do(func() { close(b.entered); <-b.release }) + } +} + +func (b *fu2BlockBackend) MarkPod(ctx context.Context, pod sandboxpolicy.PodBinding, seq sandboxpolicy.Seq) []sandboxpolicy.PodSectionResult { + res := b.fakeGateBackend.MarkPod(ctx, pod, seq) + b.hold("MarkPod") + return res +} + +func (b *fu2BlockBackend) UnmarkPod(ctx context.Context, uid types.UID, cgroup uint64, seq sandboxpolicy.Seq) error { + err := b.fakeGateBackend.UnmarkPod(ctx, uid, cgroup, seq) + b.hold("UnmarkPod") + return err +} + +// TestFU2HoldRefusesWhileAGateWriteRuns (PR #1231 Copilot 4811942032): a +// mark or unmark job of the pod that wrote and has not returned keeps a +// hold that expires meanwhile from returning its cached read-back. +func TestFU2HoldRefusesWhileAGateWriteRuns(t *testing.T) { + for _, call := range []string{"MarkPod", "UnmarkPod"} { + t.Run(call, func(t *testing.T) { + b := &fu2BlockBackend{fakeGateBackend: newFakeGateBackend(), entered: make(chan struct{}), release: make(chan struct{})} + g := newPodGate(t.Context(), b, nil) + c := selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p1", api.ModeEnforce)) + if _, err := g.JoinAndMark(t.Context(), testSandbox("sb1"), c, soon()); err != nil { + t.Fatal(err) + } + b.block = call + type held struct { + confs []sandboxpolicy.PodSectionConfirmation + err error + } + done := make(chan held, 1) + other := selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p9", api.ModeEnforce)) + go func() { + confs, err := g.HoldUntilConfirmed(t.Context(), "pod-uid", "sb1", other, time.Now().Add(300*time.Millisecond)) + done <- held{confs, err} + }() + for wait := time.Now().Add(5 * time.Second); b.count("ConfirmPod") == 0; { + if time.Now().After(wait) { + t.Fatal("setup: the hold never read back") + } + time.Sleep(time.Millisecond) + } + next := sandboxpolicy.Seq{Config: 2, Input: 2} + go func() { + if call == "MarkPod" { + _, _ = g.JoinAndMark(context.Background(), testSandbox("sb1"), selected(next, gatePolicy("p1", api.ModeAudit)), time.Now().Add(5*time.Second)) + } else { + _ = g.Unmark(context.Background(), testSandbox("sb1"), next, time.Now().Add(5*time.Second)) + } + }() + <-b.entered + h := <-done + close(b.release) + g.wait() + if len(h.confs) != 0 || !errors.Is(h.err, errCommittedAfterRead) { + t.Fatalf("a hold that expired while a %s of the pod ran: %+v %v", call, h.confs, h.err) + } + }) + } +} diff --git a/pkg/sandboxpolicy/integration/nrigate.go b/pkg/sandboxpolicy/integration/nrigate.go index ddb847cc7c..2e2933015a 100644 --- a/pkg/sandboxpolicy/integration/nrigate.go +++ b/pkg/sandboxpolicy/integration/nrigate.go @@ -117,6 +117,10 @@ type nriGate struct { syncEpoch uint64 reprove map[uint64]reproveItem reproveGen uint64 + // reproveAfter is the cgroup reproveHeld tried last: the next pass + // starts after it, so one slow lookup cannot hold the rest of the + // queue back (PR #1231 Copilot 4811942065). Under mu. + reproveAfter uint64 } // reproveItem is a pod cgroup to prove again: the Synchronize it is for, @@ -838,7 +842,11 @@ func (n *nriGate) ReproveCgroup(epoch uint64, sb startgate.Sandbox) { // refresh then retires the previous run's pending marks it covers // (Settle). Any other answer, an Unknown classification included, leaves // the cgroup queued for the next refresh (fail-closed: the mark stays). -// Bounded by reclassifyBudget. +// Bounded by reclassifyBudget, on the gate's clock (now) between items +// and on the wall clock for the lookups' context. The queue is walked in cgroup order from the +// one after the last tried (reproveAfter), wrapping around: a lookup that +// takes the whole budget costs one pass, and the next pass goes on with +// the rest. func (n *nriGate) reproveHeld(ctx context.Context) { prover, ok := n.sync.(sandboxpolicy.NRICgroupProver) n.mu.Lock() @@ -854,13 +862,23 @@ func (n *nriGate) reproveHeld(ctx context.Context) { if !ok || len(todo) == 0 { return } - deadline := time.Now().Add(reclassifyBudget) - ctx, cancel := context.WithDeadline(ctx, deadline) + deadline := n.now().Add(reclassifyBudget) + ctx, cancel := context.WithTimeout(ctx, reclassifyBudget) defer cancel() - for _, cgroup := range slices.Sorted(maps.Keys(todo)) { - if !time.Now().Before(deadline) { + order := slices.Sorted(maps.Keys(todo)) + n.mu.Lock() + after := n.reproveAfter + n.mu.Unlock() + if i, _ := slices.BinarySearch(order, after+1); i > 0 && i < len(order) { + order = append(order[i:], order[:i]...) + } + for _, cgroup := range order { + if !n.now().Before(deadline) { return } + n.mu.Lock() + n.reproveAfter = cgroup + n.mu.Unlock() it := todo[cgroup] c := n.Classify(ctx, sandboxpolicy.ClassifyRequest{Pod: it.pod}) if c.Class != sandboxpolicy.PodUnselected && (c.Class != sandboxpolicy.PodSelected || len(c.Sections) > 0 || c.Strict) { diff --git a/pkg/sandboxpolicy/integration/podgate.go b/pkg/sandboxpolicy/integration/podgate.go index 883aef7f3d..7a1b2ad4ad 100644 --- a/pkg/sandboxpolicy/integration/podgate.go +++ b/pkg/sandboxpolicy/integration/podgate.go @@ -59,7 +59,7 @@ var ( // and a write that may change the pod's plan landed after its last // read-back, so that read-back may not be the plan in force // (HoldUntilConfirmed; CodeRabbit #1176 4810415638). - errCommittedAfterRead = errors.New("start gate: a write of the pod's plan landed after the last read-back") + errCommittedAfterRead = errors.New("start gate: a write of the pod's plan landed after the last read-back, or is still running") // errNotSelected: only a Selected pod with a section plan is marked. errNotSelected = errors.New("start gate: only a Selected pod with a section plan is marked") // errNoCgroup: the sandbox's pod cgroup was not resolved (cgroup ID 0). @@ -247,6 +247,14 @@ type podGate struct { unreleased map[types.UID][]*gatePod // now is the clock of the unreleased retries (replaced in tests). now func() time.Time + // writing counts, by pod UID, the writes that may change the pod's + // plan in the backend and have started but not returned: a refresh's + // bind of the pod (beginWrites, endWrites), a mark or an unmark job. + // A hold that ends unconfirmed refuses its last read-back while one + // is outstanding (PR #1231 Copilot 4811942032): a call can replace + // the pod's mark and then block on another pod or section. An entry + // goes when its count returns to 0. + writing map[types.UID]int } type releasedEntry struct { @@ -470,15 +478,15 @@ func (g *podGate) JoinAndMark(ctx context.Context, sb gateSandbox, c sandboxpoli cgroup, joined = p.sandboxes[sb.SandboxID] } removed := g.tombstonedLocked(sb.SandboxID) || !joined || cgroup != sb.CgroupID + if !removed { + g.beginWriteLocked(sb.UID) + } g.podMu.Unlock() if removed { return gateResult{err: errSandboxRemoved} } - res := gateResult{sections: g.backend.MarkPod(ctx, pod, seq)} - g.podMu.Lock() - g.commitLocked(sb.UID) - g.podMu.Unlock() - return res + defer g.writeDone(sb.UID) // also when MarkPod panics + return gateResult{sections: g.backend.MarkPod(ctx, pod, seq)} }, }) g.podMu.Unlock() @@ -561,7 +569,9 @@ func planKey(c sandboxpolicy.PodClassification) string { // the last bind errors) when not every section was Confirmed by then; no // confirmations, with errCommittedAfterRead, when a write that may change // the pod's plan landed after that read (a refresh's bind, a mark or an -// unmark: gatePod.commits) or the pod was released meanwhile. The +// unmark: gatePod.commits), one is still outstanding (podGate.writing: it +// may already have replaced the mark), or the pod was released meanwhile. +// The // caller decides from the confirmations (a Strict create needs Confirmed, // or Pending with Strict). func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandboxID string, c sandboxpolicy.PodClassification, deadline time.Time) ([]sandboxpolicy.PodSectionConfirmation, error) { @@ -584,7 +594,7 @@ func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandbox errs := append([]error{err}, bindErrs...) if last != nil { g.podMu.Lock() - current := g.pods[uid] == stamp.entry && stamp.entry != nil && !stamp.entry.released && stamp.entry.commits == stamp.commits + current := g.pods[uid] == stamp.entry && stamp.entry != nil && !stamp.entry.released && stamp.entry.commits == stamp.commits && g.writing[uid] == 0 g.podMu.Unlock() if !current { return nil, errors.Join(append([]error{errCommittedAfterRead}, errs...)...) @@ -777,10 +787,15 @@ func (g *podGate) enqueueUnmarkLocked(uid types.UID, cgroups []uint64, seq sandb return g.enqueueLocked(uid, &gateJob{ key: fmt.Sprintf("unmark/%v/%d/%d", cgroups, seq.Config, seq.Input), run: func(ctx context.Context) gateResult { - err := g.unmarkOwners(ctx, uid, cgroups, seq) + g.podMu.Lock() + g.beginWriteLocked(uid) + g.podMu.Unlock() + err := func() error { + defer g.writeDone(uid) // also when UnmarkPod panics + return g.unmarkOwners(ctx, uid, cgroups, seq) + }() g.podMu.Lock() defer g.podMu.Unlock() - g.commitLocked(uid) p := g.pods[uid] if err == nil { // Its binding is gone: the cgroups it covered have nothing @@ -1229,6 +1244,52 @@ func (g *podGate) afterBind(sent []sandboxpolicy.PodBinding, releasesBefore uint } } +// beginWrites records that a refresh's BindPodsAt of pods starts +// (podGate.writing); endWrites, called once it returned, ends them. The +// refresh calls them around its write (Service.bindGatePodPlans). +func (g *podGate) beginWrites(pods []sandboxpolicy.PodBinding) { + g.podMu.Lock() + defer g.podMu.Unlock() + for _, p := range pods { + g.beginWriteLocked(p.PodUID) + } +} + +func (g *podGate) endWrites(pods []sandboxpolicy.PodBinding) { + g.podMu.Lock() + defer g.podMu.Unlock() + for _, p := range pods { + g.endWriteLocked(p.PodUID) + } +} + +// writeDone ends a gate job's write of uid: it counts the commit, then +// ends the write, under one lock, so a hold never sees neither. The jobs +// defer it, so it runs on a panic too. +func (g *podGate) writeDone(uid types.UID) { + g.podMu.Lock() + defer g.podMu.Unlock() + g.commitLocked(uid) + g.endWriteLocked(uid) +} + +// beginWriteLocked and endWriteLocked count one write of uid in and out +// (podGate.writing). Run under podMu. +func (g *podGate) beginWriteLocked(uid types.UID) { + if g.writing == nil { + g.writing = map[types.UID]int{} + } + g.writing[uid]++ +} + +func (g *podGate) endWriteLocked(uid types.UID) { + if g.writing[uid] <= 1 { + delete(g.writing, uid) + return + } + g.writing[uid]-- +} + // commitLocked counts a write that may have changed uid's plan in the // backend, once it returned (gatePod.commits). Runs under podMu. func (g *podGate) commitLocked(uid types.UID) { diff --git a/pkg/sandboxpolicy/integration/service.go b/pkg/sandboxpolicy/integration/service.go index b10473fa68..8fb7889d2a 100644 --- a/pkg/sandboxpolicy/integration/service.go +++ b/pkg/sandboxpolicy/integration/service.go @@ -1656,9 +1656,19 @@ func (s *Service) bindGatePodPlans(ctx context.Context, gate *podGate, pods []sa // the moment it may be in force (Copilot #1176 4799235745). n.noteRefreshStrict(pods, seq) } - err := gate.backend.BindPodsAt(ctx, pods, seq) - // Whatever err says: an ErrStaleSequence never means nothing changed. - gate.afterBind(pods, releases) + // A hold refuses its last read-back while this write runs: it may + // replace a pod's mark and then block on another (PR #1231 Copilot + // 4811942032). + err := func() error { + gate.beginWrites(pods) + // Deferred, so they run on a panic too, last in first out: + // afterBind counts the commit before endWrites ends the write, so + // a hold never sees neither. Whatever err says: an + // ErrStaleSequence never means nothing changed. + defer gate.endWrites(pods) + defer gate.afterBind(pods, releases) + return gate.backend.BindPodsAt(ctx, pods, seq) + }() if err == nil { return true } From 4e3167aeabfa9fc405219d7b39ace7a9a8801024 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Sat, 5 Dec 2026 18:13:18 +0100 Subject: [PATCH 4/5] fix(nri): bound the re-proof's wait for the node owner lock Copilot 4812087571 on #1231 (ed2e9426). ProveNRICgroup took the node owner's mutex unconditionally, so a hold worker publishing a slot could stall the whole re-proof pass past its budget. NRICgroupProver.ProveNRICgroup now takes a deadline, SectionBackend passes it to every section, and nodeOwner waits with the deadline- bounded lockBy. A busy owner records nothing and returns false, so the cgroup stays queued and unproven; the rotation continues with the rest. A cgroup counts as proven only when every section proves it. Co-Authored-By: Claude Opus 5.5 Docs-exempt: internal fix in the unreleased NRI start gate stack Signed-off-by: Matthias Bertschy --- pkg/sandboxpolicy/igbackend/fu2_gate_test.go | 39 +++++++++++++- .../igbackend/nodeowner_syncproof.go | 18 +++++-- .../integration/fu2_gate_test.go | 52 +++++++++++++++++- pkg/sandboxpolicy/integration/nrigate.go | 5 +- pkg/sandboxpolicy/sections.go | 15 +++--- pkg/sandboxpolicy/sections_fu2_test.go | 53 +++++++++++++++++++ 6 files changed, 167 insertions(+), 15 deletions(-) create mode 100644 pkg/sandboxpolicy/sections_fu2_test.go diff --git a/pkg/sandboxpolicy/igbackend/fu2_gate_test.go b/pkg/sandboxpolicy/igbackend/fu2_gate_test.go index 61fe4e3aae..4ef8ebd59a 100644 --- a/pkg/sandboxpolicy/igbackend/fu2_gate_test.go +++ b/pkg/sandboxpolicy/igbackend/fu2_gate_test.go @@ -74,7 +74,7 @@ func TestFU2ProveNRICgroup(t *testing.T) { t.Run(tt.name, func(t *testing.T) { b, _ := newGate(t) tt.setup(b) - if got := b.ProveNRICgroup(tt.epoch, podCgroup, tt.seq); got != tt.want { + 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() @@ -89,7 +89,42 @@ func TestFU2ProveNRICgroup(t *testing.T) { b.SetStartGate(true) b.SetNRISynced(1, nil) b.SetNRISyncSeq(1, seq(3, 3)) - if b.ProveNRICgroup(1, 0, 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") + } +} diff --git a/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go b/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go index 94f0784ddd..37c7da7f51 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner_syncproof.go @@ -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 @@ -45,9 +49,15 @@ func (b *nodeOwner[C]) auditRetires(seq *sandboxpolicy.Seq) bool { // 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. -func (b *nodeOwner[C]) ProveNRICgroup(epoch, cgroup uint64, seq sandboxpolicy.Seq) bool { - b.mu.Lock() +// 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 diff --git a/pkg/sandboxpolicy/integration/fu2_gate_test.go b/pkg/sandboxpolicy/integration/fu2_gate_test.go index cd2131b414..4f7406b13f 100644 --- a/pkg/sandboxpolicy/integration/fu2_gate_test.go +++ b/pkg/sandboxpolicy/integration/fu2_gate_test.go @@ -505,13 +505,18 @@ type fu2Prover struct { mu sync.Mutex calls []string answer bool + // busy names the cgroups whose gate is busy until the deadline + // (false), and deadlines records the deadline of each call. + busy map[uint64]bool + deadlines []time.Time } -func (p *fu2Prover) ProveNRICgroup(epoch, cgroup uint64, seq sandboxpolicy.Seq) bool { +func (p *fu2Prover) ProveNRICgroup(epoch, cgroup uint64, seq sandboxpolicy.Seq, deadline time.Time) bool { p.mu.Lock() defer p.mu.Unlock() p.calls = append(p.calls, fmt.Sprintf("%d:%d:%d/%d", epoch, cgroup, seq.Config, seq.Input)) - return p.answer + p.deadlines = append(p.deadlines, deadline) + return p.answer && !p.busy[cgroup] } func (p *fu2Prover) count() int { @@ -990,3 +995,46 @@ func TestFU2HoldRefusesWhileAGateWriteRuns(t *testing.T) { }) } } + +// TestFU2ReproveBusyGateStaysQueued (PR #1231 Copilot 4812087571): the +// re-proof pass gives the prover the wall-clock end of its budget, and a +// cgroup whose gate is busy until then stays queued while the pass goes on +// with the later cgroups. +func TestFU2ReproveBusyGateStaysQueued(t *testing.T) { + s, backend := nriTestService(t) + kube := s.options.Kubernetes.(*kubefake.Clientset) + for _, name := range []string{"pod-a", "pod-b", "pod-c"} { + pod := &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "ns", UID: types.UID(name + "-uid")}, Spec: corev1.PodSpec{NodeName: "node", Containers: []corev1.Container{{Name: "app"}}}} + if err := kube.Tracker().Add(pod); err != nil { + t.Fatal(err) + } + } + useNoPolicy(t, s, backend.fakeGateBackend) + n := readyNRIGate(t, s, backend) + prover := &fu2Prover{nriTestBackend: backend, answer: true, busy: map[uint64]bool{10: true}} + n.sync = prover + n.SetNRISynced(1, nil) + for i, name := range []string{"pod-a", "pod-b", "pod-c"} { + sb := startgate.Sandbox{UID: types.UID(name + "-uid"), Namespace: "ns", Name: name, ID: "sb-" + name, CgroupID: uint64(10 * (i + 1)), CgroupPath: "/kubepods/" + name} + if err := n.JoinUnselected(sb); err != nil { + t.Fatal(err) + } + n.ReproveCgroup(1, sb) + } + start := time.Now() + n.reclassifyUnbound(t.Context(), nil, sandboxpolicy.Seq{}) + n.mu.Lock() + _, q10 := n.reprove[10] + left := len(n.reprove) + n.mu.Unlock() + if !q10 || left != 1 { + t.Fatalf("a busy gate: queued 10 %v, %d left (calls %v); want only 10", q10, left, prover.calls) + } + prover.mu.Lock() + defer prover.mu.Unlock() + for _, d := range prover.deadlines { + if d.IsZero() || d.Before(start) || d.After(time.Now().Add(reclassifyBudget)) { + t.Fatalf("prove deadline %v, want within the pass's %v budget from %v", d, reclassifyBudget, start) + } + } +} diff --git a/pkg/sandboxpolicy/integration/nrigate.go b/pkg/sandboxpolicy/integration/nrigate.go index 2e2933015a..296f2e7549 100644 --- a/pkg/sandboxpolicy/integration/nrigate.go +++ b/pkg/sandboxpolicy/integration/nrigate.go @@ -865,6 +865,9 @@ func (n *nriGate) reproveHeld(ctx context.Context) { deadline := n.now().Add(reclassifyBudget) ctx, cancel := context.WithTimeout(ctx, reclassifyBudget) defer cancel() + // The prove waits for a busy backend until the wall-clock end of the + // pass at most (PR #1231 Copilot 4812087571). + wall, _ := ctx.Deadline() order := slices.Sorted(maps.Keys(todo)) n.mu.Lock() after := n.reproveAfter @@ -884,7 +887,7 @@ func (n *nriGate) reproveHeld(ctx context.Context) { if c.Class != sandboxpolicy.PodUnselected && (c.Class != sandboxpolicy.PodSelected || len(c.Sections) > 0 || c.Strict) { continue } - if n.HoldsMark(it.pod.UID) || !prover.ProveNRICgroup(it.epoch, cgroup, c.Seq) { + if n.HoldsMark(it.pod.UID) || !prover.ProveNRICgroup(it.epoch, cgroup, c.Seq, wall) { continue } n.mu.Lock() diff --git a/pkg/sandboxpolicy/sections.go b/pkg/sandboxpolicy/sections.go index 2e067de953..33a74348c0 100644 --- a/pkg/sandboxpolicy/sections.go +++ b/pkg/sandboxpolicy/sections.go @@ -437,19 +437,22 @@ type NRISyncSequencer interface { // 4802130614): ProveNRICgroup records cgroup as proven for the Synchronize // on epoch when seq, this run's classification of its pod needing no // Strict pending mark, is at or after that Synchronize's sequence (owner -// batch 12). false: not recorded (another completion, no sequence, or an -// older classification). +// batch 12). false: not recorded (another completion, no sequence, an +// older classification, or the gate busy until deadline: it waits for it +// until deadline at most, and a passed deadline gets one try; PR #1231 +// Copilot 4812087571). The caller keeps an unrecorded cgroup queued. type NRICgroupProver interface { - ProveNRICgroup(epoch, cgroup uint64, seq Seq) bool + ProveNRICgroup(epoch, cgroup uint64, seq Seq, deadline time.Time) bool } // ProveNRICgroup asks every section whose pod gate takes it -// (NRICgroupProver); true only when each of them recorded it. -func (s *SectionBackend) ProveNRICgroup(epoch, cgroup uint64, seq Seq) bool { +// (NRICgroupProver), each bounded by deadline; true only when each of them +// recorded it. +func (s *SectionBackend) ProveNRICgroup(epoch, cgroup uint64, seq Seq, deadline time.Time) bool { ok := true for _, sec := range s.sections { if p, is := sec.backend.(NRICgroupProver); is { - ok = p.ProveNRICgroup(epoch, cgroup, seq) && ok + ok = p.ProveNRICgroup(epoch, cgroup, seq, deadline) && ok } } return ok diff --git a/pkg/sandboxpolicy/sections_fu2_test.go b/pkg/sandboxpolicy/sections_fu2_test.go new file mode 100644 index 0000000000..767cc0e04b --- /dev/null +++ b/pkg/sandboxpolicy/sections_fu2_test.go @@ -0,0 +1,53 @@ +package sandboxpolicy + +import ( + "testing" + "time" +) + +// proverBackend is a section backend that answers ProveNRICgroup with +// answer and counts the calls. +type proverBackend struct { + *fakeBackend + answer bool + calls int +} + +func (b *proverBackend) ProveNRICgroup(uint64, uint64, Seq, time.Time) bool { + b.calls++ + return b.answer +} + +// TestFU2ProveNRICgroupNeedsEverySection (rev-b LOW-6 on #1231 round 2): +// SectionBackend.ProveNRICgroup is true only when every section with a +// prover recorded the cgroup. One that refuses (busy, another completion, +// an older classification) makes it false whatever its order, so the +// caller keeps the cgroup queued; every prover is still asked. +func TestFU2ProveNRICgroupNeedsEverySection(t *testing.T) { + for _, tc := range []struct { + name string + privilege, other bool + want bool + }{ + {name: "privilege refuses, network proves", privilege: false, other: true}, + {name: "privilege proves, network refuses", privilege: true, other: false}, + {name: "both refuse"}, + {name: "both prove", privilege: true, other: true, want: true}, + } { + t.Run(tc.name, func(t *testing.T) { + privilege := &proverBackend{fakeBackend: &fakeBackend{plans: map[string]Plan{}}, answer: tc.privilege} + network := &proverBackend{fakeBackend: &fakeBackend{plans: map[string]Plan{}}, answer: tc.other} + s, err := NewSectionBackend(&fakeBackend{plans: map[string]Plan{}}, privilege, nil) + if err != nil { + t.Fatal(err) + } + s.WithNetwork(network, nil) + if got := s.ProveNRICgroup(1, 77, Seq{Config: 1, Input: 1}, time.Now().Add(time.Second)); got != tc.want { + t.Fatalf("ProveNRICgroup = %v, want %v", got, tc.want) + } + if privilege.calls != 1 || network.calls != 1 { + t.Fatalf("calls: privilege %d, network %d; want each asked once", privilege.calls, network.calls) + } + }) + } +} From ebd50320796c0e6c356ac2ab40b0a8a5364626ff Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Sat, 5 Dec 2026 18:32:16 +0100 Subject: [PATCH 5/5] fix(nri): admit a confirmed hold only on a current read-back Copilot 4812211330 on #1231 (4e3167ae). The commit stamp and in-flight check ran only when a hold ended without confirmation, so a refresh that replaced the binding between the worker's read and its use could still be admitted on a stale Confirmed answer. One current() check (same entry, not released, no commit since the stamp, no write in flight) now guards every hold exit that returns confirmations. A stale Confirmed read is re-read; at the deadline the create is refused. Co-Authored-By: Claude Opus 5.5 Docs-exempt: internal fix in the unreleased NRI start gate stack Signed-off-by: Matthias Bertschy --- .../integration/fu2_gate_test.go | 77 +++++++++++++++++++ pkg/sandboxpolicy/integration/podgate.go | 42 ++++++---- 2 files changed, 102 insertions(+), 17 deletions(-) diff --git a/pkg/sandboxpolicy/integration/fu2_gate_test.go b/pkg/sandboxpolicy/integration/fu2_gate_test.go index 4f7406b13f..087cb0caad 100644 --- a/pkg/sandboxpolicy/integration/fu2_gate_test.go +++ b/pkg/sandboxpolicy/integration/fu2_gate_test.go @@ -1038,3 +1038,80 @@ func TestFU2ReproveBusyGateStaysQueued(t *testing.T) { } } } + +// fu2StaleConfirmBackend commits the pod (as a refresh's bind returning), +// or starts a write of it and leaves it running, after the first +// read-backs (stale of them), once the read is done and before the hold +// uses it. +type fu2StaleConfirmBackend struct { + *fakeGateBackend + gate *podGate + stale int + start bool // start a write that stays running, instead of a commit + reads int + opened bool +} + +func (b *fu2StaleConfirmBackend) ConfirmPod(uid types.UID, cgroupID uint64, plan sandboxpolicy.Plan) []sandboxpolicy.PodSectionConfirmation { + res := b.fakeGateBackend.ConfirmPod(uid, cgroupID, plan) + b.reads++ + if b.reads <= b.stale { + pods := []sandboxpolicy.PodBinding{{PodUID: uid}} + if b.start { + if !b.opened { + b.gate.beginWrites(pods) + b.opened = true + } + } else { + b.gate.afterBind(pods, b.gate.releases) + } + } + return res +} + +// TestFU2ConfirmedHoldIsCurrent (PR #1231 Copilot 4812211330): a Confirmed +// read-back is admitted only while it is current. A commit that lands after +// the read and before the hold uses it makes the hold read again (admitted +// on the fresh read); one after every read, or a write still running, +// refuses at the deadline with no confirmations. +func TestFU2ConfirmedHoldIsCurrent(t *testing.T) { + for _, tc := range []struct { + name string + stale int + start bool + wantReads int // at least + admitted bool + }{ + {name: "current", wantReads: 1, admitted: true}, + {name: "a commit after the first read", stale: 1, wantReads: 2, admitted: true}, + {name: "a commit after every read", stale: 1 << 30, wantReads: 2}, + {name: "a write still running", stale: 1 << 30, start: true, wantReads: 2}, + } { + t.Run(tc.name, func(t *testing.T) { + b := &fu2StaleConfirmBackend{fakeGateBackend: newFakeGateBackend(), stale: tc.stale, start: tc.start} + g := newPodGate(t.Context(), b, nil) + b.gate = g + c := selected(sandboxpolicy.Seq{Config: 1, Input: 1}, gatePolicy("p1", api.ModeEnforce)) + if _, err := g.JoinAndMark(t.Context(), testSandbox("sb1"), c, soon()); err != nil { + t.Fatal(err) + } + confs, err := g.HoldUntilConfirmed(t.Context(), "pod-uid", "sb1", c, time.Now().Add(150*time.Millisecond)) + g.wait() + if b.opened { + b.gate.endWrites([]sandboxpolicy.PodBinding{{PodUID: "pod-uid"}}) + } + if b.count("ConfirmPod") < tc.wantReads { + t.Fatalf("%d read-backs, want at least %d", b.count("ConfirmPod"), tc.wantReads) + } + if tc.admitted { + if err != nil || len(confs) != 1 || confs[0].State != sandboxpolicy.PodSectionConfirmed { + t.Fatalf("hold: %+v %v, want Confirmed", confs, err) + } + return + } + if len(confs) != 0 || !errors.Is(err, errCommittedAfterRead) { + t.Fatalf("hold: %+v %v, want no confirmations and errCommittedAfterRead", confs, err) + } + }) + } +} diff --git a/pkg/sandboxpolicy/integration/podgate.go b/pkg/sandboxpolicy/integration/podgate.go index 7a1b2ad4ad..8b57c24195 100644 --- a/pkg/sandboxpolicy/integration/podgate.go +++ b/pkg/sandboxpolicy/integration/podgate.go @@ -564,15 +564,16 @@ func planKey(c sandboxpolicy.PodClassification) string { // HoldUntilConfirmed is the create hold: it moves the pod to its record's // plan's slot (PodGate.EnsurePodBound) and reads back each section against // the caller's own classification (PodGate.ConfirmPod), again every -// holdRetry, until every section is Confirmed or the deadline passes. It -// returns the last confirmations it read, with errWorkDeadline (joined with -// the last bind errors) when not every section was Confirmed by then; no -// confirmations, with errCommittedAfterRead, when a write that may change -// the pod's plan landed after that read (a refresh's bind, a mark or an -// unmark: gatePod.commits), one is still outstanding (podGate.writing: it -// may already have replaced the mark), or the pod was released meanwhile. -// The -// caller decides from the confirmations (a Strict create needs Confirmed, +// holdRetry, until every section is Confirmed or the deadline passes. A +// read-back is current while no write that may change the pod's plan (a +// refresh's bind, a mark or an unmark: gatePod.commits) landed after it, +// none is still outstanding (podGate.writing: it may already have replaced +// the mark), and the pod was not released. It returns an all-Confirmed +// read-back only while it is current, and reads again otherwise (PR #1231 +// Copilot 4812211330). At the deadline it returns the last read-back with +// errWorkDeadline (joined with the last bind errors), or none, with +// errCommittedAfterRead, when that read-back is not current. The caller +// decides from the confirmations (a Strict create needs Confirmed, // or Pending with Strict). func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandboxID string, c sandboxpolicy.PodClassification, deadline time.Time) ([]sandboxpolicy.PodSectionConfirmation, error) { if deadline.IsZero() { @@ -590,15 +591,19 @@ func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandbox // a write of the pod's plan landed after it (CodeRabbit #1176 // 4810415638): the caller refuses then. The window is the pause // between two reads (holdRetry) plus one job. + // current reports whether the last read-back is still the plan in + // force: no write of the pod's plan landed after it or is running, and + // the entry is the same, not released. Every return of a read-back + // checks it (PR #1231 Copilot 4812211330). + current := func() bool { + g.podMu.Lock() + defer g.podMu.Unlock() + return g.pods[uid] == stamp.entry && stamp.entry != nil && !stamp.entry.released && stamp.entry.commits == stamp.commits && g.writing[uid] == 0 + } unconfirmed := func(err error) ([]sandboxpolicy.PodSectionConfirmation, error) { errs := append([]error{err}, bindErrs...) - if last != nil { - g.podMu.Lock() - current := g.pods[uid] == stamp.entry && stamp.entry != nil && !stamp.entry.released && stamp.entry.commits == stamp.commits && g.writing[uid] == 0 - g.podMu.Unlock() - if !current { - return nil, errors.Join(append([]error{errCommittedAfterRead}, errs...)...) - } + if last != nil && !current() { + return nil, errors.Join(append([]error{errCommittedAfterRead}, errs...)...) } return last, errors.Join(errs...) } @@ -649,7 +654,10 @@ func (g *podGate) HoldUntilConfirmed(ctx context.Context, uid types.UID, sandbox bindErrs = append(bindErrs, replyError(r.Err)) } } - if len(last) > 0 && !slices.ContainsFunc(last, func(c sandboxpolicy.PodSectionConfirmation) bool { return c.State != sandboxpolicy.PodSectionConfirmed }) { + // Confirmed is admitted only while it is still current; otherwise + // it is read again after the pause, and at the deadline the hold + // refuses (unconfirmed). + if len(last) > 0 && !slices.ContainsFunc(last, func(c sandboxpolicy.PodSectionConfirmation) bool { return c.State != sandboxpolicy.PodSectionConfirmed }) && current() { return last, nil } wait := time.NewTimer(min(holdRetry, time.Until(deadline)))