diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index 98c80483..0bcc377e 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -25,23 +25,25 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "go.datum.net/fleet/internal/custody/creatorwebhook" + "go.datum.net/fleet/internal/powerwebhook" ) func main() { - var configFile, providers, cert, key, clientCA string + var configFile, providers, powerWriter, cert, key, clientCA string flag.StringVar(&configFile, "config", "", "Fleet manager discovery configuration") flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider scope searched for duplicate hardware identity") + flag.StringVar(&powerWriter, "machine-power-writer", "", "username of the manager's Milo identity, the only writer of Machine status.power; empty refuses every power change") flag.StringVar(&cert, "tls-cert", "/etc/fleet/registration/tls.crt", "serving certificate") flag.StringVar(&key, "tls-key", "/etc/fleet/registration/tls.key", "serving key") flag.StringVar(&clientCA, "client-ca", "/etc/fleet/registration/client-ca.crt", "CA dedicated to trusted API-server webhook clients") flag.Parse() - if err := run(ctrl.SetupSignalHandler(), configFile, providers, cert, key, clientCA); err != nil { + if err := run(ctrl.SetupSignalHandler(), configFile, providers, powerWriter, cert, key, clientCA); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run(ctx context.Context, configFile, providers, cert, key, clientCA string) error { +func run(ctx context.Context, configFile, providers, powerWriter, cert, key, clientCA string) error { config, err := projectdiscovery.LoadConfig(configFile) if err != nil { return err @@ -76,7 +78,7 @@ func run(ctx context.Context, configFile, providers, cert, key, clientCA string) if err != nil { return err } - server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(&creatorwebhook.Handler{Projects: projects, Resources: creatorwebhook.Resources}), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} + server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(&creatorwebhook.Handler{Projects: projects, Resources: creatorwebhook.Resources}, &powerwebhook.Handler{Writer: powerWriter}), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} go func() { <-ctx.Done() shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/config/README.md b/config/README.md index b1cb911b..9d3572bb 100644 --- a/config/README.md +++ b/config/README.md @@ -38,13 +38,21 @@ The one `fleet-manager` Deployment serves every Milo project that consumes the `metal` service; see [project discovery](#project-discovery). The separate `fleet-registration` Deployment serves inert inventory-backed -capacity admission only. It keeps no state: each capacity create is checked -against live Devices and capacities in the provider projects. Its TLS trust, -read/SAR credentials and webhook serving CA are environment-owned; it has no -host RBAC and mounts no service account token. Read the +capacity admission, the operation creator webhook, and the Machine power +webhook. `config/components/machine-power-admission` admits a change to a +Machine's `status.power` only from the identity named by `fleet-registration`'s +`--machine-power-writer` flag, the manager's Milo identity; unset, every power +change is refused. `config/milo` includes it, and `config/standalone` enforces +the same rule with a ValidatingAdmissionPolicy. See +[Machine power](../docs/development/device-custody.md#machine-power). +The service keeps no state: each capacity create is checked against live +Devices and capacities in the provider projects. Its TLS trust, read/SAR +credentials and webhook serving CA are environment-owned; it has no host RBAC +and mounts no service account token. Read the [registration rollout contract](../docs/development/inventory-capacity-registration.md#production-packaging-and-rollout) -before applying either root: an unavailable service blocks capacity writes -globally, and nothing else. Pod TCP readiness is transport-only; it must not +before applying either root: an unavailable service blocks capacity writes, +operation creates and Machine power changes globally, and nothing else. Pod +TCP readiness is transport-only; it must not enable UI registration. This does not enable production allocation or provisioning. diff --git a/config/components/machine-power-admission/kustomization.yaml b/config/components/machine-power-admission/kustomization.yaml new file mode 100644 index 00000000..4fd00748 --- /dev/null +++ b/config/components/machine-power-admission/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - webhook.yaml diff --git a/config/components/machine-power-admission/webhook.yaml b/config/components/machine-power-admission/webhook.yaml new file mode 100644 index 00000000..686e158b --- /dev/null +++ b/config/components/machine-power-admission/webhook.yaml @@ -0,0 +1,33 @@ +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingWebhookConfiguration +metadata: + name: fleet-machine-power +webhooks: + # The manager's power projector is the only writer of a Machine's + # status.power. RBAC cannot hold that field to one writer: Milo authorizes a + # status write with the Machine's update and patch permissions, which the + # consumer roles hold. Milo's root API server calls this webhook, because + # Milo does not evaluate admission policies stored in a project. Only status + # writes that change status.power are routed, so an unavailable service + # blocks power changes and nothing else. It is fail-closed. The + # fleet-registration server serves it; its --machine-power-writer flag names + # the projector's identity, and without it every power change is refused. + - name: power.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-power + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [UPDATE] + resources: [machines/status] + scope: Namespaced + matchConditions: + - name: power-changes + expression: >- + (has(object.status) && has(object.status.power)) != (has(oldObject.status) && has(oldObject.status.power)) + || (has(object.status) && has(object.status.power) && object.status.power != oldObject.status.power) diff --git a/config/milo/kustomization.yaml b/config/milo/kustomization.yaml index 698ac665..8752e82f 100644 --- a/config/milo/kustomization.yaml +++ b/config/milo/kustomization.yaml @@ -7,3 +7,4 @@ resources: - ../components/inventory - ../components/registration-admission - ../components/device-operations + - ../components/machine-power-admission diff --git a/config/standalone/kustomization.yaml b/config/standalone/kustomization.yaml index 267e7b74..f6d886c2 100644 --- a/config/standalone/kustomization.yaml +++ b/config/standalone/kustomization.yaml @@ -12,6 +12,7 @@ resources: - rbac.yaml - fixtures.yaml - site.yaml + - machine-power.yaml - smoke-cronjobs.yaml images: - name: ghcr.io/datum-cloud/fleet-simulator diff --git a/config/standalone/machine-power.yaml b/config/standalone/machine-power.yaml new file mode 100644 index 00000000..873d5ad3 --- /dev/null +++ b/config/standalone/machine-power.yaml @@ -0,0 +1,29 @@ +# The power rule. Milo projects ignore admission policies, so Milo uses the +# Machine power webhook; a plain cluster enforces the same rule with this +# policy: only the power projector's identity changes a Machine's +# status.power. Here that is the smoke runner, which runs the manager's +# projector for its fixture Machines. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: {name: fleet-machine-power} +spec: + failurePolicy: Fail + matchConstraints: + resourceRules: + - apiGroups: [metal.datumapis.com] + apiVersions: ["*"] + operations: [UPDATE] + resources: [machines/status] + validations: + - expression: >- + request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-standalone-smoke' + || ((has(object.status) && has(object.status.power)) == (has(oldObject.status) && has(oldObject.status.power)) + && (!(has(object.status) && has(object.status.power)) || object.status.power == oldObject.status.power)) + message: Only the power projector writes status.power. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: {name: fleet-machine-power} +spec: + policyName: fleet-machine-power + validationActions: [Deny] diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 897486d7..c85727f4 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -356,6 +356,32 @@ manager, custody, allocation and Device events in the provider project wake the consumer's Machines, so a new hold shows as `Unknown` without a Machine event. +Admission keeps power to that one writer. RBAC alone cannot: Milo authorizes a +status write with the Machine's `update` and `patch` permissions, which the +consumer and claimant roles hold, and the manager's other status writers share +the projector's identity. + +| Mode | Guard | Writer | +| --- | --- | --- | +| Production Milo root (`config/milo`) | The Machine power webhook, served by `fleet-registration` at `/validate-machine-power`. Only status writes that change `status.power` are routed, fail-closed. | The username in `fleet-registration`'s `--machine-power-writer` flag: the manager's Milo identity. Unset, every power change is refused. Set it before a power projector runs against this root. | +| Standalone (`config/standalone`) | A ValidatingAdmissionPolicy on `machines/status` | The smoke runner's service account, which runs the projector for its fixtures | +| Synthetic Milo root and multi-plane local Milo | None. Neither runs `fleet-registration`, and Milo ignores policies stored in a project. RBAC grants Machine status only to the manager, but the consumer roles' `update` permission still reaches it. | See [Points for a person](#points-for-a-person) | + +Who can write Machine status, and who can change power: + +| Identity | Machine status | Power | +| --- | --- | --- | +| The manager: the power projector, the staging handler and the requested-hardware projector | All fields | The only writer, once the flag names it | +| The standalone smoke runner | Its fixture Machine | The only writer in standalone | +| Milo consumer and claimant roles | All fields, through `update` and `patch` | Refused | +| The Metal provider and allocator, the release controller, the custody coordinator, discovery, the inventory and operation roles, Karmada, kro and federation | None | None | + +Within the manager, the staging handler, the requested-hardware projector and +the runners carry power forward unchanged; admission cannot tell them apart +from the projector. A render check over every root in `config` fails if any +other Kubernetes role gains Machine status writes, or any other Milo role gains +a Machine status, update or patch permission. + ### Deleted, with no compatibility - The Secret-backed coordinator and its records, the private-record RBAC, the @@ -779,6 +805,16 @@ These need a decision before the increment that depends on them. `Healthy` and `Available` themselves. - **O10: the sealed store for bootstrap payloads.** Bootstrap stays refused in every increment until a store is chosen. +- **Machine status writes by consumers in Milo.** Milo's authorizer, with + subresource authorization off, checks a status write against `update` and + `patch`, which the consumer and claimant roles hold. The power webhook refuses + their power changes, but they can still write every other Machine status + field. Closing it needs subresource authorization enabled in Milo, the + Machine ProtectedResource to declare its status subresource, and the + controller role alone to hold `machines/status.update` and `.patch`. +- **The power guard in synthetic staging and the multi-plane local Milo.** + Neither runs `fleet-registration`, so neither has the power webhook, as + neither has the creator webhook. - **A second person for `DeviceRecovery`.** Not required yet. A person accepted this for now, and it stays open for a later decision. - **Synthetic staging needs its records imported again, new credentials and diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index e9a51e9f..be447d6b 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -554,6 +554,11 @@ synthetic ones. service blocks writes to inventory-backed capacity and nothing else: unmarked capacity, capacity status, Device, namespace and Project writes do not pass through the registration webhook. +- `config/milo` also includes the fail-closed + [Machine power webhook](device-custody.md#machine-power) on the same + service. It matches only Machine status writes that change `status.power`, + so an unreachable service also blocks power changes, and no other Machine + write. - No root in this repository includes Device deletion protection. A deploying repository adds `config/components/device-deletion-protection` to the root it applies to Milo when it must keep in-service Devices. @@ -586,8 +591,13 @@ Environment-owned inputs, none of which this repository supplies: 2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key` and a dedicated `client-ca.crt`. Configure Milo's admission webhook client with an API-server client certificate signed by that CA, patch the webhook URL for - reachability, and set `clientConfig.caBundle` to the serving CA. -3. Keep `--provider-projects` equal to the complete provider scope. + reachability, and set `clientConfig.caBundle` to the serving CA. Do the + same for the Machine power webhook, or every power change fails closed. +3. Keep `--provider-projects` equal to the complete provider scope. Before a + power projector runs against the root, set `--machine-power-writer` to the + username Milo reports for the manager's identity in a routed project + request. Confirm it with one of the manager's own status writes: a + mismatch refuses every power change. 4. Decide whether the Milo root you apply includes `config/components/device-deletion-protection`. With it, the only Device deletes admitted are of Retired Devices, of Devices in a deleting namespace, diff --git a/internal/powerwebhook/envtest_test.go b/internal/powerwebhook/envtest_test.go new file mode 100644 index 00000000..51ae5da4 --- /dev/null +++ b/internal/powerwebhook/envtest_test.go @@ -0,0 +1,269 @@ +package powerwebhook + +import ( + "context" + "encoding/pem" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/go-logr/logr" + metal "go.datum.net/fleet/internal/api/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" +) + +var root = filepath.Join("..", "..") + +// The identities that can reach Machine status in some mode, other than the +// power projector's. Each is impersonated with system:masters so that only +// admission decides. +var others = []string{ + "consumer-example", + "claimant-example", + "system:serviceaccount:fleet-system:fleet-custody-coordinator", + "system:serviceaccount:fleet-system:fleet-release-controller", + "system:serviceaccount:fleet-system:fleet-simulator", + "provider-example", + "discoverer-example", + "staff-example", +} + +func start(t *testing.T) (*rest.Config, client.Client, *runtime.Scheme) { + t.Helper() + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + ctrllog.SetLogger(logr.Discard()) + 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) + } + return config, admin, scheme +} + +func actor(t *testing.T, config *rest.Config, scheme *runtime.Scheme, name string) client.Client { + t.Helper() + cfg := rest.CopyConfig(config) + cfg.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: []string{"system:masters"}} + api, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + return api +} + +// powered creates a Machine whose status.power the writer has set. +func powered(t *testing.T, writer client.Client, admin client.Client, name string) *metal.Machine { + t.Helper() + ctx := context.Background() + machine := &metal.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "default", Name: name}, Spec: metal.MachineSpec{ + MachineClassRef: metal.LocalReference{Name: "class-example"}, MachineProfileRef: metal.LocalReference{Name: "profile-example"}, LocationRef: metal.LocalReference{Name: "location-example"}, PowerState: "Off", + }} + if err := admin.Create(ctx, machine); err != nil { + t.Fatal(err) + } + machine.Status.Phase = "Ready" + machine.Status.Power = &metal.PowerStatus{State: "Off"} + if err := writer.Status().Update(ctx, machine); err != nil { + t.Fatalf("the power projector's write: %v", err) + } + return machine +} + +// exercise proves the rule against a live API server: the writer changes +// power, and every other identity's power change is refused while its other +// status writes are admitted. +func exercise(t *testing.T, config *rest.Config, admin client.Client, scheme *runtime.Scheme, writerName string) { + ctx := context.Background() + writer := actor(t, config, scheme, writerName) + machine := powered(t, writer, admin, "power-example") + fresh := func() *metal.Machine { + current := &metal.Machine{} + if err := admin.Get(ctx, client.ObjectKeyFromObject(machine), current); err != nil { + t.Fatal(err) + } + return current + } + t.Run("the power projector changes and clears power", func(t *testing.T) { + current := fresh() + current.Status.Power = &metal.PowerStatus{State: "Unknown"} + if err := writer.Status().Update(ctx, current); err != nil { + t.Fatal(err) + } + current = fresh() + current.Status.Power = nil + if err := writer.Status().Update(ctx, current); err != nil { + t.Fatal(err) + } + current = fresh() + current.Status.Power = &metal.PowerStatus{State: "Off"} + if err := writer.Status().Update(ctx, current); err != nil { + t.Fatal(err) + } + }) + for _, name := range append(append([]string(nil), others...), "admin") { + t.Run(name, func(t *testing.T) { + api := admin + if name != "admin" { + api = actor(t, config, scheme, name) + } + for _, power := range []*metal.PowerStatus{{State: "On"}, {State: "Unknown"}, nil} { + current := fresh() + current.Status.Power = power + if err := api.Status().Update(ctx, current); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("power %+v: %v", power, err) + } + patch := client.MergeFrom(fresh()) + current = fresh() + current.Status.Power = power + if err := api.Status().Patch(ctx, current, patch); !apierrors.IsForbidden(err) && !apierrors.IsInvalid(err) { + t.Fatalf("patched power %+v: %v", power, err) + } + } + // Other status fields stay theirs to write; RBAC decides those. + current := fresh() + current.Status.Phase = map[string]string{"Ready": "Pending"}[current.Status.Phase] + if current.Status.Phase == "" { + current.Status.Phase = "Ready" + } + if err := api.Status().Update(ctx, current); err != nil { + t.Fatalf("a status write that keeps power: %v", err) + } + if fresh().Status.Power == nil || fresh().Status.Power.State != "Off" { + t.Fatalf("power changed to %+v", fresh().Status.Power) + } + }) + } + t.Run("a Machine update cannot change power", func(t *testing.T) { + current := fresh() + current.Status.Power = &metal.PowerStatus{State: "On"} + if err := actor(t, config, scheme, "consumer-example").Update(ctx, current); err != nil { + t.Fatal(err) + } + if fresh().Status.Power.State != "Off" { + t.Fatal("a main-resource update changed status.power") + } + }) +} + +// waitFor retries a dry-run power change by another identity on the probe +// until the guard refuses it, because admission configuration may take a +// moment to engage. +func waitFor(t *testing.T, config *rest.Config, admin client.Client, scheme *runtime.Scheme, probe *metal.Machine) { + t.Helper() + ctx := context.Background() + other := actor(t, config, scheme, "consumer-example") + deadline := time.Now().Add(15 * time.Second) + for { + current := &metal.Machine{} + if err := admin.Get(ctx, client.ObjectKeyFromObject(probe), current); err != nil { + t.Fatal(err) + } + current.Status.Power = &metal.PowerStatus{State: "On"} + if err := other.Status().Update(ctx, current, client.DryRunAll); apierrors.IsForbidden(err) || apierrors.IsInvalid(err) { + return + } + if time.Now().After(deadline) { + t.Fatal("the power guard did not engage") + } + time.Sleep(50 * time.Millisecond) + } +} + +// TestPowerWebhookAgainstAPIServer serves the handler behind the packaged +// webhook configuration. The API server passes the original caller, as +// Milo's root API server does. +func TestPowerWebhookAgainstAPIServer(t *testing.T) { + config, admin, scheme := start(t) + // The probe's power is set before the webhook exists. + probe := powered(t, admin, admin, "probe-example") + server := httptest.NewTLSServer(&admission.Webhook{Handler: &Handler{Writer: writer}}) + t.Cleanup(server.Close) + data, err := os.ReadFile(filepath.Join(root, "config", "components", "machine-power-admission", "webhook.yaml")) + if err != nil { + t.Fatal(err) + } + webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} + if err := yaml.UnmarshalStrict(data, webhooks); err != nil { + t.Fatal(err) + } + if len(webhooks.Webhooks) != 1 || !strings.HasSuffix(*webhooks.Webhooks[0].ClientConfig.URL, Path) || *webhooks.Webhooks[0].FailurePolicy != admissionregistrationv1.Fail { + t.Fatalf("the packaged webhook must call %s and fail closed", Path) + } + url := server.URL + Path + webhooks.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw})} + if err := admin.Create(context.Background(), webhooks); err != nil { + t.Fatal(err) + } + waitFor(t, config, admin, scheme, probe) + exercise(t, config, admin, scheme, writer) + + t.Run("only power changes are routed", func(t *testing.T) { + // With the service down, a power change fails closed and every other + // status write still succeeds. + server.Close() + ctx := context.Background() + current := &metal.Machine{} + if err := admin.Get(ctx, client.ObjectKey{Namespace: "default", Name: "power-example"}, current); err != nil { + t.Fatal(err) + } + current.Status.Phase = "Ready" + if err := admin.Status().Update(ctx, current); err != nil { + t.Fatalf("a status write that keeps power was routed: %v", err) + } + current.Status.Power = &metal.PowerStatus{State: "On"} + if err := actor(t, config, scheme, writer).Status().Update(ctx, current); err == nil { + t.Fatal("a power change was admitted without the webhook") + } + }) +} + +// TestStandalonePowerPolicyAgainstAPIServer applies the standalone +// ValidatingAdmissionPolicy. The smoke runner runs the power projector there, +// so its identity is the writer. +func TestStandalonePowerPolicyAgainstAPIServer(t *testing.T) { + config, admin, scheme := start(t) + probe := powered(t, admin, admin, "probe-example") + data, err := os.ReadFile(filepath.Join(root, "config", "standalone", "machine-power.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(strings.NewReader(string(data)), 4096) + policy := &admissionregistrationv1.ValidatingAdmissionPolicy{} + binding := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{} + for _, object := range []client.Object{policy, binding} { + if err := decoder.Decode(object); err != nil { + t.Fatal(err) + } + if err := admin.Create(context.Background(), object); err != nil { + t.Fatal(err) + } + } + waitFor(t, config, admin, scheme, probe) + exercise(t, config, admin, scheme, "system:serviceaccount:fleet-system:fleet-standalone-smoke") +} diff --git a/internal/powerwebhook/handler.go b/internal/powerwebhook/handler.go new file mode 100644 index 00000000..e1dc98b2 --- /dev/null +++ b/internal/powerwebhook/handler.go @@ -0,0 +1,66 @@ +// Package powerwebhook is the validating webhook that keeps the manager's +// power projector the only writer of a Machine's status.power. +// +// RBAC cannot keep that field to one writer. Milo's authorizer checks a status +// write against the Machine's own update and patch permissions, which the +// consumer roles hold, and Machine status has other writers that share the +// projector's identity. Milo's root API server calls this webhook, because +// Milo does not evaluate admission policies stored in a project. The request's +// UserInfo is the original caller. The webhook compares status.power on the +// old and new objects and admits a change only from the configured writer. +// It reads nothing, keeps no state and holds no credentials. +package powerwebhook + +import ( + "context" + "encoding/json" + "reflect" + + metal "go.datum.net/fleet/internal/api/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// Path is where the handler is served. +const Path = "/validate-machine-power" + +// Handler admits Machine status writes that leave status.power unchanged, and +// changes to it from the writer. +type Handler struct { + // Writer is the username of the power projector's identity: the + // manager's Milo identity. Empty refuses every change to status.power. + Writer string +} + +// powerOf reads status.power with exact, case-sensitive keys, as the API +// server does. encoding/json into a struct would match keys without regard +// to case and let a later duplicate win. An absent or null power is nil. +func powerOf(raw []byte) (any, error) { + var object map[string]any + if err := json.Unmarshal(raw, &object); err != nil { + return nil, err + } + status, _ := object["status"].(map[string]any) + return status["power"], nil +} + +func (h *Handler) Handle(_ context.Context, request admission.Request) admission.Response { + if request.Resource.Group != metal.GroupVersion.Group || request.Resource.Resource != "machines" || request.SubResource != "status" || request.Operation != admissionv1.Update { + return admission.Denied("unsupported Machine power admission request") + } + power, err := powerOf(request.Object.Raw) + if err != nil { + return admission.Denied("the Machine could not be decoded") + } + previous, err := powerOf(request.OldObject.Raw) + if err != nil { + return admission.Denied("the Machine could not be decoded") + } + if reflect.DeepEqual(power, previous) { + return admission.Allowed("status.power is unchanged") + } + if h.Writer != "" && request.UserInfo.Username == h.Writer { + return admission.Allowed("the power projector writes status.power") + } + return admission.Denied("only the power projector writes status.power") +} diff --git a/internal/powerwebhook/handler_test.go b/internal/powerwebhook/handler_test.go new file mode 100644 index 00000000..95d2cd23 --- /dev/null +++ b/internal/powerwebhook/handler_test.go @@ -0,0 +1,86 @@ +package powerwebhook + +import ( + "context" + "testing" + + 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" +) + +const writer = "manager-example" + +func raw(status string) runtime.RawExtension { + return runtime.RawExtension{Raw: []byte(`{"apiVersion":"metal.datumapis.com/v1alpha1","kind":"Machine","status":` + status + `}`)} +} + +func request(user string, newStatus, oldStatus string) admission.Request { + return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{ + Operation: admissionv1.Update, UserInfo: authenticationv1.UserInfo{Username: user, UID: user + "-uid"}, + Resource: metav1.GroupVersionResource{Group: "metal.datumapis.com", Version: "v1alpha1", Resource: "machines"}, + SubResource: "status", Object: raw(newStatus), OldObject: raw(oldStatus), + }} +} + +func TestHandler(t *testing.T) { + handler := &Handler{Writer: writer} + on, off := `{"phase":"Ready","power":{"state":"On"}}`, `{"phase":"Ready","power":{"state":"Off"}}` + none, pending := `{"phase":"Ready"}`, `{"phase":"Pending","power":{"state":"On"}}` + cases := map[string]struct { + request admission.Request + allowed bool + }{ + "the writer changes power": {request(writer, off, on), true}, + "the writer sets power": {request(writer, on, none), true}, + "the writer clears power": {request(writer, none, on), true}, + "another identity leaves power unchanged": {request("consumer-example", pending, on), true}, + "another identity with no power": {request("consumer-example", `{"phase":"Pending"}`, none), true}, + "another identity changes power": {request("consumer-example", off, on), false}, + "another identity sets power": {request("provider-example", on, none), false}, + "another identity clears power": {request("staff-example", none, on), false}, + "another identity adds a power field": {request("consumer-example", `{"power":{"state":"On","extra":"x"}}`, on), false}, + "a writer named only by prefix": {request(writer+"-other", off, on), false}, + "a null power equals an absent one": {request("consumer-example", `{"phase":"Ready","power":null}`, none), true}, + "a key that differs only by case is apart": {request("consumer-example", `{"phase":"Ready","Power":{"state":"Off"},"power":{"state":"On"}}`, on), true}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + if got := handler.Handle(context.Background(), test.request).Allowed; got != test.allowed { + t.Fatalf("allowed = %v, want %v", got, test.allowed) + } + }) + } + t.Run("no configured writer refuses every power change", func(t *testing.T) { + empty := &Handler{} + if empty.Handle(context.Background(), request("", off, on)).Allowed || empty.Handle(context.Background(), request(writer, off, on)).Allowed { + t.Fatal("a power change was admitted without a writer") + } + if !empty.Handle(context.Background(), request(writer, pending, on)).Allowed { + t.Fatal("an unchanged power was refused") + } + }) + t.Run("only Machine status updates are handled", func(t *testing.T) { + for _, mutate := range []func(*admission.Request){ + func(r *admission.Request) { r.SubResource = "" }, + func(r *admission.Request) { r.Resource.Resource = "installations" }, + func(r *admission.Request) { r.Resource.Group = "fleet.datumapis.com" }, + func(r *admission.Request) { r.Operation = admissionv1.Create }, + } { + r := request(writer, off, on) + mutate(&r) + if handler.Handle(context.Background(), r).Allowed { + t.Fatalf("admitted %+v", r.AdmissionRequest) + } + } + }) + t.Run("an undecodable object is refused", func(t *testing.T) { + r := request(writer, off, on) + r.Object.Raw = []byte("{") + if handler.Handle(context.Background(), r).Allowed { + t.Fatal("admitted an undecodable object") + } + }) +} diff --git a/internal/powerwebhook/render_test.go b/internal/powerwebhook/render_test.go new file mode 100644 index 00000000..35a63840 --- /dev/null +++ b/internal/powerwebhook/render_test.go @@ -0,0 +1,273 @@ +package powerwebhook + +import ( + "bytes" + "io" + "io/fs" + "os" + "os/exec" + "path/filepath" + "slices" + "sort" + "strings" + "testing" + + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "sigs.k8s.io/yaml" +) + +const standaloneWriter = "system:serviceaccount:fleet-system:fleet-standalone-smoke" + +// renderRoots builds every Kustomize root under config, keyed by directory. +// Components are rendered through the roots that include them. +func renderRoots(t *testing.T, kustomize, config string) map[string][]map[string]any { + t.Helper() + out := map[string][]map[string]any{} + err := filepath.WalkDir(config, func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || entry.Name() != "kustomization.yaml" { + return err + } + data, err := os.ReadFile(path) + if err != nil { + return err + } + var kustomization struct{ Kind string } + if err := yaml.Unmarshal(data, &kustomization); err != nil { + return err + } + if kustomization.Kind == "Component" { + return nil + } + dir := filepath.Dir(path) + rendered, err := exec.Command(kustomize, "build", dir).Output() + if err != nil { + t.Fatalf("kustomize build %s: %v", dir, err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(rendered), 4096) + for { + var object map[string]any + if err := decoder.Decode(&object); err == io.EOF { + break + } else if err != nil { + t.Fatalf("%s: %v", dir, err) + } + if object != nil { + out[dir] = append(out[dir], object) + } + } + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} + +// walk visits every map in a rendered object, including objects embedded as +// templates, such as a graph's resources, and YAML or JSON held in strings. +func walk(value any, visit func(map[string]any)) { + switch typed := value.(type) { + case map[string]any: + visit(typed) + for _, item := range typed { + walk(item, visit) + } + case []any: + for _, item := range typed { + walk(item, visit) + } + case string: + if strings.Contains(typed, "kind") { + decoder := utilyaml.NewYAMLOrJSONDecoder(strings.NewReader(typed), 4096) + for { + var object map[string]any + if decoder.Decode(&object) != nil { + return + } + walk(object, visit) + } + } + } +} + +func strs(value any) []string { + items, _ := value.([]any) + out := make([]string, 0, len(items)) + for _, item := range items { + if text, ok := item.(string); ok { + out = append(out, text) + } + } + return out +} + +func anyOf(values []string, wanted ...string) bool { + return slices.ContainsFunc(values, func(value string) bool { return slices.Contains(wanted, value) }) +} + +func name(object map[string]any) (string, string) { + metadata, _ := object["metadata"].(map[string]any) + namespace, _ := metadata["namespace"].(string) + value, _ := metadata["name"].(string) + return namespace, value +} + +// rbacStatusWriter reports whether a Kubernetes Role or ClusterRole can +// update or patch Machine status. An aggregated ClusterRole takes its rules +// from other roles at runtime, so it counts as a writer until reviewed. +func rbacStatusWriter(object map[string]any) bool { + if kind, _ := object["kind"].(string); kind != "Role" && kind != "ClusterRole" { + return false + } + if apiVersion, _ := object["apiVersion"].(string); !strings.HasPrefix(apiVersion, "rbac.authorization.k8s.io/") { + return false + } + if _, aggregated := object["aggregationRule"]; aggregated { + return true + } + rules, _ := object["rules"].([]any) + for _, item := range rules { + rule, _ := item.(map[string]any) + if anyOf(strs(rule["apiGroups"]), "*", "metal.datumapis.com") && anyOf(strs(rule["resources"]), "*", "*/status", "machines/*", "machines/status") && anyOf(strs(rule["verbs"]), "*", "update", "patch") { + return true + } + } + return false +} + +// TestOnlyThePowerWriterCanWriteMachineStatus renders every root under config +// and lists the roles that can write Machine status. Roles made outside +// config, by a script or at runtime, are not covered. Kubernetes RBAC grants +// it only to the standalone smoke runner, the power projector's identity +// there. Milo grants updateStatus and status permissions only to the +// controller role, the manager's. Milo's authorizer checks a status write +// against update and patch, so the consumer roles can write status too; the +// Machine power webhook refuses their power changes. A new holder of any of +// these fails. +func TestOnlyThePowerWriterCanWriteMachineStatus(t *testing.T) { + kustomize, err := exec.LookPath("kustomize") + if err != nil { + if os.Getenv("GITHUB_ACTIONS") == "true" { + t.Fatal("kustomize required") + } + t.Skip("kustomize required") + } + roots := renderRoots(t, kustomize, filepath.Join(root, "config")) + if len(roots) < 10 { + t.Fatalf("rendered %d roots", len(roots)) + } + var rbac []string + bound := map[string][]string{} + milo := map[string]struct { + permissions []string + inherits []string + }{} + for dir, objects := range roots { + for _, object := range objects { + walk(object, func(object map[string]any) { + namespace, objectName := name(object) + kind, _ := object["kind"].(string) + apiVersion, _ := object["apiVersion"].(string) + switch { + case rbacStatusWriter(object): + rbac = append(rbac, dir+" "+kind+" "+namespace+"/"+objectName) + case (kind == "RoleBinding" || kind == "ClusterRoleBinding") && strings.HasPrefix(apiVersion, "rbac.authorization.k8s.io/"): + ref, _ := object["roleRef"].(map[string]any) + role, _ := ref["name"].(string) + subjects, _ := object["subjects"].([]any) + for _, item := range subjects { + subject, _ := item.(map[string]any) + subjectKind, _ := subject["kind"].(string) + subjectNamespace, _ := subject["namespace"].(string) + subjectName, _ := subject["name"].(string) + if subjectKind == "ServiceAccount" { + subjectName = "system:serviceaccount:" + subjectNamespace + ":" + subjectName + } + key := dir + " " + namespace + "/" + role + bound[key] = append(bound[key], subjectName) + } + case kind == "Role" && strings.HasPrefix(apiVersion, "iam.miloapis.com/"): + spec, _ := object["spec"].(map[string]any) + entry := milo[objectName] + entry.permissions = append(entry.permissions, strs(spec["includedPermissions"])...) + inherited, _ := spec["inheritedRoles"].([]any) + for _, item := range inherited { + role, _ := item.(map[string]any) + if roleName, ok := role["name"].(string); ok { + entry.inherits = append(entry.inherits, roleName) + } + } + milo[objectName] = entry + } + }) + } + } + sort.Strings(rbac) + want := []string{ + filepath.Join(root, "config", "standalone") + " Role fleet-project-a/fleet-synthetic-consumer-writer", + filepath.Join(root, "config", "standalone") + " Role fleet-project-b/fleet-synthetic-consumer-writer", + } + if !slices.Equal(rbac, want) { + t.Fatalf("Kubernetes roles that write Machine status:\n%s\nwant only the standalone power writer's:\n%s", strings.Join(rbac, "\n"), strings.Join(want, "\n")) + } + for _, role := range rbac { + key := strings.Replace(role, " Role ", " ", 1) + if subjects := bound[key]; !slices.Equal(subjects, []string{standaloneWriter}) { + t.Fatalf("%s is bound to %v, want only %s", role, subjects, standaloneWriter) + } + } + policy, err := os.ReadFile(filepath.Join(root, "config", "standalone", "machine-power.yaml")) + if err != nil || !strings.Contains(string(policy), "request.userInfo.username == '"+standaloneWriter+"'") { + t.Fatalf("the standalone power policy must admit exactly %s", standaloneWriter) + } + + // holders resolves inheritance and returns the Milo roles that hold any + // of the permissions, directly or through an inherited role. + holders := func(permissions ...string) []string { + var out []string + var holds func(string, map[string]bool) bool + holds = func(role string, seen map[string]bool) bool { + if seen[role] { + return false + } + seen[role] = true + entry := milo[role] + if slices.ContainsFunc(entry.permissions, func(p string) bool { + return slices.Contains(permissions, p) || (strings.Contains(p, "*") && (strings.HasPrefix(p, "metal.datumapis.com/") || strings.HasPrefix(p, "*"))) + }) { + return true + } + return slices.ContainsFunc(entry.inherits, func(parent string) bool { return holds(parent, seen) }) + } + for role := range milo { + if holds(role, map[string]bool{}) { + out = append(out, role) + } + } + sort.Strings(out) + return out + } + if len(milo) == 0 { + t.Fatal("no Milo roles rendered") + } + if got := holders("metal.datumapis.com/machines.updateStatus", "metal.datumapis.com/machines/status.update", "metal.datumapis.com/machines/status.patch"); !slices.Equal(got, []string{"metal.datumapis.com-controller"}) { + t.Fatalf("Milo roles with Machine status permissions: %v, want only the controller role", got) + } + if got := holders("metal.datumapis.com/machines.update", "metal.datumapis.com/machines.patch"); !slices.Equal(got, []string{"metal.datumapis.com-claimant", "metal.datumapis.com-consumer", "metal.datumapis.com-controller"}) { + t.Fatalf("Milo roles that can write Machine status through update or patch: %v", got) + } + + // The guards are in the roots that hold Machines. + contains := func(dir, kind, objectName string) bool { + return slices.ContainsFunc(roots[filepath.Join(root, "config", dir)], func(object map[string]any) bool { + _, n := name(object) + return object["kind"] == kind && n == objectName + }) + } + if !contains("milo", "ValidatingWebhookConfiguration", "fleet-machine-power") { + t.Fatal("config/milo must install the Machine power webhook") + } + if !contains("standalone", "ValidatingAdmissionPolicy", "fleet-machine-power") || !contains("standalone", "ValidatingAdmissionPolicyBinding", "fleet-machine-power") { + t.Fatal("config/standalone must install the Machine power policy and its binding") + } +} diff --git a/internal/registration/transport.go b/internal/registration/transport.go index db0ecb6a..1e4be048 100644 --- a/internal/registration/transport.go +++ b/internal/registration/transport.go @@ -6,16 +6,19 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" "go.datum.net/fleet/internal/custody/creatorwebhook" + "go.datum.net/fleet/internal/powerwebhook" ) // Transport serves the validating webhooks and a transport probe. All sit // behind the same mutually authenticated TLS listener. The operation creator // webhook shares this server: it has the same caller, the same transport -// and the same provider scope, and it keeps no state. -func (handler *Handler) Transport(creator *creatorwebhook.Handler) http.Handler { +// and the same provider scope, and it keeps no state. The Machine power +// webhook shares it for the same reasons, across every consuming project. +func (handler *Handler) Transport(creator *creatorwebhook.Handler, power *powerwebhook.Handler) http.Handler { mux := http.NewServeMux() 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.HandleFunc("/transportz", func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) })