diff --git a/config/base/crd/metal.datumapis.com.yaml b/config/base/crd/metal.datumapis.com.yaml index f01dfd76..e4c805c2 100644 --- a/config/base/crd/metal.datumapis.com.yaml +++ b/config/base/crd/metal.datumapis.com.yaml @@ -223,7 +223,18 @@ spec: (has(self.networkInterfaces) && has(oldSelf.networkInterfaces) && self.networkInterfaces == oldSelf.networkInterfaces)) message: allocation inputs are immutable + - rule: >- + (!has(self.creator) && !has(oldSelf.creator)) || + (has(self.creator) && has(oldSelf.creator) && self.creator == oldSelf.creator) + message: creator is immutable properties: + creator: + type: object + description: The authenticated caller that created the Machine. Admission sets it; clients cannot choose it. + required: [username, uid] + properties: + username: {type: string, minLength: 1} + uid: {type: string, minLength: 1} machineClassRef: {type: object, required: [name], properties: {name: {type: string}}} machineProfileRef: {type: object, required: [name], properties: {name: {type: string}}} locationRef: {type: object, required: [name], properties: {name: {type: string}}} diff --git a/config/components/machine-admission/kustomization.yaml b/config/components/machine-admission/kustomization.yaml new file mode 100644 index 00000000..e1e551fe --- /dev/null +++ b/config/components/machine-admission/kustomization.yaml @@ -0,0 +1,9 @@ +# Machine creator admission: the webhooks that record who created each +# Machine and add its protection finalizer in the same write. The +# fleet-registration server serves them. No root includes this component +# yet: the finalizer needs a manager that releases Machines, and the +# production manager's lifecycle handlers are still blocked. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - webhook.yaml diff --git a/config/components/machine-admission/webhook.yaml b/config/components/machine-admission/webhook.yaml new file mode 100644 index 00000000..0ae140fa --- /dev/null +++ b/config/components/machine-admission/webhook.yaml @@ -0,0 +1,47 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + name: fleet-machine-creator +webhooks: + # Milo's root API server calls this webhook, because Milo does not evaluate + # admission policies stored in a project. On create it writes the + # authenticated caller into spec.creator, replacing any client value, and + # adds the Machine protection finalizer. It is fail-closed. + - name: creator.machines.metal.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + reinvocationPolicy: Never + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/mutate-machine-creator + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE] + resources: [machines] + scope: Namespaced +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-machine-creator +webhooks: + # Runs after every mutating webhook. It refuses a create whose creator is + # not the caller or that lacks the protection finalizer, and any change to + # the creator. Status writes are not routed. + - name: creator.machines.metal.datumapis.com + admissionReviewVersions: [v1] + failurePolicy: Fail + matchPolicy: Equivalent + sideEffects: None + timeoutSeconds: 10 + clientConfig: + url: https://fleet-registration.fleet-system.svc:9443/validate-machine-creator + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE] + resources: [machines] + scope: Namespaced diff --git a/docs/development/README.md b/docs/development/README.md index 77018a02..e01b7a45 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -58,6 +58,16 @@ Redfish Interface Emulator and a lab-only libvirt adapter, and that run passes every phase on custody too. They are not qualified against a physical BMC or server, and the production manager does not use them. +Machine creator admission is **implemented** and not packaged in any root. +Two webhooks that the registration server serves record the authenticated +caller in a Machine's `spec.creator`, replacing any value the client sent, and +add the Machine protection finalizer in the same create. They refuse a caller +without a Milo project context and any later change to the creator, and a CRD +rule keeps the creator unchanged if the webhooks are bypassed. Tests against a +real API server verify it. No handler reads the creator yet, and no Machine +without one is refused. See the [production admission +proposal](https://github.com/datum-cloud/fleet/pull/187). + Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. diff --git a/go.mod b/go.mod index 1bf7468f..5cdd7e75 100644 --- a/go.mod +++ b/go.mod @@ -67,7 +67,7 @@ require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect - github.com/evanphx/json-patch/v5 v5.9.11 // indirect + github.com/evanphx/json-patch/v5 v5.9.11 github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fxamacker/cbor/v2 v2.9.1 // indirect github.com/go-logr/zapr v1.3.0 // indirect diff --git a/internal/api/v1alpha1/crd_validation_test.go b/internal/api/v1alpha1/crd_validation_test.go index 3f2cabde..b0aff3a4 100644 --- a/internal/api/v1alpha1/crd_validation_test.go +++ b/internal/api/v1alpha1/crd_validation_test.go @@ -164,6 +164,35 @@ func TestMachineRequestedHardwareIsPinnedOnceAccepted(t *testing.T) { } } +func machineWithCreator(creator map[string]any) map[string]any { + machine := machineWithStatus(map[string]any{}) + if creator != nil { + machine["spec"].(map[string]any)["creator"] = creator + } + return machine +} + +// The creator rule holds even if the admission webhooks are bypassed. +func TestMachineCreatorIsImmutable(t *testing.T) { + crd := loadCRDs(t)["machines.metal.datumapis.com"] + creator := map[string]any{"username": "customer-example", "uid": "customer-example-uid"} + if errs := validateObject(t, crd, machineWithCreator(creator), machineWithCreator(creator)); len(errs) > 0 { + t.Fatalf("unchanged creator rejected: %v", errs.ToAggregate()) + } + for name, test := range map[string]struct{ next, old map[string]any }{ + "changed username": {machineWithCreator(map[string]any{"username": "other", "uid": "customer-example-uid"}), machineWithCreator(creator)}, + "changed UID": {machineWithCreator(map[string]any{"username": "customer-example", "uid": "other"}), machineWithCreator(creator)}, + "removed": {machineWithCreator(nil), machineWithCreator(creator)}, + "added later": {machineWithCreator(creator), machineWithCreator(nil)}, + "empty username": {machineWithCreator(map[string]any{"username": "", "uid": "customer-example-uid"}), nil}, + "missing UID": {machineWithCreator(map[string]any{"username": "customer-example"}), nil}, + } { + if errs := validateObject(t, crd, test.next, test.old); len(errs) == 0 { + t.Errorf("%s creator was accepted", name) + } + } +} + func TestMachinePrinterColumnsShowRequestedHardware(t *testing.T) { crd := loadCRDs(t)["machines.metal.datumapis.com"] columns := map[string]extensionsv1.CustomResourceColumnDefinition{} diff --git a/internal/api/v1alpha1/types.go b/internal/api/v1alpha1/types.go index 6e52f9cb..03fe31b4 100644 --- a/internal/api/v1alpha1/types.go +++ b/internal/api/v1alpha1/types.go @@ -205,6 +205,16 @@ type MachineSpec struct { InitialInstallationRef *LocalReference `json:"initialInstallationRef,omitempty"` NetworkInterfaces []NetworkInterfaceRequest `json:"networkInterfaces,omitempty"` PowerState string `json:"powerState,omitempty"` + // Creator is the authenticated caller that created the Machine. Fleet's + // admission webhooks set it on create and refuse any other value or any + // change, so a client cannot choose it. + Creator *MachineCreator `json:"creator,omitempty"` +} + +// MachineCreator names the caller that created a Machine. +type MachineCreator struct { + Username string `json:"username"` + UID string `json:"uid"` } type NamespacedReference struct { Namespace string `json:"namespace,omitempty"` diff --git a/internal/machineadmission/envtest_test.go b/internal/machineadmission/envtest_test.go new file mode 100644 index 00000000..022acc1b --- /dev/null +++ b/internal/machineadmission/envtest_test.go @@ -0,0 +1,236 @@ +package machineadmission + +import ( + "bytes" + "context" + "encoding/pem" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/go-logr/logr" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrllog "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + "sigs.k8s.io/yaml" + + "go.datum.net/fleet/internal/allocation" + metal "go.datum.net/fleet/internal/api/v1alpha1" +) + +// TestCreatorAgainstAPIServer serves both handlers behind the packaged +// webhook configurations. The API server passes the original caller to the +// webhooks, as Milo's root API server does, so the stored creator is the +// caller's whatever the client sent. +func TestCreatorAgainstAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + root := filepath.Join("..", "..") + environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join(root, "config", "base", "crd")}, ErrorIfCRDPathMissing: true} + config, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = environment.Stop() }) + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{metal.AddToScheme, admissionregistrationv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + admin, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + mux := http.NewServeMux() + mux.Handle(MutatePath, &admission.Webhook{Handler: Mutator{}}) + mux.Handle(ValidatePath, &admission.Webhook{Handler: Validator{}}) + server := httptest.NewTLSServer(mux) + t.Cleanup(server.Close) + data, err := os.ReadFile(filepath.Join(root, "config", "components", "machine-admission", "webhook.yaml")) + if err != nil { + t.Fatal(err) + } + caBundle := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}) + readdress := func(config *admissionregistrationv1.WebhookClientConfig, path string) { + if config.URL == nil || !strings.HasSuffix(*config.URL, path) { + t.Fatalf("the packaged webhook must call %s", path) + } + url := server.URL + path + *config = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: caBundle} + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + var configured []string + for { + var raw runtime.RawExtension + if err := decoder.Decode(&raw); err != nil { + break + } + kind := struct{ Kind string }{} + if err := yaml.Unmarshal(raw.Raw, &kind); err != nil { + t.Fatal(err) + } + switch kind.Kind { + case "MutatingWebhookConfiguration": + webhooks := &admissionregistrationv1.MutatingWebhookConfiguration{} + if err := yaml.UnmarshalStrict(raw.Raw, webhooks); err != nil { + t.Fatal(err) + } + for index := range webhooks.Webhooks { + readdress(&webhooks.Webhooks[index].ClientConfig, MutatePath) + } + if err := admin.Create(context.Background(), webhooks); err != nil { + t.Fatal(err) + } + case "ValidatingWebhookConfiguration": + webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} + if err := yaml.UnmarshalStrict(raw.Raw, webhooks); err != nil { + t.Fatal(err) + } + for index := range webhooks.Webhooks { + readdress(&webhooks.Webhooks[index].ClientConfig, ValidatePath) + } + if err := admin.Create(context.Background(), webhooks); err != nil { + t.Fatal(err) + } + } + configured = append(configured, kind.Kind) + } + if !slices.Equal(configured, []string{"MutatingWebhookConfiguration", "ValidatingWebhookConfiguration"}) { + t.Fatalf("packaged webhooks = %v", configured) + } + actor := func(name, project string) client.Client { + cfg := rest.CopyConfig(config) + cfg.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {project}}} + api, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + return api + } + newMachine := func(creator *metal.MachineCreator) *metal.Machine { + return &metal.Machine{ObjectMeta: metav1.ObjectMeta{GenerateName: "machine-", Namespace: "default"}, Spec: metal.MachineSpec{ + MachineClassRef: metal.LocalReference{Name: "class"}, MachineProfileRef: metal.LocalReference{Name: "profile"}, LocationRef: metal.LocalReference{Name: "location"}, PowerState: "Off", Creator: creator, + }} + } + customer := actor("customer-example", "consumer-example") + self := metal.MachineCreator{Username: "customer-example", UID: "customer-example-uid"} + ctx := context.Background() + // The webhooks may take a moment to engage. + deadline := time.Now().Add(15 * time.Second) + for !apierrors.IsForbidden(admin.Create(ctx, newMachine(nil), client.DryRunAll)) { + if time.Now().After(deadline) { + t.Fatal("Machine creator webhooks did not engage") + } + time.Sleep(50 * time.Millisecond) + } + + t.Run("the stored creator is the original caller", func(t *testing.T) { + for name, sent := range map[string]*metal.MachineCreator{"none": nil, "someone else": {Username: "other", UID: "other-uid"}, "the caller": &self} { + t.Run(name, func(t *testing.T) { + created := newMachine(sent) + if err := customer.Create(ctx, created); err != nil { + t.Fatal(err) + } + stored := &metal.Machine{} + if err := admin.Get(ctx, client.ObjectKeyFromObject(created), stored); err != nil { + t.Fatal(err) + } + if stored.Spec.Creator == nil || *stored.Spec.Creator != self { + t.Fatalf("creator = %+v", stored.Spec.Creator) + } + if !slices.Contains(stored.Finalizers, allocation.MachineFinalizer) { + t.Fatalf("finalizers = %v", stored.Finalizers) + } + }) + } + }) + t.Run("the creator cannot change", func(t *testing.T) { + created := newMachine(nil) + if err := customer.Create(ctx, created); err != nil { + t.Fatal(err) + } + // Another caller in the project may update the Machine without + // becoming its creator. + stored := &metal.Machine{} + if err := admin.Get(ctx, client.ObjectKeyFromObject(created), stored); err != nil { + t.Fatal(err) + } + stored.Spec.PowerState = "On" + if err := actor("other-example", "consumer-example").Update(ctx, stored); err != nil { + t.Fatalf("update keeping the creator: %v", err) + } + for name, change := range map[string]*metal.MachineCreator{"another creator": {Username: "other-example", UID: "other-example-uid"}, "no creator": nil} { + if err := admin.Get(ctx, client.ObjectKeyFromObject(created), stored); err != nil { + t.Fatal(err) + } + stored.Spec.Creator = change + if err := customer.Update(ctx, stored); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("%s: %v", name, err) + } + } + }) + t.Run("a Machine recreated with the same name does not inherit its creator", func(t *testing.T) { + first := newMachine(nil) + first.GenerateName, first.Name = "", "machine-recreated" + if err := customer.Create(ctx, first); err != nil { + t.Fatal(err) + } + stored := &metal.Machine{} + if err := admin.Get(ctx, client.ObjectKeyFromObject(first), stored); err != nil { + t.Fatal(err) + } + previous := stored.UID + // Release the Machine as the manager would, then delete it. + stored.Finalizers = nil + if err := admin.Update(ctx, stored); err != nil { + t.Fatal(err) + } + if err := admin.Delete(ctx, stored); err != nil { + t.Fatal(err) + } + deadline := time.Now().Add(15 * time.Second) + for !apierrors.IsNotFound(admin.Get(ctx, client.ObjectKeyFromObject(first), &metal.Machine{})) { + if time.Now().After(deadline) { + t.Fatal("the first Machine was not deleted") + } + time.Sleep(50 * time.Millisecond) + } + // Another caller recreates the name and sends the old creator. + second := newMachine(&self) + second.GenerateName, second.Name = "", "machine-recreated" + if err := actor("other-example", "consumer-example").Create(ctx, second); err != nil { + t.Fatal(err) + } + if err := admin.Get(ctx, client.ObjectKeyFromObject(second), stored); err != nil { + t.Fatal(err) + } + if stored.UID == previous { + t.Fatal("the recreated Machine kept its UID") + } + if stored.Spec.Creator == nil || *stored.Spec.Creator != (metal.MachineCreator{Username: "other-example", UID: "other-example-uid"}) { + t.Fatalf("recreated creator = %+v", stored.Spec.Creator) + } + }) + t.Run("a caller without a project is refused", func(t *testing.T) { + // The API server's own identity carries no project. + if err := admin.Create(ctx, newMachine(&self)); !apierrors.IsForbidden(err) { + t.Fatalf("root identity: %v", err) + } + }) +} diff --git a/internal/machineadmission/handler.go b/internal/machineadmission/handler.go new file mode 100644 index 00000000..2a570a9a --- /dev/null +++ b/internal/machineadmission/handler.go @@ -0,0 +1,197 @@ +// Package machineadmission records who created a Machine. +// +// Milo's root API server calls both webhooks, because Milo does not evaluate +// admission policies stored in a project. The request's UserInfo is the +// original caller, as Milo's routing establishes it, with the project in its +// extras. The mutating webhook writes that caller into spec.creator and adds +// the Machine protection finalizer in the create itself, replacing any +// creator the client sent. The validating webhook refuses a create whose +// creator is not the caller or that lacks the finalizer, and any change to +// the creator. A controller can therefore trust spec.creator: only these +// webhooks could have set it. Neither webhook reads anything, keeps state or +// holds credentials. +package machineadmission + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "slices" + + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + "gomodules.xyz/jsonpatch/v2" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + "go.datum.net/fleet/internal/allocation" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/tenancy" +) + +const ( + // MutatePath and ValidatePath are where the handlers are served. + MutatePath = "/mutate-machine-creator" + ValidatePath = "/validate-machine-creator" +) + +// Mutator sets spec.creator to the caller and adds the protection +// finalizer on create. +type Mutator struct{} + +// Validator admits creates whose creator is the caller and that carry the +// protection finalizer, and updates that leave the creator unchanged. +type Validator struct{} + +// consumer returns the typed reference to the caller's Milo project. Milo +// sets the parent extras when it routes a request through a project control +// plane, and overwrites any the client supplied. A Machine created through +// Milo has a Project consumer; tenancy refuses any other kind. +func consumer(actor authenticationv1.UserInfo) (metal.TypedReference, error) { + group, kind, name := actor.Extra[iam.ParentAPIGroupExtraKey], actor.Extra[iam.ParentKindExtraKey], actor.Extra[iam.ParentNameExtraKey] + if len(group) != 1 || len(kind) != 1 || len(name) != 1 { + return metal.TypedReference{}, errors.New("an authenticated Milo project context is required") + } + ref := metal.TypedReference{APIGroup: group[0], Kind: kind[0], Name: name[0]} + if err := tenancy.Supported(ref); err != nil || ref != tenancy.Project(ref.Name) { + return metal.TypedReference{}, errors.New("an authenticated Milo project context is required") + } + return ref, nil +} + +// caller returns the creator for an authenticated caller in a Milo project. +func caller(actor authenticationv1.UserInfo) (metal.MachineCreator, error) { + if _, err := consumer(actor); err != nil { + return metal.MachineCreator{}, err + } + if actor.Username == "" || actor.UID == "" { + return metal.MachineCreator{}, errors.New("an authenticated caller and project are required") + } + return metal.MachineCreator{Username: actor.Username, UID: actor.UID}, nil +} + +func supported(request admission.Request) bool { + return request.Resource.Group == metal.GroupVersion.Group && request.Resource.Resource == "machines" && request.SubResource == "" +} + +// decode reads the object with exact, case-sensitive keys, as the API +// server does. encoding/json into a struct would match keys without regard +// to case. Numbers stay exact, although nothing is re-encoded from them. +func decode(raw []byte) (map[string]any, map[string]any, error) { + var object map[string]any + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + if err := decoder.Decode(&object); err != nil { + return nil, nil, err + } + spec, ok := object["spec"].(map[string]any) + if !ok { + return nil, nil, errors.New("spec is not an object") + } + return object, spec, nil +} + +// creatorOf returns spec.creator, or nil when it is absent. +func creatorOf(spec map[string]any) (*metal.MachineCreator, error) { + value, ok := spec["creator"] + if !ok { + return nil, nil + } + fields, ok := value.(map[string]any) + if !ok { + return nil, errors.New("spec.creator is not an object") + } + username, _ := fields["username"].(string) + uid, _ := fields["uid"].(string) + return &metal.MachineCreator{Username: username, UID: uid}, nil +} + +func finalizers(object map[string]any) []string { + metadata, _ := object["metadata"].(map[string]any) + values, _ := metadata["finalizers"].([]any) + var result []string + for _, value := range values { + if name, ok := value.(string); ok { + result = append(result, name) + } + } + return result +} + +func (Mutator) Handle(_ context.Context, request admission.Request) admission.Response { + if !supported(request) || request.Operation != admissionv1.Create { + return admission.Denied("unsupported Machine creator admission request") + } + creator, err := caller(request.UserInfo) + if err != nil { + return admission.Denied(err.Error()) + } + object, spec, err := decode(request.Object.Raw) + if err != nil { + return admission.Denied("the Machine could not be decoded") + } + metadata, ok := object["metadata"].(map[string]any) + if !ok { + return admission.Denied("the Machine could not be decoded") + } + // Patch only the two fields, so nothing else in the request is + // re-encoded. + value := map[string]any{"username": creator.Username, "uid": creator.UID} + patches := []jsonpatch.JsonPatchOperation{jsonpatch.NewOperation("add", "/spec/creator", value)} + if _, ok := spec["creator"]; ok { + patches[0] = jsonpatch.NewOperation("replace", "/spec/creator", value) + } + if !slices.Contains(finalizers(object), allocation.MachineFinalizer) { + if existing, ok := metadata["finalizers"].([]any); ok && existing != nil { + patches = append(patches, jsonpatch.NewOperation("add", "/metadata/finalizers/-", allocation.MachineFinalizer)) + } else { + patches = append(patches, jsonpatch.NewOperation("add", "/metadata/finalizers", []string{allocation.MachineFinalizer})) + } + } + return admission.Patched("the creator is the caller", patches...) +} + +func (Validator) Handle(_ context.Context, request admission.Request) admission.Response { + if !supported(request) { + return admission.Denied("unsupported Machine creator admission request") + } + switch request.Operation { + case admissionv1.Create: + expected, err := caller(request.UserInfo) + if err != nil { + return admission.Denied(err.Error()) + } + object, spec, err := decode(request.Object.Raw) + if err != nil { + return admission.Denied("the Machine could not be decoded") + } + creator, err := creatorOf(spec) + if err != nil || creator == nil || *creator != expected { + return admission.Denied("spec.creator must be the authenticated caller's username and UID") + } + if !slices.Contains(finalizers(object), allocation.MachineFinalizer) { + return admission.Denied("a Machine is created with the protection finalizer") + } + return admission.Allowed("the creator is the caller") + case admissionv1.Update: + _, spec, err := decode(request.Object.Raw) + if err != nil { + return admission.Denied("the Machine could not be decoded") + } + _, previousSpec, err := decode(request.OldObject.Raw) + if err != nil { + return admission.Denied("the Machine could not be decoded") + } + creator, err := creatorOf(spec) + if err != nil { + return admission.Denied("spec.creator cannot change") + } + previous, err := creatorOf(previousSpec) + if err != nil || (creator == nil) != (previous == nil) || (creator != nil && *creator != *previous) { + return admission.Denied("spec.creator cannot change") + } + return admission.Allowed("the creator is unchanged") + } + return admission.Denied("unsupported Machine creator admission request") +} diff --git a/internal/machineadmission/handler_test.go b/internal/machineadmission/handler_test.go new file mode 100644 index 00000000..7db7c8a8 --- /dev/null +++ b/internal/machineadmission/handler_test.go @@ -0,0 +1,284 @@ +package machineadmission + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "strings" + "testing" + + jsonpatch "github.com/evanphx/json-patch/v5" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + "go.datum.net/fleet/internal/allocation" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/tenancy" +) + +func actor(name, project string) authenticationv1.UserInfo { + return authenticationv1.UserInfo{Username: name, UID: name + "-uid", Extra: map[string]authenticationv1.ExtraValue{ + iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {project}, + }} +} + +func machine(t *testing.T, creator *metal.MachineCreator, finalizers ...string) runtime.RawExtension { + t.Helper() + data, err := json.Marshal(metal.Machine{ + TypeMeta: metav1.TypeMeta{APIVersion: metal.GroupVersion.String(), Kind: "Machine"}, + ObjectMeta: metav1.ObjectMeta{Name: "machine-example", Namespace: "default", Finalizers: finalizers}, + Spec: metal.MachineSpec{MachineClassRef: metal.LocalReference{Name: "class"}, MachineProfileRef: metal.LocalReference{Name: "profile"}, LocationRef: metal.LocalReference{Name: "location"}, Creator: creator}, + }) + if err != nil { + t.Fatal(err) + } + return runtime.RawExtension{Raw: data} +} + +func request(operation admissionv1.Operation, user authenticationv1.UserInfo, newObject, oldObject runtime.RawExtension) admission.Request { + return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Operation: operation, UserInfo: user, Object: newObject, OldObject: oldObject, + Resource: metav1.GroupVersionResource{Group: metal.GroupVersion.Group, Version: "v1alpha1", Resource: "machines"}, + }} +} + +// apply returns the Machine the API server would store after the mutation. +func apply(t *testing.T, raw []byte, response admission.Response) metal.Machine { + t.Helper() + patches, err := json.Marshal(response.Patches) + if err != nil { + t.Fatal(err) + } + patch, err := jsonpatch.DecodePatch(patches) + if err != nil { + t.Fatal(err) + } + patched, err := patch.Apply(raw) + if err != nil { + t.Fatal(err) + } + var result metal.Machine + if err := json.Unmarshal(patched, &result); err != nil { + t.Fatal(err) + } + return result +} + +func TestMutatorRecordsTheCaller(t *testing.T) { + user := actor("customer-example", "consumer-example") + self := metal.MachineCreator{Username: "customer-example", UID: "customer-example-uid"} + for name, sent := range map[string]*metal.MachineCreator{ + "no creator": nil, + "someone else": {Username: "other", UID: "other-uid"}, + "the caller's name": {Username: "customer-example", UID: "forged"}, + "the caller already": &self, + } { + t.Run(name, func(t *testing.T) { + raw := machine(t, sent, "example.com/other") + response := Mutator{}.Handle(context.Background(), request(admissionv1.Create, user, raw, runtime.RawExtension{})) + if !response.Allowed { + t.Fatalf("refused: %s", response.Result.Message) + } + stored := apply(t, raw.Raw, response) + if stored.Spec.Creator == nil || *stored.Spec.Creator != self { + t.Fatalf("creator = %+v", stored.Spec.Creator) + } + if len(stored.Finalizers) != 2 || stored.Finalizers[0] != "example.com/other" || stored.Finalizers[1] != allocation.MachineFinalizer { + t.Fatalf("finalizers = %v", stored.Finalizers) + } + // The mutated Machine passes validation. + validated := Validator{}.Handle(context.Background(), request(admissionv1.Create, user, machine(t, stored.Spec.Creator, stored.Finalizers...), runtime.RawExtension{})) + if !validated.Allowed { + t.Fatalf("mutated Machine refused: %s", validated.Result.Message) + } + }) + } + t.Run("the finalizer is not added twice", func(t *testing.T) { + raw := machine(t, nil, allocation.MachineFinalizer) + stored := apply(t, raw.Raw, Mutator{}.Handle(context.Background(), request(admissionv1.Create, user, raw, runtime.RawExtension{}))) + if len(stored.Finalizers) != 1 { + t.Fatalf("finalizers = %v", stored.Finalizers) + } + }) +} + +func TestMutatorRefuses(t *testing.T) { + noProject := actor("customer-example", "consumer-example") + delete(noProject.Extra, iam.ParentNameExtraKey) + organization := actor("customer-example", "consumer-example") + organization.Extra[iam.ParentKindExtraKey] = authenticationv1.ExtraValue{"Organization"} + noUID := actor("customer-example", "consumer-example") + noUID.UID = "" + other := request(admissionv1.Create, actor("customer-example", "consumer-example"), machine(t, nil), runtime.RawExtension{}) + other.Resource.Resource = "installations" + status := request(admissionv1.Create, actor("customer-example", "consumer-example"), machine(t, nil), runtime.RawExtension{}) + status.SubResource = "status" + for name, request := range map[string]admission.Request{ + "no project": request(admissionv1.Create, noProject, machine(t, nil), runtime.RawExtension{}), + "an organization": request(admissionv1.Create, organization, machine(t, nil), runtime.RawExtension{}), + "no caller UID": request(admissionv1.Create, noUID, machine(t, nil), runtime.RawExtension{}), + "an update": request(admissionv1.Update, actor("customer-example", "consumer-example"), machine(t, nil), machine(t, nil)), + "another resource": other, + "a subresource": status, + "an undecodable Machine": request(admissionv1.Create, actor("customer-example", "consumer-example"), runtime.RawExtension{Raw: []byte(`{"spec":"x"}`)}, runtime.RawExtension{}), + } { + t.Run(name, func(t *testing.T) { + if response := (Mutator{}).Handle(context.Background(), request); response.Allowed { + t.Fatal("allowed") + } + }) + } +} + +func TestValidator(t *testing.T) { + user := actor("customer-example", "consumer-example") + self := &metal.MachineCreator{Username: "customer-example", UID: "customer-example-uid"} + other := &metal.MachineCreator{Username: "other", UID: "other-uid"} + none := runtime.RawExtension{} + cases := map[string]struct { + request admission.Request + allowed bool + }{ + "a create naming the caller with the finalizer": {request(admissionv1.Create, user, machine(t, self, allocation.MachineFinalizer), none), true}, + "a create without the finalizer": {request(admissionv1.Create, user, machine(t, self), none), false}, + "a create without a creator": {request(admissionv1.Create, user, machine(t, nil, allocation.MachineFinalizer), none), false}, + "a create naming someone else": {request(admissionv1.Create, user, machine(t, other, allocation.MachineFinalizer), none), false}, + "another caller claiming this caller": {request(admissionv1.Create, actor("other", "consumer-example"), machine(t, self, allocation.MachineFinalizer), none), false}, + "an update keeping the creator": {request(admissionv1.Update, user, machine(t, self), machine(t, self, allocation.MachineFinalizer)), true}, + "another caller's update keeping the creator": {request(admissionv1.Update, actor("other", "consumer-example"), machine(t, self), machine(t, self)), true}, + "an update changing the creator": {request(admissionv1.Update, user, machine(t, other), machine(t, self)), false}, + "an update removing the creator": {request(admissionv1.Update, user, machine(t, nil), machine(t, self)), false}, + "an update adding a creator": {request(admissionv1.Update, user, machine(t, self), machine(t, nil)), false}, + "an update of a Machine that never had one": {request(admissionv1.Update, user, machine(t, nil), machine(t, nil)), true}, + "a delete": {request(admissionv1.Delete, user, none, machine(t, self)), false}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + if response := (Validator{}).Handle(context.Background(), test.request); response.Allowed != test.allowed { + t.Fatalf("allowed = %v: %s", response.Allowed, response.Result.Message) + } + }) + } +} + +// TestMutatorPatchesOnlyTheCreatorAndFinalizer covers request shapes a +// client could send to keep its own creator or to disturb other fields. +func TestMutatorPatchesOnlyTheCreatorAndFinalizer(t *testing.T) { + user := actor("customer-example", "consumer-example") + for name, raw := range map[string]string{ + "a null creator": `{"metadata":{"name":"m"},"spec":{"creator":null}}`, + "a string creator": `{"metadata":{"name":"m"},"spec":{"creator":"customer-example"}}`, + "a capitalized Creator": `{"metadata":{"name":"m"},"spec":{"Creator":{"username":"other","uid":"other-uid"}}}`, + "null finalizers": `{"metadata":{"name":"m","finalizers":null},"spec":{}}`, + "a large integer": `{"metadata":{"name":"m"},"spec":{"big":9007199254740993}}`, + } { + t.Run(name, func(t *testing.T) { + response := Mutator{}.Handle(context.Background(), request(admissionv1.Create, user, runtime.RawExtension{Raw: []byte(raw)}, runtime.RawExtension{})) + if !response.Allowed { + t.Fatalf("refused: %s", response.Result.Message) + } + patches, err := json.Marshal(response.Patches) + if err != nil { + t.Fatal(err) + } + patch, err := jsonpatch.DecodePatch(patches) + if err != nil { + t.Fatal(err) + } + patched, err := patch.Apply([]byte(raw)) + if err != nil { + t.Fatal(err) + } + var stored map[string]any + decoder := json.NewDecoder(bytes.NewReader(patched)) + decoder.UseNumber() + if err := decoder.Decode(&stored); err != nil { + t.Fatal(err) + } + spec := stored["spec"].(map[string]any) + if creator, _ := spec["creator"].(map[string]any); creator["username"] != "customer-example" || creator["uid"] != "customer-example-uid" { + t.Fatalf("creator = %v", spec["creator"]) + } + if finalizers, _ := stored["metadata"].(map[string]any)["finalizers"].([]any); len(finalizers) != 1 || finalizers[0] != allocation.MachineFinalizer { + t.Fatalf("finalizers = %v", finalizers) + } + // Other fields pass through untouched, including a key that only + // differs in case and an integer above 2^53. + for key, value := range spec { + if key != "creator" && !strings.Contains(raw, fmt.Sprintf("%q:", key)) { + t.Fatalf("unexpected field %s = %v", key, value) + } + } + if big, ok := spec["big"]; ok && big.(json.Number).String() != "9007199254740993" { + t.Fatalf("big = %v", big) + } + if _, ok := spec["Creator"]; strings.Contains(raw, `"Creator"`) && !ok { + t.Fatal("the Creator field was removed") + } + }) + } + t.Run("a Machine without metadata", func(t *testing.T) { + if response := (Mutator{}).Handle(context.Background(), request(admissionv1.Create, user, runtime.RawExtension{Raw: []byte(`{"spec":{}}`)}, runtime.RawExtension{})); response.Allowed { + t.Fatal("allowed") + } + }) +} + +func TestValidatorRefusesMalformedCreators(t *testing.T) { + user := actor("customer-example", "consumer-example") + for name, raw := range map[string]string{ + "a null creator": `{"metadata":{"finalizers":["` + allocation.MachineFinalizer + `"]},"spec":{"creator":null}}`, + "a string creator": `{"metadata":{"finalizers":["` + allocation.MachineFinalizer + `"]},"spec":{"creator":"customer-example"}}`, + "only a Creator": `{"metadata":{"finalizers":["` + allocation.MachineFinalizer + `"]},"spec":{"Creator":{"username":"customer-example","uid":"customer-example-uid"}}}`, + "null finalizers": `{"metadata":{"finalizers":null},"spec":{"creator":{"username":"customer-example","uid":"customer-example-uid"}}}`, + } { + t.Run(name, func(t *testing.T) { + if response := (Validator{}).Handle(context.Background(), request(admissionv1.Create, user, runtime.RawExtension{Raw: []byte(raw)}, runtime.RawExtension{})); response.Allowed { + t.Fatal("allowed") + } + }) + } +} + +// TestOnlyAMiloProjectConsumerIsAdmitted reads the caller's consumer as a +// typed reference through tenancy. Through Milo a Machine's consumer is a +// Project; a Namespace, another group or kind, or a missing name is refused +// by both webhooks. +func TestOnlyAMiloProjectConsumerIsAdmitted(t *testing.T) { + self := &metal.MachineCreator{Username: "customer-example", UID: "customer-example-uid"} + with := func(group, kind, name string) authenticationv1.UserInfo { + user := actor("customer-example", "consumer-example") + user.Extra[iam.ParentAPIGroupExtraKey] = authenticationv1.ExtraValue{group} + user.Extra[iam.ParentKindExtraKey] = authenticationv1.ExtraValue{kind} + user.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{name} + return user + } + if ref, err := consumer(actor("customer-example", "consumer-example")); err != nil || ref != tenancy.Project("consumer-example") { + t.Fatalf("consumer = %+v, %v", ref, err) + } + for name, user := range map[string]authenticationv1.UserInfo{ + "a Namespace": with("", tenancy.NamespaceKind, "consumer-example"), + "another group": with("example.com", tenancy.ProjectKind, "consumer-example"), + "another kind": with(tenancy.ProjectGroup, "Organization", "consumer-example"), + "an empty name": with(tenancy.ProjectGroup, tenancy.ProjectKind, ""), + "two project names": func() authenticationv1.UserInfo { + user := actor("customer-example", "consumer-example") + user.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{"consumer-example", "other"} + return user + }(), + } { + t.Run(name, func(t *testing.T) { + if response := (Mutator{}).Handle(context.Background(), request(admissionv1.Create, user, machine(t, nil), runtime.RawExtension{})); response.Allowed { + t.Fatal("the mutating webhook allowed it") + } + if response := (Validator{}).Handle(context.Background(), request(admissionv1.Create, user, machine(t, self, allocation.MachineFinalizer), runtime.RawExtension{})); response.Allowed { + t.Fatal("the validating webhook allowed it") + } + }) + } +} diff --git a/internal/registration/transport.go b/internal/registration/transport.go index 1e4be048..3f01ab50 100644 --- a/internal/registration/transport.go +++ b/internal/registration/transport.go @@ -6,6 +6,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "go.datum.net/fleet/internal/custody/creatorwebhook" + "go.datum.net/fleet/internal/machineadmission" "go.datum.net/fleet/internal/powerwebhook" ) @@ -19,6 +20,8 @@ func (handler *Handler) Transport(creator *creatorwebhook.Handler, power *powerw mux.Handle("/validate-registration", &admission.Webhook{Handler: handler}) mux.Handle(creatorwebhook.Path, &admission.Webhook{Handler: creator}) mux.Handle(powerwebhook.Path, &admission.Webhook{Handler: power}) + mux.Handle(machineadmission.MutatePath, &admission.Webhook{Handler: machineadmission.Mutator{}}) + mux.Handle(machineadmission.ValidatePath, &admission.Webhook{Handler: machineadmission.Validator{}}) mux.HandleFunc("/transportz", func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) })