Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions config/base/crd/metal.datumapis.com.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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}}}
Expand Down
9 changes: 9 additions & 0 deletions config/components/machine-admission/kustomization.yaml
Original file line number Diff line number Diff line change
@@ -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
47 changes: 47 additions & 0 deletions config/components/machine-admission/webhook.yaml
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions docs/development/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions internal/api/v1alpha1/crd_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand Down
10 changes: 10 additions & 0 deletions internal/api/v1alpha1/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
236 changes: 236 additions & 0 deletions internal/machineadmission/envtest_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
Loading
Loading