From c7c7f0028ec94724d00fa1dbedd5402625998183 Mon Sep 17 00:00:00 2001 From: Jonas Wrede Date: Fri, 20 Nov 2026 07:47:59 +0000 Subject: [PATCH 1/6] ateworker-microvm: add opt-in privileged actors Add securityContext.privileged to ActorTemplate containers. A microvm worker runs such a container with all capabilities, no masked or read-only paths, a writable cgroup2 mount and all devices, so it can run a container engine like dockerd inside its guest. The VM stays the isolation boundary. Workers run privileged actors only when their WorkerPool sets sandboxClasses[].allowPrivilegedActors (microvm only, enforced by CEL), which the controller passes as --allow-privileged-actors. Other microvm workers and gVisor workers fail the actor with FailedPrecondition. ateapi and atelet reject capabilities set next to privileged. Signed-off-by: Jonas Wrede Co-authored-by: Cursor --- api/ateapi/v1/ateapi.pb.go | 29 ++++++++++-- api/ateapi/v1/ateapi.proto | 14 ++++++ api/infra/k8s/ate/v1/workerpool_types.go | 13 ++++++ .../k8s/ate/v1/workerpool_validation_test.go | 14 ++++++ api/infra/k8s/ate/v1/zz_generated.deepcopy.go | 5 ++ .../internal/apivalidation/actor_template.go | 6 +++ .../apivalidation/actor_template_test.go | 11 +++++ .../apivalidation/zz_generated.validation.go | 32 +++++++++++++ .../internal/controlapi/workload_spec.go | 11 +++-- .../internal/controllers/workerpool_apply.go | 17 +++++++ .../controllers/workerpool_apply_test.go | 23 ++++++++++ .../internal/apivalidation/workloadspec.go | 6 +++ .../apivalidation/zz_generated.validation.go | 32 +++++++++++++ cmd/atelet/main.go | 3 +- cmd/atelet/oci.go | 17 +++++++ cmd/atelet/oci_test.go | 15 ++++++ cmd/ateworker-gvisor/runsc.go | 7 +++ cmd/ateworker-gvisor/runsc_test.go | 19 ++++++++ cmd/ateworker-microvm/main.go | 45 ++++++++++-------- cmd/ateworker-microvm/run.go | 8 +++- cmd/ateworker-microvm/run_test.go | 26 +++++++++++ .../zz_generated.validation.go | 1 + internal/ocispec/microvm.go | 40 ++++++++++++++++ internal/ocispec/microvm_test.go | 46 +++++++++++++++++++ internal/proto/ateletpb/atelet.pb.go | 21 +++++++-- internal/proto/ateletpb/atelet.proto | 6 +++ internal/proto/ateworkerpb/ateworker.pb.go | 21 +++++++-- internal/proto/ateworkerpb/ateworker.proto | 6 +++ internal/resources/validate.go | 16 +++++++ .../generated/ate.dev_workerpools.yaml | 15 ++++++ 30 files changed, 491 insertions(+), 34 deletions(-) diff --git a/api/ateapi/v1/ateapi.pb.go b/api/ateapi/v1/ateapi.pb.go index d63c010fb1..0f425ac185 100644 --- a/api/ateapi/v1/ateapi.pb.go +++ b/api/ateapi/v1/ateapi.pb.go @@ -3330,6 +3330,7 @@ type Container struct { // the default capability set. // // +k8s:optional + // +k8s:customValidation # capabilities must be unset when privileged SecurityContext *SecurityContext `protobuf:"bytes,8,opt,name=security_context,json=securityContext,proto3" json:"security_context,omitempty"` // resources carries this container's compute limits, enforced inside the // actor's sandbox. A limit of 0 leaves that resource unlimited. @@ -3438,9 +3439,21 @@ func (x *Container) GetResources() *ResourceRequirements { type SecurityContext struct { state protoimpl.MessageState `protogen:"open.v1"` // capabilities adjusts the Linux capabilities of the container's process. + // Must be unset when privileged is true. // // +k8s:optional - Capabilities *Capabilities `protobuf:"bytes,1,opt,name=capabilities,proto3" json:"capabilities,omitempty"` + Capabilities *Capabilities `protobuf:"bytes,1,opt,name=capabilities,proto3" json:"capabilities,omitempty"` + // privileged runs the container with every Linux capability, unmasked and + // writable /proc and /sys, a writable cgroup2 hierarchy, and access to all + // devices of the sandbox, so that it can run a container engine such as + // dockerd. Only the microvm sandbox class honors it: the actor then owns a + // whole guest kernel, and the VM, not the in-guest container, is the + // isolation boundary. A worker runs privileged containers only when its + // WorkerPool sets sandboxClasses[].allowPrivilegedActors; every other worker + // fails the actor rather than run it unprivileged. + // + // +k8s:optional + Privileged bool `protobuf:"varint,2,opt,name=privileged,proto3" json:"privileged,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -3482,6 +3495,13 @@ func (x *SecurityContext) GetCapabilities() *Capabilities { return nil } +func (x *SecurityContext) GetPrivileged() bool { + if x != nil { + return x.Privileged + } + return false +} + // Capabilities adjusts a container's Linux capabilities relative to the // default set. Drop applies first, then add, so a capability in both is // granted. Capabilities are named without the "CAP_" prefix; "ALL" in drop @@ -10167,9 +10187,12 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\fwakeup_probe\x18\x06 \x01(\v2 .substrate.ateapi.v1.WakeupProbeR\vwakeupProbe\x12E\n" + "\rvolume_mounts\x18\a \x03(\v2 .substrate.ateapi.v1.VolumeMountR\fvolumeMounts\x12O\n" + "\x10security_context\x18\b \x01(\v2$.substrate.ateapi.v1.SecurityContextR\x0fsecurityContext\x12G\n" + - "\tresources\x18\t \x01(\v2).substrate.ateapi.v1.ResourceRequirementsR\tresources\"X\n" + + "\tresources\x18\t \x01(\v2).substrate.ateapi.v1.ResourceRequirementsR\tresources\"x\n" + "\x0fSecurityContext\x12E\n" + - "\fcapabilities\x18\x01 \x01(\v2!.substrate.ateapi.v1.CapabilitiesR\fcapabilities\"4\n" + + "\fcapabilities\x18\x01 \x01(\v2!.substrate.ateapi.v1.CapabilitiesR\fcapabilities\x12\x1e\n" + + "\n" + + "privileged\x18\x02 \x01(\bR\n" + + "privileged\"4\n" + "\fCapabilities\x12\x10\n" + "\x03add\x18\x01 \x03(\tR\x03add\x12\x12\n" + "\x04drop\x18\x02 \x03(\tR\x04drop\"7\n" + diff --git a/api/ateapi/v1/ateapi.proto b/api/ateapi/v1/ateapi.proto index 51ed7d1e32..d907aea32d 100644 --- a/api/ateapi/v1/ateapi.proto +++ b/api/ateapi/v1/ateapi.proto @@ -1386,6 +1386,7 @@ message Container { // the default capability set. // // +k8s:optional + // +k8s:customValidation # capabilities must be unset when privileged SecurityContext security_context = 8; // resources carries this container's compute limits, enforced inside the @@ -1399,9 +1400,22 @@ message Container { // modeling a subset of the Kubernetes container securityContext. message SecurityContext { // capabilities adjusts the Linux capabilities of the container's process. + // Must be unset when privileged is true. // // +k8s:optional Capabilities capabilities = 1; + + // privileged runs the container with every Linux capability, unmasked and + // writable /proc and /sys, a writable cgroup2 hierarchy, and access to all + // devices of the sandbox, so that it can run a container engine such as + // dockerd. Only the microvm sandbox class honors it: the actor then owns a + // whole guest kernel, and the VM, not the in-guest container, is the + // isolation boundary. A worker runs privileged containers only when its + // WorkerPool sets sandboxClasses[].allowPrivilegedActors; every other worker + // fails the actor rather than run it unprivileged. + // + // +k8s:optional + bool privileged = 2; } // Capabilities adjusts a container's Linux capabilities relative to the diff --git a/api/infra/k8s/ate/v1/workerpool_types.go b/api/infra/k8s/ate/v1/workerpool_types.go index f619b389c3..b86272697b 100644 --- a/api/infra/k8s/ate/v1/workerpool_types.go +++ b/api/infra/k8s/ate/v1/workerpool_types.go @@ -114,6 +114,7 @@ type WorkerPoolSpec struct { } // WorkerPoolSandboxClass is one sandbox runtime family a WorkerPool runs. +// +kubebuilder:validation:XValidation:rule="!has(self.allowPrivilegedActors) || !self.allowPrivilegedActors || self.name == 'microvm'",message="allowPrivilegedActors requires the microvm sandbox class" type WorkerPoolSandboxClass struct { // name selects the sandbox runtime family, which drives the worker pod // shape (KVM/vhost device mounts and node placement). The concrete binary @@ -132,6 +133,18 @@ type WorkerPoolSandboxClass struct { // // +optional ConfigRef *SandboxConfigReference `json:"configRef,omitempty"` + + // allowPrivilegedActors lets this pool's workers run containers whose + // ActorTemplate sets securityContext.privileged, for example to run a + // container engine inside the actor. Each such actor owns a whole guest + // kernel, so the VM stays the isolation boundary, but the workload gets + // full privilege inside it and can drive every guest-to-host interface + // (virtio devices, the guest agent channel) directly. Enable it only on + // pools meant for that, ideally on dedicated nodes. Only the microvm + // class supports it. Workers of pools without it fail privileged actors. + // + // +optional + AllowPrivilegedActors *bool `json:"allowPrivilegedActors,omitempty"` } // SandboxConfigReference names a cluster-scoped SandboxConfig. diff --git a/api/infra/k8s/ate/v1/workerpool_validation_test.go b/api/infra/k8s/ate/v1/workerpool_validation_test.go index 9c4c6e8a6c..dc5a966ea2 100644 --- a/api/infra/k8s/ate/v1/workerpool_validation_test.go +++ b/api/infra/k8s/ate/v1/workerpool_validation_test.go @@ -23,6 +23,7 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/ptr" ) const gpuResourceName = corev1.ResourceName("nvidia.com/gpu") @@ -119,6 +120,19 @@ func TestWorkerPoolValidation(t *testing.T) { }, wantErr: true, errMsg: "spec.sandboxClasses[0].name: Unsupported value", + }, { + name: "microvm pool allows privileged actors", + mutate: func(wp *WorkerPool) { + wp.Spec.SandboxClasses = []WorkerPoolSandboxClass{{Name: SandboxClassMicroVM, AllowPrivilegedActors: ptr.To(true)}} + }, + wantErr: false, + }, { + name: "gvisor pool cannot allow privileged actors", + mutate: func(wp *WorkerPool) { + wp.Spec.SandboxClasses = []WorkerPoolSandboxClass{{Name: SandboxClassGvisor, AllowPrivilegedActors: ptr.To(true)}} + }, + wantErr: true, + errMsg: "allowPrivilegedActors requires the microvm sandbox class", }, { name: "sandboxClass with configRef", mutate: func(wp *WorkerPool) { diff --git a/api/infra/k8s/ate/v1/zz_generated.deepcopy.go b/api/infra/k8s/ate/v1/zz_generated.deepcopy.go index 7c768dfe54..4ec21d6b79 100644 --- a/api/infra/k8s/ate/v1/zz_generated.deepcopy.go +++ b/api/infra/k8s/ate/v1/zz_generated.deepcopy.go @@ -390,6 +390,11 @@ func (in *WorkerPoolSandboxClass) DeepCopyInto(out *WorkerPoolSandboxClass) { *out = new(SandboxConfigReference) **out = **in } + if in.AllowPrivilegedActors != nil { + in, out := &in.AllowPrivilegedActors, &out.AllowPrivilegedActors + *out = new(bool) + **out = **in + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkerPoolSandboxClass. diff --git a/cmd/ateapi/internal/apivalidation/actor_template.go b/cmd/ateapi/internal/apivalidation/actor_template.go index 6791331d7e..8ca3230ba1 100644 --- a/cmd/ateapi/internal/apivalidation/actor_template.go +++ b/cmd/ateapi/internal/apivalidation/actor_template.go @@ -184,3 +184,9 @@ func ValidateCustom_Capabilities_Add(_ context.Context, _ operation.Operation, f func ValidateCustom_Capabilities_Drop(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []string) field.ErrorList { return resources.ValidateDropCapabilities(fldPath, value) } + +// ValidateCustom_Container_SecurityContext rejects capabilities next to +// privileged: a privileged container gets every capability. +func ValidateCustom_Container_SecurityContext(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *ateapi.SecurityContext) field.ErrorList { + return resources.ValidatePrivilegedSecurityContext(fldPath, value.GetPrivileged(), value.GetCapabilities().GetAdd(), value.GetCapabilities().GetDrop()) +} diff --git a/cmd/ateapi/internal/apivalidation/actor_template_test.go b/cmd/ateapi/internal/apivalidation/actor_template_test.go index 0c32ef3440..1b50387928 100644 --- a/cmd/ateapi/internal/apivalidation/actor_template_test.go +++ b/cmd/ateapi/internal/apivalidation/actor_template_test.go @@ -694,6 +694,17 @@ func TestValidateActorTemplate(t *testing.T) { Drop: []string{"ALL"}, }} }, + }, { + name: "privileged container", + mutate: func(tmpl *ateapi.ActorTemplate) { + tmpl.Containers[0].SecurityContext = &ateapi.SecurityContext{Privileged: true} + }, + }, { + name: "privileged rejects capabilities", + mutate: func(tmpl *ateapi.ActorTemplate) { + tmpl.Containers[0].SecurityContext = &ateapi.SecurityContext{Privileged: true, Capabilities: &ateapi.Capabilities{Drop: []string{"ALL"}}} + }, + want: field.ErrorList{field.Invalid(field.NewPath("containers").Index(0).Child("security_context", "capabilities"), nil, "")}, }, { name: "capabilities add rejects ALL", mutate: func(tmpl *ateapi.ActorTemplate) { diff --git a/cmd/ateapi/internal/apivalidation/zz_generated.validation.go b/cmd/ateapi/internal/apivalidation/zz_generated.validation.go index 4719d8d4f4..80c7844c5d 100644 --- a/cmd/ateapi/internal/apivalidation/zz_generated.validation.go +++ b/cmd/ateapi/internal/apivalidation/zz_generated.validation.go @@ -2100,6 +2100,10 @@ func Validate_Container( if earlyReturn { return // do not proceed } + // custom validation + if e := ValidateCustom_Container_SecurityContext(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } // call the type's validation function errs = append(errs, Validate_SecurityContext(ctx, op, fldPath, obj, oldObj)...) return @@ -7691,6 +7695,34 @@ func Validate_SecurityContext( errs = append(errs, fn(fldPath.Child("capabilities"), obj.Capabilities, oldVal, oldObj != nil)...) } + { // field v1.SecurityContext.Privileged + fn := func( + fldPath *field.Path, + obj, oldObj *bool, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.SecurityContext) *bool { + return &oldObj.Privileged + }) + errs = append(errs, fn(fldPath.Child("privileged"), &obj.Privileged, oldVal, oldObj != nil)...) + } + return errs } diff --git a/cmd/ateapi/internal/controlapi/workload_spec.go b/cmd/ateapi/internal/controlapi/workload_spec.go index 57e1e5986d..9508da45ed 100644 --- a/cmd/ateapi/internal/controlapi/workload_spec.go +++ b/cmd/ateapi/internal/controlapi/workload_spec.go @@ -224,13 +224,16 @@ func toAteletWakeupProbe(in *ateapi.WakeupProbe) *ateletpb.WakeupProbe { // so containers that set no security settings stay unchanged on the wire. func toAteletSecurityContext(in *ateapi.SecurityContext) *ateletpb.SecurityContext { caps := in.GetCapabilities() - if caps == nil || (len(caps.GetAdd()) == 0 && len(caps.GetDrop()) == 0) { + hasCaps := caps != nil && (len(caps.GetAdd()) > 0 || len(caps.GetDrop()) > 0) + if !hasCaps && !in.GetPrivileged() { return nil } - return &ateletpb.SecurityContext{ - Capabilities: &ateletpb.Capabilities{ + out := &ateletpb.SecurityContext{Privileged: in.GetPrivileged()} + if hasCaps { + out.Capabilities = &ateletpb.Capabilities{ Add: caps.GetAdd(), Drop: caps.GetDrop(), - }, + } } + return out } diff --git a/cmd/atecontroller/internal/controllers/workerpool_apply.go b/cmd/atecontroller/internal/controllers/workerpool_apply.go index 1244d6498a..881a4d248f 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_apply.go +++ b/cmd/atecontroller/internal/controllers/workerpool_apply.go @@ -25,6 +25,7 @@ import ( appsv1ac "k8s.io/client-go/applyconfigurations/apps/v1" corev1ac "k8s.io/client-go/applyconfigurations/core/v1" metav1ac "k8s.io/client-go/applyconfigurations/meta/v1" + "k8s.io/utils/ptr" atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" "go.ate.dev/substrate/internal/deviceplugin" @@ -167,6 +168,9 @@ func buildDeploymentApplyConfig(wp *atev1.WorkerPool, otel workerOTelSettings, s } previewArg := "--preview=" + strings.Join(enabledGates(), ",") args = append(args, previewArg) + if allowsPrivilegedActors(wp) { + args = append(args, "--allow-privileged-actors") + } containerAC := corev1ac.Container(). WithName("worker"). @@ -696,3 +700,16 @@ func nodeSelectorRequirementToApply(req *corev1.NodeSelectorRequirement) *corev1 } return ac } + +// allowsPrivilegedActors reports whether the pool opts its microvm workers in +// to privileged actors. The CRD rejects the field on other classes; this +// checks the class again so a stale or hand-edited object cannot pass the +// flag to a gVisor worker. +func allowsPrivilegedActors(wp *atev1.WorkerPool) bool { + for _, c := range wp.Spec.SandboxClasses { + if c.Name == atev1.SandboxClassMicroVM && ptr.Deref(c.AllowPrivilegedActors, false) { + return true + } + } + return false +} diff --git a/cmd/atecontroller/internal/controllers/workerpool_apply_test.go b/cmd/atecontroller/internal/controllers/workerpool_apply_test.go index 2ae55a2584..6f8f5676fc 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_apply_test.go +++ b/cmd/atecontroller/internal/controllers/workerpool_apply_test.go @@ -16,6 +16,7 @@ package controllers import ( "regexp" + "slices" "strings" "testing" @@ -1176,3 +1177,25 @@ func TestBuildDeploymentPreview(t *testing.T) { }) } } + +func TestBuildDeploymentAllowPrivilegedActors(t *testing.T) { + for _, tc := range []struct { + name string + class atev1.WorkerPoolSandboxClass + want bool + }{ + {"microvm opted in", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassMicroVM, AllowPrivilegedActors: ptr.To(true)}, true}, + {"microvm default", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassMicroVM}, false}, + {"gvisor never", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassGvisor, AllowPrivilegedActors: ptr.To(true)}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + wp := testWorkerPoolApplyConfig(nil) + wp.Spec.SandboxClasses = []atev1.WorkerPoolSandboxClass{tc.class} + c := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + Spec.Template.Spec.Containers[0] + if got := slices.Contains(c.Args, "--allow-privileged-actors"); got != tc.want { + t.Errorf("--allow-privileged-actors in args = %v, want %v (args %v)", got, tc.want, c.Args) + } + }) + } +} diff --git a/cmd/atelet/internal/apivalidation/workloadspec.go b/cmd/atelet/internal/apivalidation/workloadspec.go index 6d4fc67536..8d2383d5fa 100644 --- a/cmd/atelet/internal/apivalidation/workloadspec.go +++ b/cmd/atelet/internal/apivalidation/workloadspec.go @@ -151,3 +151,9 @@ func ValidateCustom_SystemInfoVolumeSource_DataSources(_ context.Context, _ oper } return errs } + +// ValidateCustom_Container_SecurityContext rejects capabilities next to +// privileged, as ateapi does. +func ValidateCustom_Container_SecurityContext(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *ateletpb.SecurityContext) field.ErrorList { + return resources.ValidatePrivilegedSecurityContext(fldPath, value.GetPrivileged(), value.GetCapabilities().GetAdd(), value.GetCapabilities().GetDrop()) +} diff --git a/cmd/atelet/internal/apivalidation/zz_generated.validation.go b/cmd/atelet/internal/apivalidation/zz_generated.validation.go index f315f19709..f67fcddfc2 100644 --- a/cmd/atelet/internal/apivalidation/zz_generated.validation.go +++ b/cmd/atelet/internal/apivalidation/zz_generated.validation.go @@ -996,6 +996,10 @@ func Validate_Container( if earlyReturn { return // do not proceed } + // custom validation + if e := ValidateCustom_Container_SecurityContext(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } // call the type's validation function errs = append(errs, Validate_SecurityContext(ctx, op, fldPath, obj, oldObj)...) return @@ -3265,6 +3269,34 @@ func Validate_SecurityContext( errs = append(errs, fn(fldPath.Child("capabilities"), obj.Capabilities, oldVal, oldObj != nil)...) } + { // field ateletpb.SecurityContext.Privileged + fn := func( + fldPath *field.Path, + obj, oldObj *bool, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ateletpb.SecurityContext) *bool { + return &oldObj.Privileged + }) + errs = append(errs, fn(fldPath.Child("privileged"), &obj.Privileged, oldVal, oldObj != nil)...) + } + return errs } diff --git a/cmd/atelet/main.go b/cmd/atelet/main.go index 42d1e4d75b..994c62c04c 100644 --- a/cmd/atelet/main.go +++ b/cmd/atelet/main.go @@ -2275,7 +2275,8 @@ func (s *Atelet) prepareOCIBundles( containerSpecs[i] = &ateworkerpb.ContainerSpec{ Args: args, Env: resolveActorEnv(&img.Config, envs), - Capabilities: resolveCapabilities(ctr.GetSecurityContext().GetCapabilities()), + Capabilities: resolveContainerCapabilities(ctr.GetSecurityContext()), + Privileged: ctr.GetSecurityContext().GetPrivileged(), Resources: toAteworkerResources(ctr.GetResources()), User: user, Cwd: cwd, diff --git a/cmd/atelet/oci.go b/cmd/atelet/oci.go index c046a1791e..1a4dbb0096 100644 --- a/cmd/atelet/oci.go +++ b/cmd/atelet/oci.go @@ -32,6 +32,7 @@ import ( "go.ate.dev/substrate/internal/imagecache" "go.ate.dev/substrate/internal/proto/ateletpb" "go.ate.dev/substrate/internal/proto/ateworkerpb" + "go.ate.dev/substrate/internal/resources" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "golang.org/x/sync/errgroup" @@ -80,6 +81,22 @@ func resolveCapabilities(caps *ateletpb.Capabilities) []string { return out } +// resolveContainerCapabilities is resolveCapabilities, except that a +// privileged container gets every capability. Whether the worker may run it +// privileged at all is the worker's decision (see ateworker-microvm's +// --allow-privileged-actors). +func resolveContainerCapabilities(sc *ateletpb.SecurityContext) []string { + if !sc.GetPrivileged() { + return resolveCapabilities(sc.GetCapabilities()) + } + all := resources.AllLinuxCapabilities() + out := make([]string, len(all)) + for i, c := range all { + out[i] = "CAP_" + c + } + return out +} + // prepareOCIDirectory pulls the container's image and writes the overlay spec // the worker composes its rootfs from. It returns the image and the process's // working directory, which the worker creates through the overlay. diff --git a/cmd/atelet/oci_test.go b/cmd/atelet/oci_test.go index 8f9006e86e..2c72961feb 100644 --- a/cmd/atelet/oci_test.go +++ b/cmd/atelet/oci_test.go @@ -300,3 +300,18 @@ func TestResolveCapabilities(t *testing.T) { }) } } + +func TestResolveContainerCapabilities(t *testing.T) { + if got := resolveContainerCapabilities(nil); !slices.Equal(got, wantDefaultCapabilities) { + t.Errorf("unset securityContext = %v, want the default set %v", got, wantDefaultCapabilities) + } + got := resolveContainerCapabilities(&ateletpb.SecurityContext{Privileged: true}) + for _, c := range []string{"CAP_SYS_ADMIN", "CAP_NET_ADMIN", "CAP_MKNOD", "CAP_CHECKPOINT_RESTORE"} { + if !slices.Contains(got, c) { + t.Errorf("privileged capabilities %v lack %s", got, c) + } + } + if !slices.IsSorted(got) { + t.Errorf("privileged capabilities are not sorted: %v", got) + } +} diff --git a/cmd/ateworker-gvisor/runsc.go b/cmd/ateworker-gvisor/runsc.go index 0cef2a156b..e39ceeff6e 100644 --- a/cmd/ateworker-gvisor/runsc.go +++ b/cmd/ateworker-gvisor/runsc.go @@ -31,6 +31,8 @@ import ( "go.ate.dev/substrate/internal/ocispec" "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/sizing" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) type runsc struct { @@ -113,6 +115,11 @@ func (r *runsc) writeSpec(containerName string) error { if i < 0 { return fmt.Errorf("container %q is not in the workload spec", containerName) } + if r.containers[i].GetContainerSpec().GetPrivileged() { + // The privileged shape relies on a VM boundary; gVisor shares the + // host kernel through runsc, so it never runs one. + return status.Errorf(codes.FailedPrecondition, "container %q is privileged; only microvm workers run privileged containers", containerName) + } spec = ocispec.Build(ocispec.Options{ActorUID: r.actorUID, ActorDirs: r.actorDirs, Container: r.containers[i]}) } ocispec.ShapeGVisor(spec, ocispec.GVisorOptions{ diff --git a/cmd/ateworker-gvisor/runsc_test.go b/cmd/ateworker-gvisor/runsc_test.go index 9791c31992..9b06c8c774 100644 --- a/cmd/ateworker-gvisor/runsc_test.go +++ b/cmd/ateworker-gvisor/runsc_test.go @@ -28,6 +28,7 @@ import ( "github.com/opencontainers/runtime-spec/specs-go" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "go.ate.dev/substrate/internal/actorlock" "go.ate.dev/substrate/internal/apierror" @@ -405,3 +406,21 @@ func TestRestoreWorkloadRejectsEmptyRestoreDir(t *testing.T) { }) } } + +// gVisor never runs a privileged container: the privileged shape relies on a +// VM boundary. +func TestWriteSpecRejectsPrivileged(t *testing.T) { + root := t.TempDir() + actorDirs := &ateworkerpb.ActorDirs{RootDir: root, OciBundleDir: filepath.Join(root, "bundles")} + if err := os.MkdirAll(ociBundlePath(actorDirs, "app"), 0o700); err != nil { + t.Fatal(err) + } + r := &runsc{ + actorUID: "uid-a", + actorDirs: actorDirs, + containers: []*ateworkerpb.Container{{Name: "app", ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}, Privileged: true}}}, + } + if err := r.writeSpec("app"); status.Code(err) != codes.FailedPrecondition { + t.Errorf("writeSpec(app) = %v, want FailedPrecondition", err) + } +} diff --git a/cmd/ateworker-microvm/main.go b/cmd/ateworker-microvm/main.go index 845f26d006..df45fcf504 100644 --- a/cmd/ateworker-microvm/main.go +++ b/cmd/ateworker-microvm/main.go @@ -66,13 +66,15 @@ import ( ) var ( - podUID = pflag.String("pod-uid", "", "The UID of the current pod") - podIPs = pflag.String("pod-ips", "", "The comma-separated IPs of the current pod") - chBinary = pflag.String("cloud-hypervisor-binary", "cloud-hypervisor", "Path to the cloud-hypervisor binary (used to relaunch on restore).") - guestDebug = pflag.Bool("guest-debug", false, "enable guest debugging (agent debug logs, debug console, and early serial console)") - showVersion = pflag.Bool("version", false, "Print version and exit.") - logLevelFlag = pflag.String("log-level", "info", "Minimum log level: debug, info, warn, or error.") - previewFlags = pflag.StringSlice("preview", nil, "Preview gates to enable.") + podUID = pflag.String("pod-uid", "", "The UID of the current pod") + podIPs = pflag.String("pod-ips", "", "The comma-separated IPs of the current pod") + chBinary = pflag.String("cloud-hypervisor-binary", "cloud-hypervisor", "Path to the cloud-hypervisor binary (used to relaunch on restore).") + guestDebug = pflag.Bool("guest-debug", false, "enable guest debugging (agent debug logs, debug console, and early serial console)") + // Set by the WorkerPool controller from sandboxClasses[].allowPrivilegedActors. + allowPrivilegedActors = pflag.Bool("allow-privileged-actors", false, "Run containers whose template sets securityContext.privileged. Without it the worker fails such actors.") + showVersion = pflag.Bool("version", false, "Print version and exit.") + logLevelFlag = pflag.String("log-level", "info", "Minimum log level: debug, info, warn, or error.") + previewFlags = pflag.StringSlice("preview", nil, "Preview gates to enable.") otlpRelaySocket = pflag.String("otlp-relay-socket", nodepath.AteletOTLPSocketPath(), "Unix socket of atelet's OTLP relay to export telemetry through, keeping it off the pod network. Empty, or absent at startup, exports directly to OTEL_EXPORTER_OTLP_ENDPOINT instead.") @@ -362,6 +364,10 @@ const ( type AteWorkerService struct { ateworkerpb.UnimplementedWorkerServer + // allowPrivilegedActors is --allow-privileged-actors: whether containers + // with securityContext.privileged may run here. + allowPrivilegedActors bool + // Serializes lifecycle RPCs per actor. locks *actorlock.Locks // Tracks lifecycle RPCs for shutdown cancellation and draining. @@ -422,18 +428,19 @@ var _ ateworkerpb.WorkerServer = (*AteWorkerService)(nil) // NewService creates a new AteWorkerService. func NewService(podUID, chBinary string, guestDebug bool, maxActors int, tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, bootID string) *AteWorkerService { s := &AteWorkerService{ - locks: actorlock.New(), - inFlight: actorlock.NewInFlight(), - actors: map[string]*hostedActor{}, - guestSlots: make(chan struct{}, statsFanOut), - maxActors: maxActors, - podUID: podUID, - chBinary: chBinary, - guestDebug: guestDebug, - snapshotWrites: make(chan struct{}, snapshotWriteSlots), - tunnel: tunnel, - actorLogger: actorLogger, - bootID: bootID, + allowPrivilegedActors: *allowPrivilegedActors, + locks: actorlock.New(), + inFlight: actorlock.NewInFlight(), + actors: map[string]*hostedActor{}, + guestSlots: make(chan struct{}, statsFanOut), + maxActors: maxActors, + podUID: podUID, + chBinary: chBinary, + guestDebug: guestDebug, + snapshotWrites: make(chan struct{}, snapshotWriteSlots), + tunnel: tunnel, + actorLogger: actorLogger, + bootID: bootID, } s.borrow = &memborrow.Ledger{Unbooked: s.unbookedMemory} return s diff --git a/cmd/ateworker-microvm/run.go b/cmd/ateworker-microvm/run.go index 058849dd20..0a59fc229f 100644 --- a/cmd/ateworker-microvm/run.go +++ b/cmd/ateworker-microvm/run.go @@ -48,6 +48,8 @@ import ( "go.ate.dev/substrate/internal/sizing" "go.ate.dev/substrate/internal/wakeupprobe" "golang.org/x/sys/unix" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // runningActor holds the live state for one actor's micro-VM. ateworker owns the @@ -653,8 +655,12 @@ func (s *AteWorkerService) buildActorContainers(actorUID string, actorDirs *atew for i, c := range containers { cn := c.GetName() bundle := ociBundlePath(actorDirs, cn) + privileged := c.GetContainerSpec().GetPrivileged() + if privileged && !s.allowPrivilegedActors { + return nil, status.Errorf(codes.FailedPrecondition, "container %q is privileged, but this worker does not allow privileged actors (WorkerPool sandboxClasses[].allowPrivilegedActors)", cn) + } spec := ocispec.Build(ocispec.Options{ActorUID: actorUID, ActorDirs: actorDirs, Container: c}) - if err := ocispec.ShapeMicroVM(spec, ocispec.MicroVMOptions{ActorDirs: actorDirs, ContainerName: cn}); err != nil { + if err := ocispec.ShapeMicroVM(spec, ocispec.MicroVMOptions{ActorDirs: actorDirs, ContainerName: cn, Privileged: privileged}); err != nil { return nil, fmt.Errorf("while shaping the OCI spec for %q: %w", cn, err) } // Compose the bundle rootfs from the node's cached image layers (an diff --git a/cmd/ateworker-microvm/run_test.go b/cmd/ateworker-microvm/run_test.go index 5863175d5d..a33f3fb8ae 100644 --- a/cmd/ateworker-microvm/run_test.go +++ b/cmd/ateworker-microvm/run_test.go @@ -31,6 +31,8 @@ import ( "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" "go.ate.dev/substrate/internal/proto/ateworkerpb" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // A vsock socket that has gone missing means cloud-hypervisor stopped the VM @@ -216,6 +218,30 @@ func TestWorkloadIDs(t *testing.T) { } } +// A privileged container runs only on a worker started with +// --allow-privileged-actors; any other worker fails the actor rather than run +// it unprivileged. +func TestBuildActorContainersPrivileged(t *testing.T) { + dirs := &ateworkerpb.ActorDirs{OciBundleDir: t.TempDir()} + if err := os.MkdirAll(filepath.Join(ociBundlePath(dirs, "main"), "rootfs"), 0o755); err != nil { + t.Fatal(err) + } + containers := []*ateworkerpb.Container{{Name: "main", ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}, Privileged: true}}} + + _, err := (&AteWorkerService{}).buildActorContainers("uid", dirs, containers) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("buildActorContainers() without allowPrivilegedActors = %v, want FailedPrecondition", err) + } + + ctrs, err := (&AteWorkerService{allowPrivilegedActors: true}).buildActorContainers("uid", dirs, containers) + if err != nil { + t.Fatalf("buildActorContainers() with allowPrivilegedActors = %v", err) + } + if ctrs[0].spec.Linux.MaskedPaths != nil { + t.Errorf("privileged spec MaskedPaths = %v, want none", ctrs[0].spec.Linux.MaskedPaths) + } +} + func TestKernelParamsDebugConsole(t *testing.T) { prodParams := (&AteWorkerService{guestDebug: false}).kernelParams() for _, forbidden := range []string{"agent.debug_console", "agent.debug_console_vport", "1026"} { diff --git a/internal/ateworkervalidation/zz_generated.validation.go b/internal/ateworkervalidation/zz_generated.validation.go index f39e3ba6d1..c16d0e0d3f 100644 --- a/internal/ateworkervalidation/zz_generated.validation.go +++ b/internal/ateworkervalidation/zz_generated.validation.go @@ -924,6 +924,7 @@ func Validate_ContainerSpec( // field ateworkerpb.ContainerSpec.User has no validation // field ateworkerpb.ContainerSpec.Cwd has no validation + // field ateworkerpb.ContainerSpec.Privileged has no validation return errs } diff --git a/internal/ocispec/microvm.go b/internal/ocispec/microvm.go index 311cf94a61..5cf03168a2 100644 --- a/internal/ocispec/microvm.go +++ b/internal/ocispec/microvm.go @@ -55,6 +55,12 @@ type MicroVMOptions struct { // staged into the share. ActorDirs *ateworkerpb.ActorDirs ContainerName string + // Privileged skips the in-guest hardening below (masked and read-only + // paths, read-only /sys, the device allowlist) and gives the container a + // writable cgroup2 hierarchy, so it can run a container engine. The guest + // kernel stays the boundary: the actor owns its whole VM. The caller must + // check that the worker allows privileged actors. + Privileged bool } // ShapeMicroVM repoints volume bind mounts to guest share paths, applies @@ -81,6 +87,10 @@ func ShapeMicroVM(spec *specs.Spec, o MicroVMOptions) error { } } } + if o.Privileged { + shapePrivileged(spec) + return nil + } // Mask each directory with a read-only tmpfs, as runc's maskDir does. // https://github.com/opencontainers/runc/blob/7d36b05953ebb377900a0a565d8b0754e464be0b/libcontainer/rootfs_linux.go#L1338-L1350 for _, dir := range guestMaskedDirPaths(runtime.GOARCH) { @@ -112,6 +122,36 @@ func ShapeMicroVM(spec *specs.Spec, o MicroVMOptions) error { return nil } +// shapePrivileged finishes the spec of a privileged guest container, the +// equivalent of a privileged container under containerd inside the VM: no +// masked or read-only paths, read-write /sys, a read-write cgroup2 mount, and +// every guest device. Capabilities already hold the full set (atelet sets them +// with Privileged). The sysctls ShapeMicroVM sets for unprivileged containers +// are left out: a privileged container can set them itself, and a container +// engine inside expects the kernel defaults. +func shapePrivileged(spec *specs.Spec) { + for i := range spec.Mounts { + m := &spec.Mounts[i] + if m.Destination == "/sys" && m.Type == "sysfs" { + m.Options = slices.DeleteFunc(slices.Clone(m.Options), func(o string) bool { return o == "ro" }) + m.Options = append(m.Options, "rw") + } + } + spec.Mounts = append(spec.Mounts, specs.Mount{ + Destination: "/sys/fs/cgroup", + Type: "cgroup2", + Source: "cgroup2", + Options: []string{"nosuid", "noexec", "nodev", "rw"}, + }) + spec.Linux.MaskedPaths = nil + spec.Linux.ReadonlyPaths = nil + resources := mergeKataResources(spec.Linux.Resources) + // A container engine creates device nodes for its own containers + // (/dev/null, /dev/net/tun, ...), so allow every guest device. + resources.Devices = []specs.LinuxDeviceCgroup{{Allow: true, Access: "rwm"}} + spec.Linux.Resources = resources +} + // mergeKataResources fills in the kata defaults that the caller's spec leaves // unset. The caller's values win, and anything it sets that has no default is // carried through untouched — the defaults supply the device allowlist and CPU diff --git a/internal/ocispec/microvm_test.go b/internal/ocispec/microvm_test.go index 63754fc7c4..02fb7021e9 100644 --- a/internal/ocispec/microvm_test.go +++ b/internal/ocispec/microvm_test.go @@ -21,6 +21,7 @@ import ( "strings" "testing" + "github.com/google/go-cmp/cmp" "github.com/opencontainers/runtime-spec/specs-go" "go.ate.dev/substrate/internal/proto/ateworkerpb" ) @@ -305,3 +306,48 @@ func TestShapeMicroVM_SystemMounts(t *testing.T) { } } } + +func TestShapeMicroVM_Privileged(t *testing.T) { + spec := Build(Options{Container: &ateworkerpb.Container{ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}, Privileged: true}}}) + if err := ShapeMicroVM(spec, MicroVMOptions{ActorDirs: parityActorDirs, ContainerName: "app", Privileged: true}); err != nil { + t.Fatalf("ShapeMicroVM() = %v", err) + } + if len(spec.Linux.MaskedPaths) != 0 || len(spec.Linux.ReadonlyPaths) != 0 { + t.Errorf("masked = %v, readonly = %v; want none for a privileged container", spec.Linux.MaskedPaths, spec.Linux.ReadonlyPaths) + } + for _, m := range spec.Mounts { + if m.Type == "tmpfs" && slices.Contains(m.Options, "nr_inodes=1") { + t.Errorf("masking tmpfs at %s; want none for a privileged container", m.Destination) + } + if m.Destination == "/sys" && slices.Contains(m.Options, "ro") { + t.Errorf("/sys options = %v, want read-write", m.Options) + } + } + i := slices.IndexFunc(spec.Mounts, func(m specs.Mount) bool { return m.Destination == "/sys/fs/cgroup" }) + if i < 0 || spec.Mounts[i].Type != "cgroup2" || !slices.Contains(spec.Mounts[i].Options, "rw") { + t.Errorf("want a read-write cgroup2 mount at /sys/fs/cgroup, mounts = %v", spec.Mounts) + } + want := []specs.LinuxDeviceCgroup{{Allow: true, Access: "rwm"}} + if diff := cmp.Diff(want, spec.Linux.Resources.Devices); diff != "" { + t.Errorf("devices mismatch (-want +got):\n%s", diff) + } + if spec.Linux.Resources.CPU == nil || spec.Linux.Resources.CPU.Shares == nil { + t.Errorf("kata's default CPU shares are missing: %+v", spec.Linux.Resources.CPU) + } +} + +func TestShapeMicroVM_UnprivilegedKeepsHardening(t *testing.T) { + spec := Build(parityOptions) + if err := ShapeMicroVM(spec, MicroVMOptions{ActorDirs: parityActorDirs, ContainerName: "app"}); err != nil { + t.Fatal(err) + } + if len(spec.Linux.MaskedPaths) == 0 || len(spec.Linux.ReadonlyPaths) == 0 { + t.Errorf("unprivileged container lost its masked or read-only paths") + } + if slices.ContainsFunc(spec.Mounts, func(m specs.Mount) bool { return m.Destination == "/sys/fs/cgroup" }) { + t.Errorf("unprivileged container got a cgroup mount") + } + if slices.ContainsFunc(spec.Linux.Resources.Devices, func(d specs.LinuxDeviceCgroup) bool { return d.Allow && d.Major == nil && d.Type == "" }) { + t.Errorf("unprivileged container may use every device: %v", spec.Linux.Resources.Devices) + } +} diff --git a/internal/proto/ateletpb/atelet.pb.go b/internal/proto/ateletpb/atelet.pb.go index 1a88aec7f5..8ea5f0f45f 100644 --- a/internal/proto/ateletpb/atelet.pb.go +++ b/internal/proto/ateletpb/atelet.pb.go @@ -2945,6 +2945,7 @@ type Container struct { // +k8s:customValidation # mounts must not nest VolumeMounts []*VolumeMount `protobuf:"bytes,6,rep,name=volume_mounts,json=volumeMounts,proto3" json:"volume_mounts,omitempty"` // +k8s:optional + // +k8s:customValidation # capabilities must be unset when privileged SecurityContext *SecurityContext `protobuf:"bytes,8,opt,name=security_context,json=securityContext,proto3" json:"security_context,omitempty"` // resources are the cgroup limits for this container, from the // ActorTemplate. Unset means no limits. @@ -3052,7 +3053,11 @@ func (x *Container) GetResources() *ResourceRequirements { type SecurityContext struct { state protoimpl.MessageState `protogen:"open.v1"` // +k8s:optional - Capabilities *Capabilities `protobuf:"bytes,1,opt,name=capabilities,proto3" json:"capabilities,omitempty"` + Capabilities *Capabilities `protobuf:"bytes,1,opt,name=capabilities,proto3" json:"capabilities,omitempty"` + // privileged mirrors ateapi.SecurityContext.privileged. + // + // +k8s:optional + Privileged bool `protobuf:"varint,2,opt,name=privileged,proto3" json:"privileged,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -3094,6 +3099,13 @@ func (x *SecurityContext) GetCapabilities() *Capabilities { return nil } +func (x *SecurityContext) GetPrivileged() bool { + if x != nil { + return x.Privileged + } + return false +} + // Capabilities adjusts a container's Linux capabilities relative to the default // set. Names carry no "CAP_" prefix; drop applies before add. type Capabilities struct { @@ -4592,9 +4604,12 @@ const file_internal_proto_ateletpb_atelet_proto_rawDesc = "" + "\fwakeup_probe\x18\x05 \x01(\v2\x13.atelet.WakeupProbeR\vwakeupProbe\x128\n" + "\rvolume_mounts\x18\x06 \x03(\v2\x13.atelet.VolumeMountR\fvolumeMounts\x12B\n" + "\x10security_context\x18\b \x01(\v2\x17.atelet.SecurityContextR\x0fsecurityContext\x12:\n" + - "\tresources\x18\t \x01(\v2\x1c.atelet.ResourceRequirementsR\tresources\"K\n" + + "\tresources\x18\t \x01(\v2\x1c.atelet.ResourceRequirementsR\tresources\"k\n" + "\x0fSecurityContext\x128\n" + - "\fcapabilities\x18\x01 \x01(\v2\x14.atelet.CapabilitiesR\fcapabilities\"4\n" + + "\fcapabilities\x18\x01 \x01(\v2\x14.atelet.CapabilitiesR\fcapabilities\x12\x1e\n" + + "\n" + + "privileged\x18\x02 \x01(\bR\n" + + "privileged\"4\n" + "\fCapabilities\x12\x10\n" + "\x03add\x18\x01 \x03(\tR\x03add\x12\x12\n" + "\x04drop\x18\x02 \x03(\tR\x04drop\"7\n" + diff --git a/internal/proto/ateletpb/atelet.proto b/internal/proto/ateletpb/atelet.proto index 536604385e..4657e9330c 100644 --- a/internal/proto/ateletpb/atelet.proto +++ b/internal/proto/ateletpb/atelet.proto @@ -839,6 +839,7 @@ message Container { repeated VolumeMount volume_mounts = 6; // +k8s:optional + // +k8s:customValidation # capabilities must be unset when privileged SecurityContext security_context = 8; // resources are the cgroup limits for this container, from the @@ -852,6 +853,11 @@ message Container { message SecurityContext { // +k8s:optional Capabilities capabilities = 1; + + // privileged mirrors ateapi.SecurityContext.privileged. + // + // +k8s:optional + bool privileged = 2; } // Capabilities adjusts a container's Linux capabilities relative to the default diff --git a/internal/proto/ateworkerpb/ateworker.pb.go b/internal/proto/ateworkerpb/ateworker.pb.go index 8de8d66ac7..80a74693c8 100644 --- a/internal/proto/ateworkerpb/ateworker.pb.go +++ b/internal/proto/ateworkerpb/ateworker.pb.go @@ -875,7 +875,12 @@ type ContainerSpec struct { // /etc/passwd and /etc/group. Unset is root. User *ProcessUser `protobuf:"bytes,5,opt,name=user,proto3" json:"user,omitempty"` // cwd is the process working directory, the image's WORKDIR. Empty is "/". - Cwd string `protobuf:"bytes,6,opt,name=cwd,proto3" json:"cwd,omitempty"` + Cwd string `protobuf:"bytes,6,opt,name=cwd,proto3" json:"cwd,omitempty"` + // privileged is the template's securityContext.privileged. capabilities + // then hold the full set. Only a microvm worker started with + // --allow-privileged-actors accepts it; it shapes the guest container + // without the default hardening (see ocispec.ShapeMicroVM). + Privileged bool `protobuf:"varint,7,opt,name=privileged,proto3" json:"privileged,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -952,6 +957,13 @@ func (x *ContainerSpec) GetCwd() string { return "" } +func (x *ContainerSpec) GetPrivileged() bool { + if x != nil { + return x.Privileged + } + return false +} + // ProcessUser is a resolved process identity. type ProcessUser struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -2187,14 +2199,17 @@ const file_internal_proto_ateworkerpb_ateworker_proto_rawDesc = "" + "\x16external_volume_mounts\x18\x04 \x03(\v2\x16.ateworker.VolumeMountR\x14externalVolumeMounts\x12Q\n" + "\x19system_info_volume_mounts\x18\x05 \x03(\v2\x16.ateworker.VolumeMountR\x16systemInfoVolumeMounts\x12F\n" + "\x13image_volume_mounts\x18\x06 \x03(\v2\x16.ateworker.VolumeMountR\x11imageVolumeMounts\x12?\n" + - "\x0econtainer_spec\x18\a \x01(\v2\x18.ateworker.ContainerSpecR\rcontainerSpec\"\xdb\x01\n" + + "\x0econtainer_spec\x18\a \x01(\v2\x18.ateworker.ContainerSpecR\rcontainerSpec\"\xfb\x01\n" + "\rContainerSpec\x12\x12\n" + "\x04args\x18\x01 \x03(\tR\x04args\x12\x15\n" + "\x03env\x18\x02 \x03(\tB\x03\x80\x01\x01R\x03env\x12\"\n" + "\fcapabilities\x18\x03 \x03(\tR\fcapabilities\x12=\n" + "\tresources\x18\x04 \x01(\v2\x1f.ateworker.ResourceRequirementsR\tresources\x12*\n" + "\x04user\x18\x05 \x01(\v2\x16.ateworker.ProcessUserR\x04user\x12\x10\n" + - "\x03cwd\x18\x06 \x01(\tR\x03cwd\"Z\n" + + "\x03cwd\x18\x06 \x01(\tR\x03cwd\x12\x1e\n" + + "\n" + + "privileged\x18\a \x01(\bR\n" + + "privileged\"Z\n" + "\vProcessUser\x12\x10\n" + "\x03uid\x18\x01 \x01(\rR\x03uid\x12\x10\n" + "\x03gid\x18\x02 \x01(\rR\x03gid\x12'\n" + diff --git a/internal/proto/ateworkerpb/ateworker.proto b/internal/proto/ateworkerpb/ateworker.proto index 2a0ccd824b..7a48f8f1be 100644 --- a/internal/proto/ateworkerpb/ateworker.proto +++ b/internal/proto/ateworkerpb/ateworker.proto @@ -356,6 +356,12 @@ message ContainerSpec { // cwd is the process working directory, the image's WORKDIR. Empty is "/". string cwd = 6; + + // privileged is the template's securityContext.privileged. capabilities + // then hold the full set. Only a microvm worker started with + // --allow-privileged-actors accepts it; it shapes the guest container + // without the default hardening (see ocispec.ShapeMicroVM). + bool privileged = 7; } // ProcessUser is a resolved process identity. message ProcessUser { diff --git a/internal/resources/validate.go b/internal/resources/validate.go index cff8d9ecc3..ceaeaf6139 100644 --- a/internal/resources/validate.go +++ b/internal/resources/validate.go @@ -658,3 +658,19 @@ func ValidateHostPort(fldPath *field.Path, value string) field.ErrorList { } return errs } + +// ValidatePrivilegedSecurityContext rejects capability adjustments next to +// privileged: a privileged container always gets the full set, so add or drop +// would be silently ignored. +func ValidatePrivilegedSecurityContext(fldPath *field.Path, privileged bool, add, drop []string) field.ErrorList { + if privileged && (len(add) > 0 || len(drop) > 0) { + return field.ErrorList{field.Invalid(fldPath.Child("capabilities"), "", "must be unset when privileged is true; a privileged container gets every capability")} + } + return nil +} + +// AllLinuxCapabilities returns every Linux capability name, sorted, without +// the "CAP_" prefix: the set a privileged container runs with. +func AllLinuxCapabilities() []string { + return sets.List(linuxCapabilities) +} diff --git a/manifests/ate-install/generated/ate.dev_workerpools.yaml b/manifests/ate-install/generated/ate.dev_workerpools.yaml index 8c76630c8f..16af7083b6 100644 --- a/manifests/ate-install/generated/ate.dev_workerpools.yaml +++ b/manifests/ate-install/generated/ate.dev_workerpools.yaml @@ -87,6 +87,17 @@ spec: description: WorkerPoolSandboxClass is one sandbox runtime family a WorkerPool runs. properties: + allowPrivilegedActors: + description: |- + allowPrivilegedActors lets this pool's workers run containers whose + ActorTemplate sets securityContext.privileged, for example to run a + container engine inside the actor. Each such actor owns a whole guest + kernel, so the VM stays the isolation boundary, but the workload gets + full privilege inside it and can drive every guest-to-host interface + (virtio devices, the guest agent channel) directly. Enable it only on + pools meant for that, ideally on dedicated nodes. Only the microvm + class supports it. Workers of pools without it fail privileged actors. + type: boolean configRef: description: |- configRef names a cluster-scoped SandboxConfig for this sandbox class. @@ -116,6 +127,10 @@ spec: required: - name type: object + x-kubernetes-validations: + - message: allowPrivilegedActors requires the microvm sandbox class + rule: '!has(self.allowPrivilegedActors) || !self.allowPrivilegedActors + || self.name == ''microvm''' maxItems: 1 minItems: 1 type: array From d24642b4659093109910e7116318cca792ec2484 Mon Sep 17 00:00:00 2001 From: michaeljguarino Date: Sat, 28 Nov 2026 15:30:13 -0500 Subject: [PATCH 2/6] Privileged actors: gVisor support, guest devices, cluster-wide kill switch Builds on the microVM privileged actors change so a privileged container can run rootful Docker, kind and k3s: - microVM: forward Linux.Devices to the Kata agent, and give privileged containers /dev/net/tun, /dev/fuse and /dev/kmsg. - gVisor: allowPrivilegedActors now applies to gVisor pools too. The worker boots such sandboxes with runsc --net-raw and --allow-packet-socket-write, with a writable /sys and cgroup mount. - ate-api-server and ate-controller take --disable-privileged-actors. The API server rejects new privileged templates, and the controller ignores allowPrivilegedActors on every pool. Signed-off-by: michaeljguarino Co-authored-by: Cursor --- api/ateapi/v1/ateapi.pb.go | 22 +++-- api/ateapi/v1/ateapi.proto | 22 +++-- api/infra/k8s/ate/v1/workerpool_types.go | 20 +++-- .../k8s/ate/v1/workerpool_validation_test.go | 5 +- .../internal/controlapi/access_policy_test.go | 2 +- .../internal/controlapi/actor_template.go | 7 ++ .../controlapi/actor_template_test.go | 37 ++++++++ .../controlapi/functionaltest/common_test.go | 1 + cmd/ateapi/internal/controlapi/service.go | 8 ++ cmd/ateapi/main.go | 2 + .../internal/controllers/workerpool_apply.go | 25 +++--- .../controllers/workerpool_apply_test.go | 16 +++- .../controllers/workerpool_controller.go | 8 ++ cmd/atecontroller/main.go | 4 +- cmd/atelet/oci.go | 3 +- cmd/ateworker-gvisor/main.go | 86 +++++++++++-------- cmd/ateworker-gvisor/runsc.go | 23 ++++- cmd/ateworker-gvisor/runsc_test.go | 71 +++++++++++---- .../internal/kata/specconv.go | 17 +++- .../internal/kata/specconv_linux_test.go | 13 +++ docs/reference/api-guide.md | 17 +++- internal/ocispec/gvisor.go | 28 +++++- internal/ocispec/gvisor_test.go | 26 ++++++ internal/ocispec/microvm.go | 30 ++++--- internal/ocispec/microvm_test.go | 10 +++ internal/ocispec/ocispec.go | 11 +++ internal/proto/ateworkerpb/ateworker.pb.go | 6 +- internal/proto/ateworkerpb/ateworker.proto | 6 +- .../generated/ate.dev_workerpools.yaml | 23 ++--- 29 files changed, 421 insertions(+), 128 deletions(-) diff --git a/api/ateapi/v1/ateapi.pb.go b/api/ateapi/v1/ateapi.pb.go index 0f425ac185..abe6857469 100644 --- a/api/ateapi/v1/ateapi.pb.go +++ b/api/ateapi/v1/ateapi.pb.go @@ -3443,14 +3443,20 @@ type SecurityContext struct { // // +k8s:optional Capabilities *Capabilities `protobuf:"bytes,1,opt,name=capabilities,proto3" json:"capabilities,omitempty"` - // privileged runs the container with every Linux capability, unmasked and - // writable /proc and /sys, a writable cgroup2 hierarchy, and access to all - // devices of the sandbox, so that it can run a container engine such as - // dockerd. Only the microvm sandbox class honors it: the actor then owns a - // whole guest kernel, and the VM, not the in-guest container, is the - // isolation boundary. A worker runs privileged containers only when its - // WorkerPool sets sandboxClasses[].allowPrivilegedActors; every other worker - // fails the actor rather than run it unprivileged. + // privileged runs the container with every Linux capability, a writable + // /sys and cgroup hierarchy, and no masked paths, so that it can run a + // container engine such as dockerd, or Kubernetes in containers (kind, k3s). + // The sandbox, not the container inside it, stays the isolation boundary, + // and the privilege never reaches the node: + // + // * microvm: the actor owns a whole guest kernel. The container also gets + // every guest device, including /dev/net/tun, /dev/fuse and /dev/kmsg. + // * gvisor: capabilities exist only in the Sentry, and runsc runs the + // sandbox with raw and packet sockets enabled. + // + // A worker runs privileged containers only when its WorkerPool sets + // sandboxClasses[].allowPrivilegedActors; every other worker fails the actor + // rather than run it unprivileged. // // +k8s:optional Privileged bool `protobuf:"varint,2,opt,name=privileged,proto3" json:"privileged,omitempty"` diff --git a/api/ateapi/v1/ateapi.proto b/api/ateapi/v1/ateapi.proto index d907aea32d..56aa60f735 100644 --- a/api/ateapi/v1/ateapi.proto +++ b/api/ateapi/v1/ateapi.proto @@ -1405,14 +1405,20 @@ message SecurityContext { // +k8s:optional Capabilities capabilities = 1; - // privileged runs the container with every Linux capability, unmasked and - // writable /proc and /sys, a writable cgroup2 hierarchy, and access to all - // devices of the sandbox, so that it can run a container engine such as - // dockerd. Only the microvm sandbox class honors it: the actor then owns a - // whole guest kernel, and the VM, not the in-guest container, is the - // isolation boundary. A worker runs privileged containers only when its - // WorkerPool sets sandboxClasses[].allowPrivilegedActors; every other worker - // fails the actor rather than run it unprivileged. + // privileged runs the container with every Linux capability, a writable + // /sys and cgroup hierarchy, and no masked paths, so that it can run a + // container engine such as dockerd, or Kubernetes in containers (kind, k3s). + // The sandbox, not the container inside it, stays the isolation boundary, + // and the privilege never reaches the node: + // + // * microvm: the actor owns a whole guest kernel. The container also gets + // every guest device, including /dev/net/tun, /dev/fuse and /dev/kmsg. + // * gvisor: capabilities exist only in the Sentry, and runsc runs the + // sandbox with raw and packet sockets enabled. + // + // A worker runs privileged containers only when its WorkerPool sets + // sandboxClasses[].allowPrivilegedActors; every other worker fails the actor + // rather than run it unprivileged. // // +k8s:optional bool privileged = 2; diff --git a/api/infra/k8s/ate/v1/workerpool_types.go b/api/infra/k8s/ate/v1/workerpool_types.go index b86272697b..39835013dd 100644 --- a/api/infra/k8s/ate/v1/workerpool_types.go +++ b/api/infra/k8s/ate/v1/workerpool_types.go @@ -114,7 +114,6 @@ type WorkerPoolSpec struct { } // WorkerPoolSandboxClass is one sandbox runtime family a WorkerPool runs. -// +kubebuilder:validation:XValidation:rule="!has(self.allowPrivilegedActors) || !self.allowPrivilegedActors || self.name == 'microvm'",message="allowPrivilegedActors requires the microvm sandbox class" type WorkerPoolSandboxClass struct { // name selects the sandbox runtime family, which drives the worker pod // shape (KVM/vhost device mounts and node placement). The concrete binary @@ -136,12 +135,19 @@ type WorkerPoolSandboxClass struct { // allowPrivilegedActors lets this pool's workers run containers whose // ActorTemplate sets securityContext.privileged, for example to run a - // container engine inside the actor. Each such actor owns a whole guest - // kernel, so the VM stays the isolation boundary, but the workload gets - // full privilege inside it and can drive every guest-to-host interface - // (virtio devices, the guest agent channel) directly. Enable it only on - // pools meant for that, ideally on dedicated nodes. Only the microvm - // class supports it. Workers of pools without it fail privileged actors. + // container engine inside the actor. The sandbox stays the isolation + // boundary, but the workload gets full privilege inside it: + // + // - microvm: each actor owns a whole guest kernel and can drive every + // guest-to-host interface (virtio devices, the guest agent channel) + // directly. + // - gvisor: the Sentry grants every capability inside the sandbox + // (never on the host), and runsc runs with --net-raw and + // --allow-packet-socket-write, so the actor can open raw sockets and + // write arbitrary packets on its own network interface. + // + // Enable it only on pools meant for that, ideally on dedicated nodes. + // Workers of pools without it fail privileged actors. // // +optional AllowPrivilegedActors *bool `json:"allowPrivilegedActors,omitempty"` diff --git a/api/infra/k8s/ate/v1/workerpool_validation_test.go b/api/infra/k8s/ate/v1/workerpool_validation_test.go index dc5a966ea2..f12defbf3d 100644 --- a/api/infra/k8s/ate/v1/workerpool_validation_test.go +++ b/api/infra/k8s/ate/v1/workerpool_validation_test.go @@ -127,12 +127,11 @@ func TestWorkerPoolValidation(t *testing.T) { }, wantErr: false, }, { - name: "gvisor pool cannot allow privileged actors", + name: "gvisor pool allows privileged actors", mutate: func(wp *WorkerPool) { wp.Spec.SandboxClasses = []WorkerPoolSandboxClass{{Name: SandboxClassGvisor, AllowPrivilegedActors: ptr.To(true)}} }, - wantErr: true, - errMsg: "allowPrivilegedActors requires the microvm sandbox class", + wantErr: false, }, { name: "sandboxClass with configRef", mutate: func(wp *WorkerPool) { diff --git a/cmd/ateapi/internal/controlapi/access_policy_test.go b/cmd/ateapi/internal/controlapi/access_policy_test.go index 900c98eb12..9a0a39ab2d 100644 --- a/cmd/ateapi/internal/controlapi/access_policy_test.go +++ b/cmd/ateapi/internal/controlapi/access_policy_test.go @@ -48,7 +48,7 @@ func TestAccessPolicy_GlobalAndAtespaceGovernance(t *testing.T) { } persistence.SetPolicyManager(policyManager) - svc := NewRPCService(persistence, nil, nil, nil, nil, nil, "", nil, nil, "", nil, "") + svc := NewRPCService(persistence, nil, nil, nil, nil, nil, "", nil, nil, "", nil, "", false) interceptor := authz.UnaryServerInterceptor(authorizer) userCtx := func(id string) context.Context { diff --git a/cmd/ateapi/internal/controlapi/actor_template.go b/cmd/ateapi/internal/controlapi/actor_template.go index 68d1f8ee34..fe9194a803 100644 --- a/cmd/ateapi/internal/controlapi/actor_template.go +++ b/cmd/ateapi/internal/controlapi/actor_template.go @@ -75,6 +75,13 @@ func (s *ServiceImpl) CreateActorTemplate(ctx context.Context, inTemplate *ateap if _, err := resolveSnapshotLocation(s.clusterSnapshotLocation, outTemplate); err != nil { return nil, err } + if s.disablePrivilegedActors { + for _, c := range outTemplate.GetContainers() { + if c.GetSecurityContext().GetPrivileged() { + return nil, apierror.FailedPrecondition("container %q is privileged, but this cluster disables privileged actors (ate-api-server --disable-privileged-actors)", c.GetName()) + } + } + } return s.store.CreateActorTemplate(ctx, outTemplate) } diff --git a/cmd/ateapi/internal/controlapi/actor_template_test.go b/cmd/ateapi/internal/controlapi/actor_template_test.go index 66aa77778a..5c0a2f1442 100644 --- a/cmd/ateapi/internal/controlapi/actor_template_test.go +++ b/cmd/ateapi/internal/controlapi/actor_template_test.go @@ -146,6 +146,43 @@ func TestCreateActorTemplate_RequiresSnapshotLocation(t *testing.T) { } } +// TestCreateActorTemplate_DisablePrivilegedActors pins that +// --disable-privileged-actors rejects only templates with a privileged +// container. +func TestCreateActorTemplate_DisablePrivilegedActors(t *testing.T) { + for i, tt := range []struct { + name string + disable bool + privileged bool + wantCode codes.Code + }{ + {name: "allowed", privileged: true, wantCode: codes.OK}, + {name: "disabled, privileged", disable: true, privileged: true, wantCode: codes.FailedPrecondition}, + {name: "disabled, unprivileged", disable: true, wantCode: codes.OK}, + } { + t.Run(tt.name, func(t *testing.T) { + persistence := newTestPersistence(t) + impl := newServiceImpl(persistence, nil) + impl.clusterSnapshotLocation = "gs://cluster-bucket/" + impl.disablePrivilegedActors = tt.disable + s := &RPCService{impl: impl} + ctx := context.Background() + if _, err := persistence.CreateAtespace(ctx, &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "ns1"}}); err != nil { + t.Fatalf("CreateAtespace failed: %v", err) + } + req := &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { + tmpl.Metadata = &ateapi.ResourceMetadata{Atespace: "ns1", Name: fmt.Sprintf("tmpl-%d", i)} + if tt.privileged { + tmpl.Containers[0].SecurityContext = &ateapi.SecurityContext{Privileged: true} + } + })} + if _, err := s.CreateActorTemplate(ctx, req); apierror.Code(err) != tt.wantCode { + t.Errorf("CreateActorTemplate error = %v, want code %v", err, tt.wantCode) + } + }) + } +} + // TestCreateActorTemplateIgnoresServerOwnedFields pins the create contract: // status on the request is dropped and new templates start with an empty // status. The store persists whatever the handler hands it, so the handler is diff --git a/cmd/ateapi/internal/controlapi/functionaltest/common_test.go b/cmd/ateapi/internal/controlapi/functionaltest/common_test.go index 72709ef72d..44728227c4 100644 --- a/cmd/ateapi/internal/controlapi/functionaltest/common_test.go +++ b/cmd/ateapi/internal/controlapi/functionaltest/common_test.go @@ -233,6 +233,7 @@ func setupTestWithOptions(t *testing.T, ns string, options testOptions) *testCon testActorJWTIssuer, actorJWTAuthorityPool, testStorageLocation, + false, ) // 5. Start REAL gRPC Server for ATE API diff --git a/cmd/ateapi/internal/controlapi/service.go b/cmd/ateapi/internal/controlapi/service.go index f67ebcd613..7d86ca1507 100644 --- a/cmd/ateapi/internal/controlapi/service.go +++ b/cmd/ateapi/internal/controlapi/service.go @@ -73,6 +73,9 @@ type VolumePluginRegistry interface { // // snapshotLocation is ate-api-server's cluster-wide --snapshot-location; see // resolveSnapshotLocation. +// +// disablePrivilegedActors is ate-api-server's --disable-privileged-actors: new +// ActorTemplates with a privileged container are rejected. func NewRPCService( persistence store.Interface, workerCache *workercache.Cache, @@ -86,9 +89,11 @@ func NewRPCService( actorJWTIssuer string, actorIDJWTPool localjwtauthority.Pool, snapshotLocation string, + disablePrivilegedActors bool, ) *RPCService { impl := newServiceImpl(persistence, storageClassLister) impl.clusterSnapshotLocation = snapshotLocation + impl.disablePrivilegedActors = disablePrivilegedActors s := &RPCService{ impl: impl, persistence: persistence, @@ -180,6 +185,9 @@ type ServiceImpl struct { // clusterSnapshotLocation is ate-api-server's --snapshot-location; see // resolveSnapshotLocation. clusterSnapshotLocation string + + // disablePrivilegedActors is ate-api-server's --disable-privileged-actors. + disablePrivilegedActors bool } var _ store.Interface = (*ServiceImpl)(nil) diff --git a/cmd/ateapi/main.go b/cmd/ateapi/main.go index 7b08232531..cc3f7877b6 100644 --- a/cmd/ateapi/main.go +++ b/cmd/ateapi/main.go @@ -111,6 +111,7 @@ var ( drainTimeout = pflag.Duration("drain-timeout", 15*time.Second, "Deadline for the graceful gRPC drain on shutdown. In-flight RPCs still running past it are forcefully cancelled.") objectStorePluginSocket = pflag.String("objectstore-plugin-socket", "/run/objectstore-plugin/control.sock", "Unix socket of the control object-store plugin that external snapshots are deleted and copied through.") + disablePrivilegedActors = pflag.Bool("disable-privileged-actors", false, "Reject new ActorTemplates with a privileged container (securityContext.privileged). ate-controller's flag of the same name keeps workers from running them.") snapshotLocation = pflag.String("snapshot-location", "", "Base object-storage URI (for example gs://BUCKET/PREFIX/) that actor snapshots are stored under. Required unless the PerTemplateSnapshotLocation preview gate is enabled; with the gate, an actor template's snapshotConfig.storageLocation overrides it.") templateResyncInterval = pflag.Duration("template-resync-interval", 20*time.Second, fmt.Sprintf("Interval between actor template resyncs. Must be at least %s.", minResyncInterval)) @@ -356,6 +357,7 @@ func main() { *actorJWTIssuer, actorIDJWTAuthorityPool, *snapshotLocation, + *disablePrivilegedActors, ) // Drive stored ActorTemplates through the golden actor flow. diff --git a/cmd/atecontroller/internal/controllers/workerpool_apply.go b/cmd/atecontroller/internal/controllers/workerpool_apply.go index 881a4d248f..4a521d7f6c 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_apply.go +++ b/cmd/atecontroller/internal/controllers/workerpool_apply.go @@ -701,15 +701,20 @@ func nodeSelectorRequirementToApply(req *corev1.NodeSelectorRequirement) *corev1 return ac } -// allowsPrivilegedActors reports whether the pool opts its microvm workers in -// to privileged actors. The CRD rejects the field on other classes; this -// checks the class again so a stale or hand-edited object cannot pass the -// flag to a gVisor worker. -func allowsPrivilegedActors(wp *atev1.WorkerPool) bool { - for _, c := range wp.Spec.SandboxClasses { - if c.Name == atev1.SandboxClassMicroVM && ptr.Deref(c.AllowPrivilegedActors, false) { - return true - } +// withoutPrivilegedActors returns a copy of wp with allowPrivilegedActors +// cleared on every sandbox class. +func withoutPrivilegedActors(wp *atev1.WorkerPool) *atev1.WorkerPool { + out := wp.DeepCopy() + for i := range out.Spec.SandboxClasses { + out.Spec.SandboxClasses[i].AllowPrivilegedActors = nil } - return false + return out +} + +// allowsPrivilegedActors reports whether the pool opts its workers in to +// privileged actors. +func allowsPrivilegedActors(wp *atev1.WorkerPool) bool { + return slices.ContainsFunc(wp.Spec.SandboxClasses, func(c atev1.WorkerPoolSandboxClass) bool { + return ptr.Deref(c.AllowPrivilegedActors, false) + }) } diff --git a/cmd/atecontroller/internal/controllers/workerpool_apply_test.go b/cmd/atecontroller/internal/controllers/workerpool_apply_test.go index 6f8f5676fc..89f66716fa 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_apply_test.go +++ b/cmd/atecontroller/internal/controllers/workerpool_apply_test.go @@ -1186,7 +1186,8 @@ func TestBuildDeploymentAllowPrivilegedActors(t *testing.T) { }{ {"microvm opted in", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassMicroVM, AllowPrivilegedActors: ptr.To(true)}, true}, {"microvm default", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassMicroVM}, false}, - {"gvisor never", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassGvisor, AllowPrivilegedActors: ptr.To(true)}, false}, + {"gvisor opted in", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassGvisor, AllowPrivilegedActors: ptr.To(true)}, true}, + {"gvisor default", atev1.WorkerPoolSandboxClass{Name: atev1.SandboxClassGvisor}, false}, } { t.Run(tc.name, func(t *testing.T) { wp := testWorkerPoolApplyConfig(nil) @@ -1199,3 +1200,16 @@ func TestBuildDeploymentAllowPrivilegedActors(t *testing.T) { }) } } + +// --disable-privileged-actors applies withoutPrivilegedActors, which must not +// touch the cached pool. +func TestWithoutPrivilegedActors(t *testing.T) { + wp := testWorkerPoolApplyConfig(nil) + wp.Spec.SandboxClasses = []atev1.WorkerPoolSandboxClass{{Name: atev1.SandboxClassMicroVM, AllowPrivilegedActors: ptr.To(true)}} + if got := withoutPrivilegedActors(wp); allowsPrivilegedActors(got) { + t.Errorf("withoutPrivilegedActors() still allows privileged actors: %+v", got.Spec.SandboxClasses) + } + if !allowsPrivilegedActors(wp) { + t.Errorf("withoutPrivilegedActors() modified its input: %+v", wp.Spec.SandboxClasses) + } +} diff --git a/cmd/atecontroller/internal/controllers/workerpool_controller.go b/cmd/atecontroller/internal/controllers/workerpool_controller.go index 23b1906a4f..528a593f6b 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_controller.go +++ b/cmd/atecontroller/internal/controllers/workerpool_controller.go @@ -89,6 +89,10 @@ type WorkerPoolReconciler struct { RouterServiceAccount string // DNSEgressPolicy is the --dns-egress-policy mode propagated to worker pods. DNSEgressPolicy string + + // DisablePrivilegedActors is --disable-privileged-actors: no worker gets + // --allow-privileged-actors, whatever its pool sets. + DisablePrivilegedActors bool // Recorder emits a Normal event each time a pool's SandboxConfig // changes, and a Warning event when a class stops resolving. Recorder events.EventRecorder @@ -331,6 +335,10 @@ func (r *WorkerPoolReconciler) applyDeployment(ctx context.Context, wp *atev1.Wo return err } } + if r.DisablePrivilegedActors && allowsPrivilegedActors(wp) { + log.FromContext(ctx).Info("Ignoring sandboxClasses[].allowPrivilegedActors: ate-controller runs with --disable-privileged-actors") + wp = withoutPrivilegedActors(wp) + } depAC := buildDeploymentApplyConfig(wp, workerOTelSettings{ Endpoint: r.OTelEndpoint, MetricExportInterval: r.OTelMetricExportInterval, diff --git a/cmd/atecontroller/main.go b/cmd/atecontroller/main.go index d99fb97c81..7e59f57e49 100644 --- a/cmd/atecontroller/main.go +++ b/cmd/atecontroller/main.go @@ -97,7 +97,8 @@ var ( workerSyncConcurrency = pflag.Int("worker-sync-concurrency", 2, "Number of concurrent worker goroutines reconciling worker pods into the Worker registry. Defaults to 2.") - dnsEgressPolicy = pflag.String("dns-egress-policy", "", "DNS egress policy enforcement mode propagated to worker pods (must be "+egresspolicy.DNSEgressPolicyEnforceInAtunnel+").") + disablePrivilegedActors = pflag.Bool("disable-privileged-actors", false, "Never let workers run privileged containers, whatever WorkerPool sandboxClasses[].allowPrivilegedActors says. Their actors fail with FailedPrecondition.") + dnsEgressPolicy = pflag.String("dns-egress-policy", "", "DNS egress policy enforcement mode propagated to worker pods (must be "+egresspolicy.DNSEgressPolicyEnforceInAtunnel+").") ) func init() { @@ -266,6 +267,7 @@ func main() { AteletServiceAccount: *ateletServiceAccount, RouterServiceAccount: *routerServiceAccount, DNSEgressPolicy: *dnsEgressPolicy, + DisablePrivilegedActors: *disablePrivilegedActors, Recorder: mgr.GetEventRecorder("workerpool-controller"), APIReader: mgr.GetAPIReader(), }).SetupWithManager(mgr); err != nil { diff --git a/cmd/atelet/oci.go b/cmd/atelet/oci.go index 1a4dbb0096..909ca817c6 100644 --- a/cmd/atelet/oci.go +++ b/cmd/atelet/oci.go @@ -83,8 +83,7 @@ func resolveCapabilities(caps *ateletpb.Capabilities) []string { // resolveContainerCapabilities is resolveCapabilities, except that a // privileged container gets every capability. Whether the worker may run it -// privileged at all is the worker's decision (see ateworker-microvm's -// --allow-privileged-actors). +// privileged at all is the worker's decision (its --allow-privileged-actors). func resolveContainerCapabilities(sc *ateletpb.SecurityContext) []string { if !sc.GetPrivileged() { return resolveCapabilities(sc.GetCapabilities()) diff --git a/cmd/ateworker-gvisor/main.go b/cmd/ateworker-gvisor/main.go index d42598a5cd..09118391e8 100644 --- a/cmd/ateworker-gvisor/main.go +++ b/cmd/ateworker-gvisor/main.go @@ -110,6 +110,9 @@ var ( maxActors = pflag.Int("max-actors", 1000, "How many actors this worker will host at once") usageSampleInterval = pflag.Duration("usage-sample-interval", time.Minute, "How often the ateworker samples the resource usage of its actors. Each sample writes an ate.actor.usage_sampled record per actor, and GetActiveWorkloadStats serves the latest.") + // Set by the WorkerPool controller from sandboxClasses[].allowPrivilegedActors. + allowPrivilegedActors = pflag.Bool("allow-privileged-actors", false, "Run containers whose template sets securityContext.privileged. Without it the worker fails such actors.") + showVersion = pflag.Bool("version", false, "Print version and exit.") logLevelFlag = pflag.String("log-level", "info", "Minimum log level: debug, info, warn, or error.") previewFlags = pflag.StringSlice("preview", nil, "Preview gates to enable.") @@ -423,6 +426,10 @@ type AteWorkerService struct { // enableCoreTags indicates whether the host kernel supports core tagging. enableCoreTags bool + + // allowPrivilegedActors is --allow-privileged-actors: whether containers + // with securityContext.privileged may run here. + allowPrivilegedActors bool } var _ ateworkerpb.WorkerServer = (*AteWorkerService)(nil) @@ -430,17 +437,18 @@ var _ ateworkerpb.WorkerServer = (*AteWorkerService)(nil) // NewService creates a new AteWorkerService. func NewService(tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, maxActors int, flags *flagStore, bootID string) *AteWorkerService { s := &AteWorkerService{ - locks: actorlock.New(), - inFlight: actorlock.NewInFlight(), - actors: map[string]*hostedActor{}, - maxActors: maxActors, - tunnel: tunnel, - actorLogger: actorLogger, - cgroupRoot: defaultCgroupRoot, - flags: flags, - checkpointWrites: make(chan struct{}, checkpointWriteSlots), - bootID: bootID, - enableCoreTags: checkCoreTagsSupported(), + locks: actorlock.New(), + inFlight: actorlock.NewInFlight(), + actors: map[string]*hostedActor{}, + maxActors: maxActors, + tunnel: tunnel, + actorLogger: actorLogger, + cgroupRoot: defaultCgroupRoot, + flags: flags, + checkpointWrites: make(chan struct{}, checkpointWriteSlots), + bootID: bootID, + enableCoreTags: checkCoreTagsSupported(), + allowPrivilegedActors: *allowPrivilegedActors, } s.borrow = &memborrow.Ledger{Unbooked: s.unbookedMemory} return s @@ -706,14 +714,15 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run return nil, err } rcmd := &runsc{ - path: req.GetRunscPath(), - actorUID: req.GetActorUid(), - actorDirs: req.GetActorDirs(), - size: sizing.FromLimits(req.GetResources().GetLimits()), - durableVolumes: durableVolumeNames(req.GetSpec()), - containers: req.GetSpec().GetContainers(), - flags: s.flags, - enableCoreTags: s.enableCoreTags, + path: req.GetRunscPath(), + actorUID: req.GetActorUid(), + actorDirs: req.GetActorDirs(), + size: sizing.FromLimits(req.GetResources().GetLimits()), + durableVolumes: durableVolumeNames(req.GetSpec()), + containers: req.GetSpec().GetContainers(), + flags: s.flags, + enableCoreTags: s.enableCoreTags, + allowPrivileged: s.allowPrivilegedActors, } var containersToDelete []string defer func() { @@ -866,11 +875,12 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke // Checkpoint only saves state; no sizing is applied, so size is left zero. rcmd := &runsc{ - path: req.GetRunscPath(), - actorUID: req.GetActorUid(), - actorDirs: req.GetActorDirs(), - flags: s.flags, - enableCoreTags: s.enableCoreTags, + path: req.GetRunscPath(), + actorUID: req.GetActorUid(), + actorDirs: req.GetActorDirs(), + flags: s.flags, + enableCoreTags: s.enableCoreTags, + allowPrivileged: s.allowPrivilegedActors, } checkpointPath := req.GetActorDirs().GetCheckpointDir() @@ -1185,14 +1195,15 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb return nil, err } rcmd := &runsc{ - path: req.GetRunscPath(), - actorUID: req.GetActorUid(), - actorDirs: req.GetActorDirs(), - size: sizing.FromLimits(req.GetResources().GetLimits()), - durableVolumes: durableVolumeNames(req.GetSpec()), - containers: req.GetSpec().GetContainers(), - flags: s.flags, - enableCoreTags: s.enableCoreTags, + path: req.GetRunscPath(), + actorUID: req.GetActorUid(), + actorDirs: req.GetActorDirs(), + size: sizing.FromLimits(req.GetResources().GetLimits()), + durableVolumes: durableVolumeNames(req.GetSpec()), + containers: req.GetSpec().GetContainers(), + flags: s.flags, + enableCoreTags: s.enableCoreTags, + allowPrivileged: s.allowPrivilegedActors, } var containersToDelete []string defer func() { @@ -1380,11 +1391,12 @@ func (s *AteWorkerService) terminateWorkload(ctx context.Context, actorRef resou } rcmd := &runsc{ - path: runscPath, - actorUID: actorUID, - actorDirs: actorDirs, - flags: s.flags, - enableCoreTags: s.enableCoreTags, + path: runscPath, + actorUID: actorUID, + actorDirs: actorDirs, + flags: s.flags, + enableCoreTags: s.enableCoreTags, + allowPrivileged: s.allowPrivilegedActors, } // Detached from the caller: a deadline mid-`runsc delete` would leave the diff --git a/cmd/ateworker-gvisor/runsc.go b/cmd/ateworker-gvisor/runsc.go index e39ceeff6e..a1b18bb4c1 100644 --- a/cmd/ateworker-gvisor/runsc.go +++ b/cmd/ateworker-gvisor/runsc.go @@ -50,6 +50,17 @@ type runsc struct { flags *flagStore // enableCoreTags enables Linux core scheduling tags (--enable-core-tags). enableCoreTags bool + // allowPrivileged is the worker's --allow-privileged-actors. + allowPrivileged bool +} + +// privileged reports whether the sandbox runs a privileged container the +// worker allows. Only the commands that boot the sandbox (create and restore) +// know the containers, and only they read RunscPrivilegedFlags. +func (r *runsc) privileged() bool { + return r.allowPrivileged && slices.ContainsFunc(r.containers, func(c *ateworkerpb.Container) bool { + return c.GetContainerSpec().GetPrivileged() + }) } // buildArgs constructs the runsc argument vector for command, appending @@ -67,6 +78,9 @@ func (r *runsc) buildArgs(command, containerName string, extraArgs ...string) [] if r.enableCoreTags { args = append(args, "--enable-core-tags") } + if r.privileged() { + args = append(args, ocispec.RunscPrivilegedFlags...) + } args = append(args, "-root", runscStateDir(r.actorDirs)) args = append(args, command) args = append(args, subcommandFlags...) @@ -104,6 +118,7 @@ func noRootContainerArgs(containerName string) []string { func (r *runsc) writeSpec(containerName string) error { bundlePath := ociBundlePath(r.actorDirs, containerName) var spec *specs.Spec + privileged := false if containerName == ocispec.SandboxID { // atelet makes only the application containers' bundles. if err := os.MkdirAll(bundlePath, 0o700); err != nil { @@ -115,10 +130,9 @@ func (r *runsc) writeSpec(containerName string) error { if i < 0 { return fmt.Errorf("container %q is not in the workload spec", containerName) } - if r.containers[i].GetContainerSpec().GetPrivileged() { - // The privileged shape relies on a VM boundary; gVisor shares the - // host kernel through runsc, so it never runs one. - return status.Errorf(codes.FailedPrecondition, "container %q is privileged; only microvm workers run privileged containers", containerName) + privileged = r.containers[i].GetContainerSpec().GetPrivileged() + if privileged && !r.allowPrivileged { + return status.Errorf(codes.FailedPrecondition, "container %q is privileged, but this worker does not allow privileged actors (WorkerPool sandboxClasses[].allowPrivilegedActors)", containerName) } spec = ocispec.Build(ocispec.Options{ActorUID: r.actorUID, ActorDirs: r.actorDirs, Container: r.containers[i]}) } @@ -128,6 +142,7 @@ func (r *runsc) writeSpec(containerName string) error { ContainerName: containerName, DurableVolumes: r.durableVolumes, Size: r.size, + Privileged: privileged, }) return ocispec.Save(bundlePath, spec) } diff --git a/cmd/ateworker-gvisor/runsc_test.go b/cmd/ateworker-gvisor/runsc_test.go index 9b06c8c774..f865f4a3a6 100644 --- a/cmd/ateworker-gvisor/runsc_test.go +++ b/cmd/ateworker-gvisor/runsc_test.go @@ -407,20 +407,61 @@ func TestRestoreWorkloadRejectsEmptyRestoreDir(t *testing.T) { } } -// gVisor never runs a privileged container: the privileged shape relies on a -// VM boundary. -func TestWriteSpecRejectsPrivileged(t *testing.T) { - root := t.TempDir() - actorDirs := &ateworkerpb.ActorDirs{RootDir: root, OciBundleDir: filepath.Join(root, "bundles")} - if err := os.MkdirAll(ociBundlePath(actorDirs, "app"), 0o700); err != nil { - t.Fatal(err) - } - r := &runsc{ - actorUID: "uid-a", - actorDirs: actorDirs, - containers: []*ateworkerpb.Container{{Name: "app", ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}, Privileged: true}}}, - } - if err := r.writeSpec("app"); status.Code(err) != codes.FailedPrecondition { - t.Errorf("writeSpec(app) = %v, want FailedPrecondition", err) +// A privileged container runs only on a worker started with +// --allow-privileged-actors, which then shapes it for a container engine and +// boots the sandbox with ocispec.RunscPrivilegedFlags. +func TestPrivilegedContainer(t *testing.T) { + for _, tc := range []struct { + name string + allow bool + privileged bool + wantCode codes.Code + wantFlags bool + }{ + {name: "denied", privileged: true, wantCode: codes.FailedPrecondition}, + {name: "allowed", allow: true, privileged: true, wantCode: codes.OK, wantFlags: true}, + {name: "unprivileged on an allowing worker", allow: true, wantCode: codes.OK}, + } { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + actorDirs := &ateworkerpb.ActorDirs{RootDir: root, OciBundleDir: filepath.Join(root, "bundles")} + if err := os.MkdirAll(ociBundlePath(actorDirs, "app"), 0o700); err != nil { + t.Fatal(err) + } + r := &runsc{ + actorUID: "uid-a", + actorDirs: actorDirs, + containers: []*ateworkerpb.Container{{Name: "app", ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}, Privileged: tc.privileged}}}, + flags: mustFlagStore(t), + allowPrivileged: tc.allow, + } + err := r.writeSpec("app") + if status.Code(err) != tc.wantCode { + t.Fatalf("writeSpec(app) = %v, want %v", err, tc.wantCode) + } + for _, cmd := range []string{"create", "restore"} { + args := r.buildArgs(cmd, ocispec.SandboxID) + for _, f := range ocispec.RunscPrivilegedFlags { + if got := slices.Contains(args, f); got != tc.wantFlags { + t.Errorf("%s args contain %s = %v, want %v (args %v)", cmd, f, got, tc.wantFlags, args) + } + } + } + if err != nil { + return + } + b, err := os.ReadFile(filepath.Join(ociBundlePath(actorDirs, "app"), "config.json")) + if err != nil { + t.Fatal(err) + } + var spec specs.Spec + if err := json.Unmarshal(b, &spec); err != nil { + t.Fatal(err) + } + hasCgroup := slices.ContainsFunc(spec.Mounts, func(m specs.Mount) bool { return m.Destination == "/sys/fs/cgroup" }) + if hasCgroup != tc.privileged { + t.Errorf("cgroup mount present = %v, want %v (mounts %v)", hasCgroup, tc.privileged, spec.Mounts) + } + }) } } diff --git a/cmd/ateworker-microvm/internal/kata/specconv.go b/cmd/ateworker-microvm/internal/kata/specconv.go index dfc546ed54..81e6c60fe5 100644 --- a/cmd/ateworker-microvm/internal/kata/specconv.go +++ b/cmd/ateworker-microvm/internal/kata/specconv.go @@ -32,7 +32,7 @@ const DefaultCPUPeriodUS = 100000 // config.json is lowercase. // // Only the fields the kata-agent needs to create + start a container are mapped -// (process, root, mounts, linux namespaces/resources/cgroup/masked+readonly paths). +// (process, root, mounts, linux namespaces/devices/resources/cgroup/masked+readonly paths). // The container rootfs is provided out-of-band as storages; the caller sets the // returned spec's Root.Path to the overlay mount point. func SpecToAgentPB(s *specs.Spec) *agentpb.Spec { @@ -112,6 +112,21 @@ func SpecToAgentPB(s *specs.Spec) *agentpb.Spec { } l.Namespaces = append(l.Namespaces, &agentpb.LinuxNamespace{Type: string(ns.Type)}) } + // The agent creates these nodes in the container's /dev. The + // Resources.Devices cgroup rules below must also allow them. + for _, d := range s.Linux.Devices { + ld := &agentpb.LinuxDevice{Path: d.Path, Type: d.Type, Major: d.Major, Minor: d.Minor} + if d.FileMode != nil { + ld.FileMode = uint32(*d.FileMode) + } + if d.UID != nil { + ld.UID = *d.UID + } + if d.GID != nil { + ld.GID = *d.GID + } + l.Devices = append(l.Devices, ld) + } if r := s.Linux.Resources; r != nil { res := &agentpb.LinuxResources{} for _, d := range r.Devices { diff --git a/cmd/ateworker-microvm/internal/kata/specconv_linux_test.go b/cmd/ateworker-microvm/internal/kata/specconv_linux_test.go index 5abca549cc..6dc25447ce 100644 --- a/cmd/ateworker-microvm/internal/kata/specconv_linux_test.go +++ b/cmd/ateworker-microvm/internal/kata/specconv_linux_test.go @@ -17,6 +17,7 @@ package kata import ( + "os" "slices" "testing" @@ -194,3 +195,15 @@ func TestSpecToAgentPB_ForwardsCwd(t *testing.T) { t.Fatalf("Process.Cwd = %q, want /work", got.GetProcess().GetCwd()) } } + +// The agent creates a container's device nodes only from Linux.Devices. +func TestSpecToAgentPB_ForwardsDevices(t *testing.T) { + mode := os.FileMode(0o666) + got := SpecToAgentPB(&specs.Spec{Linux: &specs.Linux{Devices: []specs.LinuxDevice{ + {Path: "/dev/net/tun", Type: "c", Major: 10, Minor: 200, FileMode: &mode}, + }}}) + d := got.GetLinux().GetDevices() + if len(d) != 1 || d[0].Path != "/dev/net/tun" || d[0].Type != "c" || d[0].Major != 10 || d[0].Minor != 200 || d[0].FileMode != 0o666 { + t.Fatalf("Linux.Devices = %v, want /dev/net/tun c 10:200 0666", d) + } +} diff --git a/docs/reference/api-guide.md b/docs/reference/api-guide.md index 50b6873d79..524f0016e3 100644 --- a/docs/reference/api-guide.md +++ b/docs/reference/api-guide.md @@ -23,7 +23,7 @@ The `WorkerPool` defines the pool of physical "warm" compute capacity. It manage | :--- | :--- | :--- | | `replicas` | `int32` | **Required.** Number of physical standby pods to maintain in the cluster. | | `workerImage` | `string` | **Required.** The container image for the `ateworker` process (e.g. `ko://go.ate.dev/substrate/cmd/ateworker-gvisor`). | -| `sandboxClasses` | `[]WorkerPoolSandboxClass` | **Required.** The sandbox runtime families the pool runs; exactly one entry today. Each entry has `name` (**required**, `gvisor` or `microvm`, immutable), which drives the worker pod shape (e.g. KVM device mounts, node placement), and `configRef.name` (optional), which names a cluster-scoped [`SandboxConfig`](#3-sandboxconfig-the-sandbox-itself) of the same class. Without `configRef`, the pool uses the class default (see [Class default](#class-default)). The controller records the result in `status.sandboxClasses`. The sandbox binaries an actor boots with come from the `SandboxConfig` the pool of its assigned worker resolved. | +| `sandboxClasses` | `[]WorkerPoolSandboxClass` | **Required.** The sandbox runtime families the pool runs; exactly one entry today. Each entry has `name` (**required**, `gvisor` or `microvm`, immutable), which drives the worker pod shape (e.g. KVM device mounts, node placement), and `configRef.name` (optional), which names a cluster-scoped [`SandboxConfig`](#3-sandboxconfig-the-sandbox-itself) of the same class. Without `configRef`, the pool uses the class default (see [Class default](#class-default)). The controller records the result in `status.sandboxClasses`. The sandbox binaries an actor boots with come from the `SandboxConfig` the pool of its assigned worker resolved. `allowPrivilegedActors` (optional, default false) lets the pool's workers run [privileged containers](#privileged-containers-securitycontextprivileged). | | `template` | `WorkerPoolPodTemplate` | **Optional.** Metadata, scheduling, and resource settings for worker workloads. | #### `WorkerPoolPodTemplate` (`spec.template`) @@ -341,7 +341,7 @@ Each entry in `containers` describes one process to run in the actor's sandbox. | `env` | `[]EnvVar` | Optional. Literal `value` entries. | | `wakeupProbe` | `WakeupProbe` | Optional. HTTP wakeup probe — see [Container Wakeup Probe](#container-wakeup-probe-wakeupprobe). | | `volumeMounts` | `[]VolumeMount` | Optional. Mounts a `volumes` entry (e.g. `durableDir`) into this container. | -| `securityContext` | `SecurityContext` | Optional. Security settings for the container process — see [Container Capabilities](#container-capabilities-securitycontextcapabilities). | +| `securityContext` | `SecurityContext` | Optional. Security settings for the container process — see [Container Capabilities](#container-capabilities-securitycontextcapabilities) and [Privileged containers](#privileged-containers-securitycontextprivileged). | | `resources` | `ResourceRequirements` | Optional. Compute limits for this container (`limits.cpuMillicores` and `limits.memoryBytes`), enforced inside the actor's sandbox. See [Per-container limits](#per-container-limits). | `command` and `args` resolve against the container image's `ENTRYPOINT`/`CMD` the same way [Kubernetes Pod `command`/`args`](https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/) resolve against `ENTRYPOINT`/`CMD`. If the resolved argv is empty — the image sets neither `ENTRYPOINT` nor `CMD`, and the container sets neither `command` nor `args` — `Run`/`Restore` fails. @@ -381,6 +381,19 @@ A container running as root has that set as its effective capabilities. A contai The sandbox — gVisor or microVM — remains the isolation boundary; capabilities constrain the workload *inside* it. +### Privileged containers (`securityContext.privileged`) + +A container that sets `securityContext.privileged: true` runs with every Linux capability, a read-write `/sys`, a read-write cgroup hierarchy at `/sys/fs/cgroup` and no masked or read-only paths, like a privileged Kubernetes container. That is what a container engine (`dockerd`, `containerd`, Podman) or Kubernetes in containers (kind, k3s) needs inside the actor. `capabilities` must be unset next to it. + +The sandbox stays the isolation boundary, and the privilege never reaches the node: + +- **microVM.** The actor owns a whole guest kernel. The container may also use every guest device, and gets `/dev/net/tun`, `/dev/fuse` and `/dev/kmsg` nodes. It can drive the guest's virtio devices and agent channel directly. +- **gVisor.** Capabilities exist only in the Sentry. The worker boots the sandbox with runsc's `--net-raw` and `--allow-packet-socket-write`, which [Docker in gVisor](https://gvisor.dev/docs/tutorials/docker-in-gvisor/) needs. The actor can then write arbitrary packets on its own interface. That guide also lists what `dockerd` needs inside the sandbox, such as `--iptables=false` and a tmpfs at `/var/lib/docker`. + +Two opt-ins are needed. The template sets `privileged`, and the pool its `workerSelector` targets sets `sandboxClasses[].allowPrivilegedActors: true`. A worker whose pool doesn't allow it fails the actor with `FailedPrecondition` rather than run the container unprivileged. Enable it only on pools meant for such workloads, ideally on dedicated nodes. + +To forbid privileged containers cluster-wide, run both `ate-api-server` and `ate-controller` with `--disable-privileged-actors`. The API server then rejects new templates that set `privileged` with `FailedPrecondition`, and the controller ignores `allowPrivilegedActors` on every pool, so actors from existing templates fail on their workers. + ### Per-container limits A container may cap its own CPU and memory so it cannot starve or kill its siblings in the same actor (on a template whose `workerSelector` targets a microVM pool): diff --git a/internal/ocispec/gvisor.go b/internal/ocispec/gvisor.go index 6af8b39559..ec2173ea24 100644 --- a/internal/ocispec/gvisor.go +++ b/internal/ocispec/gvisor.go @@ -42,8 +42,21 @@ type GVisorOptions struct { // applies it; a microVM container's limits come from its own declared // resources (see sizing). Size sizing.SandboxSize + // Privileged gives the container a read-write /sys and a read-write + // cgroup hierarchy, so it can run a container engine. The Sentry grants + // the full capability set (atelet sets it with Privileged) inside the + // sandbox only. The caller must check that the worker allows privileged + // actors and run runsc with RunscPrivilegedFlags. + Privileged bool } +// RunscPrivilegedFlags are the runsc flags a sandbox with a privileged +// container needs: a container engine's networking uses raw sockets, and +// dockerd v28 and later writes ARP and NA packets on AF_PACKET sockets when it +// brings up an interface. +// https://gvisor.dev/docs/tutorials/docker-in-gvisor/ +var RunscPrivilegedFlags = []string{"--net-raw", "--allow-packet-socket-write"} + // GVisorCgroupLeaf names an actor container's cgroup relative to the pod scope. func GVisorCgroupLeaf(actorUID, containerName string) string { return actorUID + "-" + containerName @@ -51,7 +64,9 @@ func GVisorCgroupLeaf(actorUID, containerName string) string { // ShapeGVisor adds runsc CRI annotations, durable-dir mount hints, and // per-container cgroups to the spec, caps /tmp at half the memory limit, and -// drops mounts and mount options runsc supplies or ignores. It is idempotent. +// drops mounts and mount options runsc supplies or ignores. A privileged +// container also gets a read-write /sys and cgroup hierarchy. It is +// idempotent. func ShapeGVisor(spec *specs.Spec, o GVisorOptions) { if spec.Annotations == nil { spec.Annotations = make(map[string]string) @@ -83,6 +98,17 @@ func ShapeGVisor(spec *specs.Spec, o GVisorOptions) { return opt == "strictatime" }) } + // Docker's default cgroup mount, read-write as for a privileged container. + // runsc serves it from the Sentry's own cgroupfs, never the host's. + if o.Privileged && !slices.ContainsFunc(spec.Mounts, func(m specs.Mount) bool { return m.Destination == "/sys/fs/cgroup" }) { + makeSysfsWritable(spec) + spec.Mounts = append(spec.Mounts, specs.Mount{ + Destination: "/sys/fs/cgroup", + Type: "cgroup", + Source: "cgroup", + Options: []string{"nosuid", "noexec", "nodev", "rw"}, + }) + } // runsc's tmpfs defaults to half of the node's memory. Cap /tmp at half the // actor's memory limit, matching the guest kernel's default on microVM. // runsc requires unchanged mount options across MEMORY restores. diff --git a/internal/ocispec/gvisor_test.go b/internal/ocispec/gvisor_test.go index ae4e4e8e3d..9f10cf4aca 100644 --- a/internal/ocispec/gvisor_test.go +++ b/internal/ocispec/gvisor_test.go @@ -16,6 +16,7 @@ package ocispec import ( "reflect" + "slices" "strings" "testing" @@ -127,3 +128,28 @@ func TestShapeGVisor_SystemMounts(t *testing.T) { }) } } + +// A privileged container gets a read-write /sys and cgroup hierarchy; shaping +// twice adds no second cgroup mount. +func TestShapeGVisor_Privileged(t *testing.T) { + spec := Build(Options{Container: &ateworkerpb.Container{ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}, Privileged: true}}}) + o := GVisorOptions{ActorUID: "uid-a", ContainerName: "app", Privileged: true} + ShapeGVisor(spec, o) + ShapeGVisor(spec, o) + for _, want := range []specs.Mount{ + {Destination: "/sys", Type: "sysfs", Source: "sysfs", Options: []string{"nosuid", "noexec", "nodev", "rw"}}, + {Destination: "/sys/fs/cgroup", Type: "cgroup", Source: "cgroup", Options: []string{"nosuid", "noexec", "nodev", "rw"}}, + } { + if got := mountFor(t, spec, want.Destination); !reflect.DeepEqual(got, want) { + t.Errorf("%s =\n%+v\nwant\n%+v", want.Destination, got, want) + } + } + + unprivileged := Build(Options{Container: &ateworkerpb.Container{ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}}}}) + ShapeGVisor(unprivileged, GVisorOptions{ActorUID: "uid-a", ContainerName: "app"}) + for _, m := range unprivileged.Mounts { + if m.Destination == "/sys/fs/cgroup" || (m.Destination == "/sys" && !slices.Contains(m.Options, "ro")) { + t.Errorf("unprivileged container got %+v", m) + } + } +} diff --git a/internal/ocispec/microvm.go b/internal/ocispec/microvm.go index 5cf03168a2..2eb95a2620 100644 --- a/internal/ocispec/microvm.go +++ b/internal/ocispec/microvm.go @@ -16,6 +16,7 @@ package ocispec import ( "fmt" + "os" "path" "path/filepath" "runtime" @@ -125,18 +126,12 @@ func ShapeMicroVM(spec *specs.Spec, o MicroVMOptions) error { // shapePrivileged finishes the spec of a privileged guest container, the // equivalent of a privileged container under containerd inside the VM: no // masked or read-only paths, read-write /sys, a read-write cgroup2 mount, and -// every guest device. Capabilities already hold the full set (atelet sets them -// with Privileged). The sysctls ShapeMicroVM sets for unprivileged containers -// are left out: a privileged container can set them itself, and a container -// engine inside expects the kernel defaults. +// every guest device, with tun, fuse and kmsg nodes. Capabilities already hold +// the full set (atelet sets them with Privileged). The sysctls ShapeMicroVM +// sets for unprivileged containers are left out: a privileged container can +// set them itself, and a container engine inside expects the kernel defaults. func shapePrivileged(spec *specs.Spec) { - for i := range spec.Mounts { - m := &spec.Mounts[i] - if m.Destination == "/sys" && m.Type == "sysfs" { - m.Options = slices.DeleteFunc(slices.Clone(m.Options), func(o string) bool { return o == "ro" }) - m.Options = append(m.Options, "rw") - } - } + makeSysfsWritable(spec) spec.Mounts = append(spec.Mounts, specs.Mount{ Destination: "/sys/fs/cgroup", Type: "cgroup2", @@ -150,6 +145,19 @@ func shapePrivileged(spec *specs.Spec) { // (/dev/null, /dev/net/tun, ...), so allow every guest device. resources.Devices = []specs.LinuxDeviceCgroup{{Allow: true, Access: "rwm"}} spec.Linux.Resources = resources + // The agent creates only the OCI default nodes in the container's /dev. + // Container engines and kubelet expect these too; they exist only in the + // guest kernel, so they give the actor no host device. + spec.Linux.Devices = append(spec.Linux.Devices, privilegedGuestDevices...) +} + +// privilegedGuestDevices are the device nodes a privileged guest container +// gets beyond the OCI defaults: tun for container and VPN networking, fuse +// for fuse-overlayfs and FUSE file systems, and kmsg, which kubelet reads. +var privilegedGuestDevices = []specs.LinuxDevice{ + {Path: "/dev/net/tun", Type: "c", Major: 10, Minor: 200, FileMode: new(os.FileMode(0o666))}, + {Path: "/dev/fuse", Type: "c", Major: 10, Minor: 229, FileMode: new(os.FileMode(0o666))}, + {Path: "/dev/kmsg", Type: "c", Major: 1, Minor: 11, FileMode: new(os.FileMode(0o644))}, } // mergeKataResources fills in the kata defaults that the caller's spec leaves diff --git a/internal/ocispec/microvm_test.go b/internal/ocispec/microvm_test.go index 02fb7021e9..546371aca1 100644 --- a/internal/ocispec/microvm_test.go +++ b/internal/ocispec/microvm_test.go @@ -334,6 +334,13 @@ func TestShapeMicroVM_Privileged(t *testing.T) { if spec.Linux.Resources.CPU == nil || spec.Linux.Resources.CPU.Shares == nil { t.Errorf("kata's default CPU shares are missing: %+v", spec.Linux.Resources.CPU) } + var paths []string + for _, d := range spec.Linux.Devices { + paths = append(paths, d.Path) + } + if diff := cmp.Diff([]string{"/dev/net/tun", "/dev/fuse", "/dev/kmsg"}, paths); diff != "" { + t.Errorf("device nodes mismatch (-want +got):\n%s", diff) + } } func TestShapeMicroVM_UnprivilegedKeepsHardening(t *testing.T) { @@ -350,4 +357,7 @@ func TestShapeMicroVM_UnprivilegedKeepsHardening(t *testing.T) { if slices.ContainsFunc(spec.Linux.Resources.Devices, func(d specs.LinuxDeviceCgroup) bool { return d.Allow && d.Major == nil && d.Type == "" }) { t.Errorf("unprivileged container may use every device: %v", spec.Linux.Resources.Devices) } + if len(spec.Linux.Devices) != 0 { + t.Errorf("unprivileged container got device nodes: %v", spec.Linux.Devices) + } } diff --git a/internal/ocispec/ocispec.go b/internal/ocispec/ocispec.go index 8b7040e1ea..e4b8656368 100644 --- a/internal/ocispec/ocispec.go +++ b/internal/ocispec/ocispec.go @@ -120,6 +120,17 @@ func systemMounts() []specs.Mount { } } +// makeSysfsWritable mounts a privileged container's /sys read-write. +func makeSysfsWritable(spec *specs.Spec) { + for i := range spec.Mounts { + m := &spec.Mounts[i] + if m.Destination == "/sys" && m.Type == "sysfs" { + m.Options = slices.DeleteFunc(slices.Clone(m.Options), func(o string) bool { return o == "ro" || o == "rw" }) + m.Options = append(m.Options, "rw") + } + } +} + // Build returns a runtime-neutral OCI spec for an actor container. func Build(o Options) *specs.Spec { container := o.Container diff --git a/internal/proto/ateworkerpb/ateworker.pb.go b/internal/proto/ateworkerpb/ateworker.pb.go index 80a74693c8..bbaffe5b8e 100644 --- a/internal/proto/ateworkerpb/ateworker.pb.go +++ b/internal/proto/ateworkerpb/ateworker.pb.go @@ -877,9 +877,9 @@ type ContainerSpec struct { // cwd is the process working directory, the image's WORKDIR. Empty is "/". Cwd string `protobuf:"bytes,6,opt,name=cwd,proto3" json:"cwd,omitempty"` // privileged is the template's securityContext.privileged. capabilities - // then hold the full set. Only a microvm worker started with - // --allow-privileged-actors accepts it; it shapes the guest container - // without the default hardening (see ocispec.ShapeMicroVM). + // then hold the full set. Only a worker started with + // --allow-privileged-actors accepts it (see ocispec.ShapeMicroVM and + // ocispec.ShapeGVisor). Privileged bool `protobuf:"varint,7,opt,name=privileged,proto3" json:"privileged,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache diff --git a/internal/proto/ateworkerpb/ateworker.proto b/internal/proto/ateworkerpb/ateworker.proto index 7a48f8f1be..740a8da74a 100644 --- a/internal/proto/ateworkerpb/ateworker.proto +++ b/internal/proto/ateworkerpb/ateworker.proto @@ -358,9 +358,9 @@ message ContainerSpec { string cwd = 6; // privileged is the template's securityContext.privileged. capabilities - // then hold the full set. Only a microvm worker started with - // --allow-privileged-actors accepts it; it shapes the guest container - // without the default hardening (see ocispec.ShapeMicroVM). + // then hold the full set. Only a worker started with + // --allow-privileged-actors accepts it (see ocispec.ShapeMicroVM and + // ocispec.ShapeGVisor). bool privileged = 7; } // ProcessUser is a resolved process identity. diff --git a/manifests/ate-install/generated/ate.dev_workerpools.yaml b/manifests/ate-install/generated/ate.dev_workerpools.yaml index 16af7083b6..c37d473c6f 100644 --- a/manifests/ate-install/generated/ate.dev_workerpools.yaml +++ b/manifests/ate-install/generated/ate.dev_workerpools.yaml @@ -91,12 +91,19 @@ spec: description: |- allowPrivilegedActors lets this pool's workers run containers whose ActorTemplate sets securityContext.privileged, for example to run a - container engine inside the actor. Each such actor owns a whole guest - kernel, so the VM stays the isolation boundary, but the workload gets - full privilege inside it and can drive every guest-to-host interface - (virtio devices, the guest agent channel) directly. Enable it only on - pools meant for that, ideally on dedicated nodes. Only the microvm - class supports it. Workers of pools without it fail privileged actors. + container engine inside the actor. The sandbox stays the isolation + boundary, but the workload gets full privilege inside it: + + - microvm: each actor owns a whole guest kernel and can drive every + guest-to-host interface (virtio devices, the guest agent channel) + directly. + - gvisor: the Sentry grants every capability inside the sandbox + (never on the host), and runsc runs with --net-raw and + --allow-packet-socket-write, so the actor can open raw sockets and + write arbitrary packets on its own network interface. + + Enable it only on pools meant for that, ideally on dedicated nodes. + Workers of pools without it fail privileged actors. type: boolean configRef: description: |- @@ -127,10 +134,6 @@ spec: required: - name type: object - x-kubernetes-validations: - - message: allowPrivilegedActors requires the microvm sandbox class - rule: '!has(self.allowPrivilegedActors) || !self.allowPrivilegedActors - || self.name == ''microvm''' maxItems: 1 minItems: 1 type: array From 4f59254ba4ad83894babafe8d42010290ead1f51 Mon Sep 17 00:00:00 2001 From: michaeljguarino Date: Sat, 28 Nov 2026 15:41:24 -0500 Subject: [PATCH 3/6] ci: publish release images from pluralsh/substrate to ghcr.io/pluralsh/substrate Skip the draft release and the site deploy outside agent-substrate/substrate. Signed-off-by: michaeljguarino Co-authored-by: Cursor --- .github/workflows/release.yaml | 18 ++++++++++-------- .github/workflows/site.yaml | 2 +- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 231147e2b2..6af53d47f7 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -17,10 +17,12 @@ # kubectl-ate binaries attached. A maintainer edits and publishes it; see # docs/dev/releasing.md. # -# Images are published only from agent-substrate/substrate, to -# ghcr.io/agent-substrate/substrate. In any other repository (a fork) the -# images job is skipped, because GitHub bills package storage to the fork's -# owner, and the draft is created as before. +# Images are published only from agent-substrate/substrate and the +# pluralsh/substrate fork, each to ghcr.io/. In any other +# repository (a fork) the images job is skipped, because GitHub bills package +# storage to the fork's owner, and the draft is created as before. +# pluralsh/substrate publishes images only: it creates no draft, because it +# has no upstream release tags for the notes to start from. # # Run manually to publish images or draft a release for an existing tag. # A complete image set is left unchanged unless overwrite is set; an incomplete @@ -54,7 +56,7 @@ concurrency: jobs: # The only job that writes to a registry. images: - if: github.repository == 'agent-substrate/substrate' && !inputs.dry_run_images + if: (github.repository == 'agent-substrate/substrate' || github.repository == 'pluralsh/substrate') && !inputs.dry_run_images runs-on: ubuntu-latest timeout-minutes: 30 permissions: @@ -63,7 +65,7 @@ jobs: # Read by ate-setup publish release-images. env: VERSION: ${{ inputs.tag || github.ref_name }} - KO_DOCKER_REPO: ghcr.io/agent-substrate/substrate + KO_DOCKER_REPO: ghcr.io/${{ github.repository }} KO_DEFAULTPLATFORMS: linux/amd64,linux/arm64 # inputs.overwrite is empty on a tag push; this makes the value explicit. ATE_PUBLISH_OVERWRITE: ${{ inputs.overwrite == true }} @@ -153,8 +155,8 @@ jobs: # Runs after images succeeded, or when images was skipped (any repository # other than agent-substrate/substrate). If images failed, no draft is # created, so a release cannot be published without its images. Skipped - # in a dry run. - if: ${{ !cancelled() && !inputs.dry_run_images && (needs.images.result == 'success' || needs.images.result == 'skipped') }} + # in a dry run and in pluralsh/substrate. + if: ${{ !cancelled() && !inputs.dry_run_images && github.repository != 'pluralsh/substrate' && (needs.images.result == 'success' || needs.images.result == 'skipped') }} runs-on: ubuntu-latest timeout-minutes: 30 # Creating a release needs contents: write. diff --git a/.github/workflows/site.yaml b/.github/workflows/site.yaml index eb96462dbe..24aceeb972 100644 --- a/.github/workflows/site.yaml +++ b/.github/workflows/site.yaml @@ -110,7 +110,7 @@ jobs: with: path: site/public deploy: - if: github.event_name != 'pull_request' + if: github.event_name != 'pull_request' && github.repository == 'agent-substrate/substrate' needs: build runs-on: ubuntu-latest timeout-minutes: 10 From 44483604bdddf577a2742c787db430a47cabdc31 Mon Sep 17 00:00:00 2001 From: michaeljguarino Date: Sat, 28 Nov 2026 19:16:27 -0500 Subject: [PATCH 4/6] ateworker-microvm: keep the low-port and ping sysctls for privileged containers A privileged container still runs its processes as the image's user, which binds ports below 1024 without CAP_NET_BIND_SERVICE. Without the sysctl a non-root server on :80 fails to bind, and the wakeup probe never succeeds. Both sysctls are per network namespace, so containers an engine starts inside keep the kernel defaults. Co-authored-by: Cursor (cherry picked from commit 0002fe49a611d10112ff5347f92ef24edc791178) --- internal/ocispec/microvm.go | 30 ++++++++++++++++-------------- internal/ocispec/microvm_test.go | 6 ++++++ 2 files changed, 22 insertions(+), 14 deletions(-) diff --git a/internal/ocispec/microvm.go b/internal/ocispec/microvm.go index 2eb95a2620..f1c5354007 100644 --- a/internal/ocispec/microvm.go +++ b/internal/ocispec/microvm.go @@ -88,20 +88,14 @@ func ShapeMicroVM(spec *specs.Spec, o MicroVMOptions) error { } } } - if o.Privileged { - shapePrivileged(spec) - return nil - } - // Mask each directory with a read-only tmpfs, as runc's maskDir does. - // https://github.com/opencontainers/runc/blob/7d36b05953ebb377900a0a565d8b0754e464be0b/libcontainer/rootfs_linux.go#L1338-L1350 - for _, dir := range guestMaskedDirPaths(runtime.GOARCH) { - spec.Mounts = append(spec.Mounts, specs.Mount{Destination: dir, Type: "tmpfs", Source: "tmpfs", Options: []string{"ro", "nr_blocks=1", "nr_inodes=1"}}) - } - if spec.Linux == nil { spec.Linux = &specs.Linux{} } - // gVisor has no privileged-port limit, and runsc ignores this key. + // gVisor has no privileged-port limit, and runsc ignores this key. Privileged + // containers get it too: they still run their processes as the image's + // user, which binds its ports without CAP_NET_BIND_SERVICE. Both sysctls are + // per network namespace, so containers an engine starts inside keep the + // kernel defaults. if spec.Linux.Sysctl == nil { spec.Linux.Sysctl = map[string]string{} } @@ -113,6 +107,16 @@ func ShapeMicroVM(spec *specs.Spec, o MicroVMOptions) error { if _, ok := spec.Linux.Sysctl["net.ipv4.ping_group_range"]; !ok { spec.Linux.Sysctl["net.ipv4.ping_group_range"] = "0 2147483647" } + if o.Privileged { + shapePrivileged(spec) + return nil + } + // Mask each directory with a read-only tmpfs, as runc's maskDir does. + // https://github.com/opencontainers/runc/blob/7d36b05953ebb377900a0a565d8b0754e464be0b/libcontainer/rootfs_linux.go#L1338-L1350 + for _, dir := range guestMaskedDirPaths(runtime.GOARCH) { + spec.Mounts = append(spec.Mounts, specs.Mount{Destination: dir, Type: "tmpfs", Source: "tmpfs", Options: []string{"ro", "nr_blocks=1", "nr_inodes=1"}}) + } + // gVisor needs neither list: its procfs and sysfs leave out the masked // files and keep most of /proc/sys read-only. spec.Linux.MaskedPaths = guestMaskedFilePaths() @@ -127,9 +131,7 @@ func ShapeMicroVM(spec *specs.Spec, o MicroVMOptions) error { // equivalent of a privileged container under containerd inside the VM: no // masked or read-only paths, read-write /sys, a read-write cgroup2 mount, and // every guest device, with tun, fuse and kmsg nodes. Capabilities already hold -// the full set (atelet sets them with Privileged). The sysctls ShapeMicroVM -// sets for unprivileged containers are left out: a privileged container can -// set them itself, and a container engine inside expects the kernel defaults. +// the full set (atelet sets them with Privileged). func shapePrivileged(spec *specs.Spec) { makeSysfsWritable(spec) spec.Mounts = append(spec.Mounts, specs.Mount{ diff --git a/internal/ocispec/microvm_test.go b/internal/ocispec/microvm_test.go index 546371aca1..de8e68bcc4 100644 --- a/internal/ocispec/microvm_test.go +++ b/internal/ocispec/microvm_test.go @@ -341,6 +341,12 @@ func TestShapeMicroVM_Privileged(t *testing.T) { if diff := cmp.Diff([]string{"/dev/net/tun", "/dev/fuse", "/dev/kmsg"}, paths); diff != "" { t.Errorf("device nodes mismatch (-want +got):\n%s", diff) } + // The image's user still binds its ports and pings without capabilities. + for key, want := range map[string]string{"net.ipv4.ip_unprivileged_port_start": "0", "net.ipv4.ping_group_range": "0 2147483647"} { + if got := spec.Linux.Sysctl[key]; got != want { + t.Errorf("sysctl %s = %q, want %q", key, got, want) + } + } } func TestShapeMicroVM_UnprivilegedKeepsHardening(t *testing.T) { From 32649c900160b0a8ab26202026a7e9ecb079787f Mon Sep 17 00:00:00 2001 From: michaeljguarino Date: Sat, 28 Nov 2026 22:02:43 -0500 Subject: [PATCH 5/6] ateworker-microvm: stop killing busy micro-VMs over reclaimable page cache A busy guest fills its RAM with its own page cache, so cloud-hypervisor's memfd sits at the full guest size, and the host page cache of the guest's virtio-fs writes is charged to the same cgroup. Two things went wrong: - The MemoryGuard counted the guest's memfd (shmem) as used memory, which alone put the cgroup within 1/16 of its memory.high. Any reclaim stall from the host page cache of virtio-fs writes then read as stuck, and the whole VM was killed, e.g. during a large docker build or cargo build. - The booking left ~8MiB per GiB above the guest for cloud-hypervisor and virtiofsd, and nothing for that page cache, so every write reclaimed at memory.high. MemoryWatch now takes the memory a cgroup allocates up front and can't grow past (a micro-VM's guest RAM, read from vm.info on restore) and judges only the rest against what the limit leaves it. The hard overshoot cap is unchanged, and gVisor passes none. The micro-VM actor overhead books a sixteenth of the limit on top of the guest for the host page cache, so the guest keeps its full declared size. Co-authored-by: Cursor --- cmd/ateworker-microvm/internal/ch/ch.go | 20 ++++++++ cmd/ateworker-microvm/internal/ch/ch_test.go | 22 +++++++++ cmd/ateworker-microvm/restore.go | 7 +++ cmd/ateworker-microvm/run.go | 8 ++- cmd/ateworker-microvm/snapshotborrow_test.go | 4 +- internal/ateworker/cgroup/memguard.go | 9 +++- internal/ateworker/cgroup/memwatch.go | 12 ++++- internal/ateworker/cgroup/memwatch_test.go | 52 ++++++++++++++++++-- 8 files changed, 123 insertions(+), 11 deletions(-) diff --git a/cmd/ateworker-microvm/internal/ch/ch.go b/cmd/ateworker-microvm/internal/ch/ch.go index 25ecd9520c..49634fbd17 100644 --- a/cmd/ateworker-microvm/internal/ch/ch.go +++ b/cmd/ateworker-microvm/internal/ch/ch.go @@ -26,6 +26,7 @@ package ch import ( "context" + "errors" "fmt" "os" "time" @@ -101,6 +102,25 @@ func (c *Client) State(ctx context.Context) (string, error) { return info.State, nil } +// GuestMemoryBytes returns the guest RAM the VM was created or restored with, +// as reported by vm.info. +func (c *Client) GuestMemoryBytes(ctx context.Context) (uint64, error) { + var info struct { + Config struct { + Memory struct { + Size uint64 `json:"size"` + } `json:"memory"` + } `json:"config"` + } + if err := c.api.getJSON(ctx, "/api/v1/vm.info", &info); err != nil { + return 0, err + } + if info.Config.Memory.Size == 0 { + return 0, errors.New("vm.info reports no guest memory size") + } + return info.Config.Memory.Size, nil +} + // Pause pauses the running guest (quiescing it before snapshot). Idempotent: // already-paused is success (CH itself 500s on pausing a paused VM, which would // otherwise wedge checkpoint retries after a partial earlier attempt). diff --git a/cmd/ateworker-microvm/internal/ch/ch_test.go b/cmd/ateworker-microvm/internal/ch/ch_test.go index 2181c29530..39277df322 100644 --- a/cmd/ateworker-microvm/internal/ch/ch_test.go +++ b/cmd/ateworker-microvm/internal/ch/ch_test.go @@ -38,6 +38,8 @@ type fakeCH struct { mu sync.Mutex requests []recordedReq srv *http.Server + // vmInfo, when set, is the vm.info reply + vmInfo string } type recordedReq struct { @@ -60,7 +62,13 @@ func startFakeCH(t *testing.T) (*Client, *fakeCH) { body, _ := io.ReadAll(r.Body) f.mu.Lock() f.requests = append(f.requests, recordedReq{method: r.Method, path: r.URL.Path, body: string(body)}) + vmInfo := f.vmInfo f.mu.Unlock() + if r.URL.Path == "/api/v1/vm.info" && vmInfo != "" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(vmInfo)) + return + } if r.URL.Path == "/api/v1/vmm.ping" { // Mirror what a real VMM answers, which callers parse for its version. w.Header().Set("Content-Type", "application/json") @@ -84,6 +92,20 @@ func (f *fakeCH) recorded() []recordedReq { return out } +func TestGuestMemoryBytes(t *testing.T) { + client, fake := startFakeCH(t) + if _, err := client.GuestMemoryBytes(t.Context()); err == nil { + t.Error("GuestMemoryBytes() with no vm.info succeeded") + } + fake.mu.Lock() + fake.vmInfo = `{"config":{"memory":{"size":12079595520,"shared":true}},"state":"Running","memory_actual_size":12079595520}` + fake.mu.Unlock() + got, err := client.GuestMemoryBytes(t.Context()) + if err != nil || got != 12079595520 { + t.Errorf("GuestMemoryBytes() = %d, %v, want 12079595520", got, err) + } +} + func TestClientLifecycleCalls(t *testing.T) { client, fake := startFakeCH(t) ctx := context.Background() diff --git a/cmd/ateworker-microvm/restore.go b/cmd/ateworker-microvm/restore.go index 33e718a657..7db53b7f42 100644 --- a/cmd/ateworker-microvm/restore.go +++ b/cmd/ateworker-microvm/restore.go @@ -544,6 +544,13 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo if err := s.tunnel.ActivateIngress(p.attribution(), s.sandboxDialer(p.actorUID)); err != nil { return err } + // The guest keeps the size it was snapshotted with, not the actor's current limit. + if guest, err := client.GuestMemoryBytes(ctx); err != nil { + slog.WarnContext(ctx, "Failed to read the restored guest's memory size; its memory guard counts guest RAM as used", + slog.String("id", actorUID), slog.Any("err", err)) + } else { + ra.memory.SetFixed(guest) + } ra.memory.Resume(uint64(s.leafMemoryHigh(p.size.MemoryBytes))) s.setRunningVM(actorUID, ra) go s.watchVM(p.attribution(), p.actorDirs, ra) diff --git a/cmd/ateworker-microvm/run.go b/cmd/ateworker-microvm/run.go index 0a59fc229f..94c2a41836 100644 --- a/cmd/ateworker-microvm/run.go +++ b/cmd/ateworker-microvm/run.go @@ -145,8 +145,11 @@ const kataAgentPath = "/usr/bin/kata-agent" // actorOverhead is what an actor costs outside its guest, in the same worker // pod cgroup, which the control plane books with every actor: cloud-hypervisor // and virtiofsd, and the host page tables for guest RAM, KVM's EPT and the -// memfd's xarray. -var actorOverhead = &ateletpb.RuntimeOverhead{MemoryBytes: 4 << 20, MemoryBytesPerGib: 8 << 20} +// memfd's xarray (8MiB per GiB), plus room for the host page cache of the +// guest's virtio-fs I/O (a sixteenth). A busy guest keeps its RAM full of its +// own page cache, so without that room every write through virtiofsd reclaims +// at memory.high. +var actorOverhead = &ateletpb.RuntimeOverhead{MemoryBytes: 4 << 20, MemoryBytesPerGib: 8<<20 + 64<<20} // memoryReservedBytes is how much of the worker pod's memory limit we keep from // actors: the worker process itself, and the page cache of snapshot writes in @@ -616,6 +619,7 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) if err := s.tunnel.ActivateIngress(p.attribution(), s.sandboxDialer(p.actorUID)); err != nil { return err } + ra.memory.SetFixed(uint64(memMiB) << 20) ra.memory.Resume(uint64(s.leafMemoryHigh(p.size.MemoryBytes))) s.setRunningVM(actorUID, ra) go s.watchVM(p.attribution(), p.actorDirs, ra) diff --git a/cmd/ateworker-microvm/snapshotborrow_test.go b/cmd/ateworker-microvm/snapshotborrow_test.go index 69abd9496a..8cf6e6db20 100644 --- a/cmd/ateworker-microvm/snapshotborrow_test.go +++ b/cmd/ateworker-microvm/snapshotborrow_test.go @@ -30,8 +30,8 @@ func TestUnbookedMemory(t *testing.T) { "a": {memoryBytes: 1 << 30}, "b": {memoryBytes: 512 << 20}, }} - // 4MiB each, plus 8MiB per GiB - want := int64(limit - memoryReservedBytes - (1<<30 + 4<<20 + 8<<20) - (512<<20 + 4<<20 + 4<<20)) + // 4MiB each, plus 72MiB per GiB + want := int64(limit - memoryReservedBytes - (1<<30 + 4<<20 + 72<<20) - (512<<20 + 4<<20 + 36<<20)) if got := s.unbookedMemory(limit); got != want { t.Errorf("unbookedMemory() = %d, want %d", got, want) } diff --git a/internal/ateworker/cgroup/memguard.go b/internal/ateworker/cgroup/memguard.go index 728a891d12..85bf53f976 100644 --- a/internal/ateworker/cgroup/memguard.go +++ b/internal/ateworker/cgroup/memguard.go @@ -40,6 +40,7 @@ const MemoryGuardInterval = 250 * time.Millisecond // memory.high. It does nothing until Resume arms it with the limit. type MemoryGuard struct { limit atomic.Uint64 + fixed atomic.Uint64 killed atomic.Bool // mu is held while a check or a kill runs, and guards watch mu sync.Mutex @@ -66,7 +67,7 @@ func (g *MemoryGuard) Check(ctx context.Context, root, name string) (Kill, bool) g.mu.Unlock() return Kill{}, false } - over, current, err := g.watch.Check(filepath.Join(root, name), limit, time.Now()) + over, current, err := g.watch.Check(filepath.Join(root, name), limit, g.fixed.Load(), time.Now()) if err != nil || !over { // a read fails when the cgroup is going away g.mu.Unlock() @@ -96,6 +97,12 @@ func (g *MemoryGuard) Pause() uint64 { return g.limit.Swap(0) } +// SetFixed sets the memory the cgroup allocates up front and can't grow past, +// such as a microVM's guest RAM (see MemoryWatch.Check). It outlasts Pause. +func (g *MemoryGuard) SetFixed(bytes uint64) { + g.fixed.Store(bytes) +} + // Resume arms the guard for limit, from a fresh window. A limit of 0 leaves it // paused. func (g *MemoryGuard) Resume(limit uint64) { diff --git a/internal/ateworker/cgroup/memwatch.go b/internal/ateworker/cgroup/memwatch.go index db67fe89fc..0c27136cd0 100644 --- a/internal/ateworker/cgroup/memwatch.go +++ b/internal/ateworker/cgroup/memwatch.go @@ -61,13 +61,20 @@ type stallSample struct { // memoryStallWindow and hitting its own memory.high, or when over the limit by // more than 1/16 of it or memoryOvershootMax at all. // +// fixed is memory the cgroup allocates up front and can't grow past, such as a +// microVM's guest RAM, which a busy guest keeps whole with its own page cache. +// It is left out of "within 1/16 of the limit": what's judged is the rest +// against what the limit leaves it, so reclaiming the cgroup's page cache with +// the guest full isn't taken for being stuck. The guest's kernel enforces the +// guest's own ceiling. +// // Stalls rather than memory.current over the limit, because reclaim keeps // pulling a throttled cgroup back under memory.high between allocations, and // at only a little over it a cgroup stalls about half the time. "some" rather // than "full", because busy threads alongside a throttled one hide a full // stall. Its own memory.high events, so stalls from node-wide reclaim don't // count. -func (w *MemoryWatch) Check(dir string, limit uint64, now time.Time) (bool, uint64, error) { +func (w *MemoryWatch) Check(dir string, limit, fixed uint64, now time.Time) (bool, uint64, error) { current, err := memoryCurrent(dir) if err != nil { return false, 0, err @@ -87,7 +94,8 @@ func (w *MemoryWatch) Check(dir string, limit uint64, now time.Time) (bool, uint if used > limit+min(limit/16, memoryOvershootMax) { return true, current, nil } - if used < limit-limit/16 { + fixed = min(fixed, used, limit) + if rest := limit - fixed; used-fixed < rest-rest/16 { w.samples = w.samples[:0] return false, current, nil } diff --git a/internal/ateworker/cgroup/memwatch_test.go b/internal/ateworker/cgroup/memwatch_test.go index 2121a5c66f..5d66c35042 100644 --- a/internal/ateworker/cgroup/memwatch_test.go +++ b/internal/ateworker/cgroup/memwatch_test.go @@ -139,7 +139,7 @@ func TestMemoryWatch(t *testing.T) { "memory.stat": memoryStat(s.current-min(s.cache, s.current), s.cache), "memory.pressure": fmt.Sprintf("some avg10=0.00 avg60=0.00 avg300=0.00 total=%d\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0\n", s.stallMs*1000), }) - got, current, err := w.Check(dir, limit, start.Add(s.after)) + got, current, err := w.Check(dir, limit, 0, start.Add(s.after)) if err != nil { t.Fatal(err) } @@ -151,6 +151,50 @@ func TestMemoryWatch(t *testing.T) { } } +// A microVM whose guest has filled its RAM with page cache, stalled while the +// host reclaims the page cache of its virtio-fs writes, is not stuck: its guest +// RAM is fixed. It still is once the memory outside the guest fills what the +// limit leaves it. +func TestMemoryWatchFixed(t *testing.T) { + const ( + guest = 12288 << 20 + limit = 13156 << 20 // the guest's 12GiB plus 4MiB and 72MiB per GiB booked on top + ) + for _, tc := range []struct { + name string + fixed uint64 + outside uint64 // used memory besides the guest + want bool + }{ + {name: "guest counted as used", fixed: 0, outside: 100 << 20, want: true}, + {name: "guest left out", fixed: guest, outside: 100 << 20, want: false}, + {name: "outside the guest near the limit", fixed: guest, outside: limit - guest - 32<<20, want: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + start := time.Now() + used := guest + tc.outside + var w MemoryWatch + var got bool + for i, stallMs := range []uint64{0, 500, 1000} { + writeCgroupFiles(t, dir, map[string]string{ + "memory.events.local": fmt.Sprintf("high %d\n", stallMs), + "memory.current": fmt.Sprint(limit + 4<<20), + "memory.stat": memoryStat(used, limit+4<<20-used), + "memory.pressure": fmt.Sprintf("some avg10=0.00 avg60=0.00 avg300=0.00 total=%d\n", stallMs*1000), + }) + var err error + if got, _, err = w.Check(dir, limit, tc.fixed, start.Add(time.Duration(i)*500*time.Millisecond)); err != nil { + t.Fatal(err) + } + } + if got != tc.want { + t.Errorf("Check() = %v, want %v", got, tc.want) + } + }) + } +} + // A big cgroup may go only memoryOvershootMax over its limit, not 1/16 of it. func TestMemoryWatchCapsOvershoot(t *testing.T) { const limit = 8 << 30 @@ -169,7 +213,7 @@ func TestMemoryWatchCapsOvershoot(t *testing.T) { "memory.events.local": "high 0\n", }) var w MemoryWatch - if got, _, err := w.Check(dir, limit, time.Now()); err != nil || got != tc.want { + if got, _, err := w.Check(dir, limit, 0, time.Now()); err != nil || got != tc.want { t.Errorf("Check() at %d over = %v, %v, want %v", tc.current-limit, got, err, tc.want) } } @@ -177,7 +221,7 @@ func TestMemoryWatchCapsOvershoot(t *testing.T) { func TestMemoryWatchMissingCgroup(t *testing.T) { var w MemoryWatch - if _, _, err := w.Check(filepath.Join(t.TempDir(), "gone"), 1, time.Now()); err == nil { + if _, _, err := w.Check(filepath.Join(t.TempDir(), "gone"), 1, 0, time.Now()); err == nil { t.Error("Check() on a missing cgroup succeeded") } } @@ -195,7 +239,7 @@ func TestMemoryWatchStaleStat(t *testing.T) { "memory.events.local": "high 0\n", }) var w MemoryWatch - if got, _, err := w.Check(dir, limit, time.Now()); err != nil || got { + if got, _, err := w.Check(dir, limit, 0, time.Now()); err != nil || got { t.Errorf("Check() = %v, %v, want false", got, err) } } From eb19e10e209f600a18f29d014442d83a6e0b07b9 Mon Sep 17 00:00:00 2001 From: michaeljguarino Date: Sun, 29 Nov 2026 00:23:33 -0500 Subject: [PATCH 6/6] ateworker-microvm: count VMM memory before the guest touches all its RAM The near-limit kill check left out up to the guest's declared size of all used memory, so until the guest had touched its whole RAM everything outside it (the VMM's and virtiofsd's anon and kernel memory) netted to zero, and a blowup there throttled the VM at memory.high until the hard overshoot kill instead of being caught by the stall check. Leave out only the guest RAM that is resident, the shmem the fixed size covers, and judge the rest against what the limit leaves besides the guest. A fully touched guest is judged as before. Co-authored-by: Cursor (cherry picked from commit 84027e7288cf6ba32f0525868eba890dcc802b71) --- internal/ateworker/cgroup/memwatch.go | 74 ++++++++++++++-------- internal/ateworker/cgroup/memwatch_test.go | 28 ++++---- 2 files changed, 63 insertions(+), 39 deletions(-) diff --git a/internal/ateworker/cgroup/memwatch.go b/internal/ateworker/cgroup/memwatch.go index 0c27136cd0..faf4c159a7 100644 --- a/internal/ateworker/cgroup/memwatch.go +++ b/internal/ateworker/cgroup/memwatch.go @@ -61,12 +61,13 @@ type stallSample struct { // memoryStallWindow and hitting its own memory.high, or when over the limit by // more than 1/16 of it or memoryOvershootMax at all. // -// fixed is memory the cgroup allocates up front and can't grow past, such as a -// microVM's guest RAM, which a busy guest keeps whole with its own page cache. -// It is left out of "within 1/16 of the limit": what's judged is the rest -// against what the limit leaves it, so reclaiming the cgroup's page cache with -// the guest full isn't taken for being stuck. The guest's kernel enforces the -// guest's own ceiling. +// fixed is shmem the cgroup can't grow past, such as a microVM's guest RAM, +// which a busy guest keeps whole with its own page cache. It is left out of +// "within 1/16 of the limit": what's judged is the rest of used, everything +// but the shmem fixed covers, against what the limit leaves besides fixed, so +// reclaiming the cgroup's page cache with the guest full isn't taken for being +// stuck, while the VMM's own memory counts before the guest has touched all of +// its RAM. The guest's kernel enforces the guest's own ceiling. // // Stalls rather than memory.current over the limit, because reclaim keeps // pulling a throttled cgroup back under memory.high between allocations, and @@ -87,15 +88,15 @@ func (w *MemoryWatch) Check(dir string, limit, fixed uint64, now time.Time) (boo } // page cache aside, e.g. a snapshot write's dirty pages, which reclaim // can't drop until they're written back - used, err := memoryUsed(dir) + used, shmem, err := memoryUsed(dir) if err != nil { return false, current, err } if used > limit+min(limit/16, memoryOvershootMax) { return true, current, nil } - fixed = min(fixed, used, limit) - if rest := limit - fixed; used-fixed < rest-rest/16 { + fixed = min(fixed, limit) + if rest := limit - fixed; used-min(fixed, shmem) < rest-rest/16 { w.samples = w.samples[:0] return false, current, nil } @@ -131,16 +132,23 @@ func memoryCurrent(dir string) (uint64, error) { return strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64) } -// memoryUsed is what the cgroup holds besides page cache, from one -// memory.stat read. memory.stat splits charged memory into anon, file, kernel -// and sock, where file is page cache plus shmem (memfd-backed memory such as a -// gVisor sentry's or a microVM guest's), so this is anon + shmem + kernel + -// sock. The kernel only flushes memory.stat past a threshold of updates, so it -// can trail memory.current, and mixing the two could count fresh page cache as -// used. +// memoryUsed is what the cgroup holds besides page cache, and the shmem part +// of it, from one memory.stat read. memory.stat splits charged memory into +// anon, file, kernel and sock, where file is page cache plus shmem +// (memfd-backed memory such as a gVisor sentry's or a microVM guest's), so this +// is anon + shmem + kernel + sock. The kernel only flushes memory.stat past a +// threshold of updates, so it can trail memory.current, and mixing the two +// could count fresh page cache as used. // https://github.com/torvalds/linux/blob/v7.0/mm/memcontrol.c#L561-L564 -func memoryUsed(dir string) (uint64, error) { - return sumMemoryStat(dir, memoryUsedStats...) +func memoryUsed(dir string) (used, shmem uint64, err error) { + stats, err := readMemoryStat(dir, memoryUsedStats...) + if err != nil { + return 0, 0, err + } + for _, v := range stats { + used += v + } + return used, stats["shmem"], nil } // memoryUsedStats are the memory.stat keys memoryUsed sums @@ -149,13 +157,26 @@ var memoryUsedStats = []string{"anon", "shmem", "kernel", "sock"} // sumMemoryStat sums keys from one read of dir's memory.stat, which must have // anon. func sumMemoryStat(dir string, keys ...string) (uint64, error) { - path := filepath.Join(dir, "memory.stat") - b, err := os.ReadFile(path) + stats, err := readMemoryStat(dir, keys...) if err != nil { return 0, err } var sum uint64 - var anon bool + for _, v := range stats { + sum += v + } + return sum, nil +} + +// readMemoryStat reads keys from one read of dir's memory.stat, which must +// have anon. +func readMemoryStat(dir string, keys ...string) (map[string]uint64, error) { + path := filepath.Join(dir, "memory.stat") + b, err := os.ReadFile(path) + if err != nil { + return nil, err + } + stats := make(map[string]uint64, len(keys)) for line := range bytes.Lines(b) { f := bytes.Fields(line) if len(f) != 2 || !slices.Contains(keys, string(f[0])) { @@ -163,15 +184,14 @@ func sumMemoryStat(dir string, keys ...string) (uint64, error) { } v, err := strconv.ParseUint(string(f[1]), 10, 64) if err != nil { - return 0, fmt.Errorf("parsing %s in %q: %w", f[0], path, err) + return nil, fmt.Errorf("parsing %s in %q: %w", f[0], path, err) } - sum += v - anon = anon || string(f[0]) == "anon" + stats[string(f[0])] = v } - if !anon { - return 0, fmt.Errorf("no anon in %q", path) + if _, ok := stats["anon"]; !ok { + return nil, fmt.Errorf("no anon in %q", path) } - return sum, nil + return stats, nil } // memoryStall is memory.pressure's some total: microseconds during which at diff --git a/internal/ateworker/cgroup/memwatch_test.go b/internal/ateworker/cgroup/memwatch_test.go index 5d66c35042..67a71eda24 100644 --- a/internal/ateworker/cgroup/memwatch_test.go +++ b/internal/ateworker/cgroup/memwatch_test.go @@ -161,27 +161,31 @@ func TestMemoryWatchFixed(t *testing.T) { limit = 13156 << 20 // the guest's 12GiB plus 4MiB and 72MiB per GiB booked on top ) for _, tc := range []struct { - name string - fixed uint64 - outside uint64 // used memory besides the guest - want bool + name string + fixed uint64 + resident uint64 // the guest RAM the guest has touched, in shmem + outside uint64 // used memory besides the guest, in anon + want bool }{ - {name: "guest counted as used", fixed: 0, outside: 100 << 20, want: true}, - {name: "guest left out", fixed: guest, outside: 100 << 20, want: false}, - {name: "outside the guest near the limit", fixed: guest, outside: limit - guest - 32<<20, want: true}, + {name: "guest counted as used", fixed: 0, resident: guest, outside: 100 << 20, want: true}, + {name: "guest left out", fixed: guest, resident: guest, outside: 100 << 20, want: false}, + {name: "outside the guest near the limit", fixed: guest, resident: guest, outside: limit - guest - 32<<20, want: true}, + {name: "guest partly touched", fixed: guest, resident: guest / 2, outside: 100 << 20, want: false}, + {name: "outside a partly touched guest near the limit", fixed: guest, resident: guest / 2, outside: limit - guest - 32<<20, want: true}, } { t.Run(tc.name, func(t *testing.T) { dir := t.TempDir() start := time.Now() - used := guest + tc.outside + cache := limit + 4<<20 - tc.resident - tc.outside var w MemoryWatch var got bool for i, stallMs := range []uint64{0, 500, 1000} { writeCgroupFiles(t, dir, map[string]string{ "memory.events.local": fmt.Sprintf("high %d\n", stallMs), "memory.current": fmt.Sprint(limit + 4<<20), - "memory.stat": memoryStat(used, limit+4<<20-used), - "memory.pressure": fmt.Sprintf("some avg10=0.00 avg60=0.00 avg300=0.00 total=%d\n", stallMs*1000), + "memory.stat": fmt.Sprintf("anon %d\nfile %d\nkernel 0\nsock 0\nshmem %d\ninactive_file %d\nactive_file 0\n", + tc.outside, tc.resident+cache, tc.resident, cache), + "memory.pressure": fmt.Sprintf("some avg10=0.00 avg60=0.00 avg300=0.00 total=%d\n", stallMs*1000), }) var err error if got, _, err = w.Check(dir, limit, tc.fixed, start.Add(time.Duration(i)*500*time.Millisecond)); err != nil { @@ -251,7 +255,7 @@ func TestMemoryUsed(t *testing.T) { writeCgroupFiles(t, dir, map[string]string{ "memory.stat": "anon 1\nfile 104\nkernel 2\nsock 4\nshmem 8\nfile_dirty 16\ninactive_file 32\nactive_file 64\n", }) - if got, err := memoryUsed(dir); err != nil || got != 1+2+4+8 { - t.Errorf("memoryUsed() = %d, %v, want 15", got, err) + if used, shmem, err := memoryUsed(dir); err != nil || used != 1+2+4+8 || shmem != 8 { + t.Errorf("memoryUsed() = %d, %d, %v, want 15, 8", used, shmem, err) } }