From 661af5b82ea440bf8f86079f503c1cf1fe2097a8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:32 -0600 Subject: [PATCH 01/16] refactor(registration): check live Devices only Remove the registration ledger and everything that served it: the Secret-backed CAS store, sealed segments, signed activation and expansion, the control ConfigMap and key, /activationz and /status, cmd/fleet-registration-control, the ledger retention policies and the ledger Secret RBAC. The webhook now keeps no state. A capacity create must be named device-, so the API server refuses a second capacity for the same Device. It is checked against the live Device, the caller's SARs, aliases on every live Device in the provider scope, and every existing capacity. The webhook fences capacity writes only; Device, namespace and Project writes no longer pass through it. The registration pod mounts no service account token. Co-Authored-By: Claude Opus 5.5 --- cmd/fleet-registration-control/main.go | 56 -- cmd/fleet-registration-control/main_test.go | 51 -- cmd/fleet-registration/main.go | 85 +-- config/base/registration/deployment.yaml | 8 +- config/base/registration/kustomization.yaml | 2 - config/base/registration/protection.yaml | 55 -- config/base/registration/rbac.yaml | 27 - .../registration-admission/webhook.yaml | 60 +- .../registration-exclusion.yaml | 40 +- .../registration-storage-rollout.md | 232 -------- internal/registration/admission.go | 443 +++----------- .../admission_regression_envtest_test.go | 436 -------------- .../registration/admission_regression_test.go | 75 --- internal/registration/admission_test.go | 479 ++++++--------- internal/registration/bounded_fences_test.go | 200 ------- .../registration/contention_envtest_test.go | 112 ---- internal/registration/control.go | 235 -------- internal/registration/control_test.go | 150 ----- internal/registration/envtest_test.go | 559 +++++++++--------- internal/registration/fence.go | 75 --- internal/registration/fence_test.go | 113 ---- internal/registration/ledger.go | 106 ---- internal/registration/manifest_test.go | 40 ++ .../registration/namespace_lifetime_test.go | 167 ------ internal/registration/runtime.go | 84 +-- internal/registration/segments.go | 269 --------- .../registration/segments_envtest_test.go | 382 ------------ internal/registration/terminal_errors_test.go | 121 ---- .../testdata/review_adversarial_test.go.txt | 172 ------ internal/registration/transport.go | 92 +-- 30 files changed, 652 insertions(+), 4274 deletions(-) delete mode 100644 cmd/fleet-registration-control/main.go delete mode 100644 cmd/fleet-registration-control/main_test.go delete mode 100644 config/base/registration/protection.yaml delete mode 100644 config/base/registration/rbac.yaml delete mode 100644 docs/development/registration-storage-rollout.md delete mode 100644 internal/registration/admission_regression_envtest_test.go delete mode 100644 internal/registration/admission_regression_test.go delete mode 100644 internal/registration/bounded_fences_test.go delete mode 100644 internal/registration/contention_envtest_test.go delete mode 100644 internal/registration/control.go delete mode 100644 internal/registration/control_test.go delete mode 100644 internal/registration/fence.go delete mode 100644 internal/registration/fence_test.go delete mode 100644 internal/registration/ledger.go create mode 100644 internal/registration/manifest_test.go delete mode 100644 internal/registration/namespace_lifetime_test.go delete mode 100644 internal/registration/segments.go delete mode 100644 internal/registration/segments_envtest_test.go delete mode 100644 internal/registration/terminal_errors_test.go delete mode 100644 internal/registration/testdata/review_adversarial_test.go.txt diff --git a/cmd/fleet-registration-control/main.go b/cmd/fleet-registration-control/main.go deleted file mode 100644 index 1e135e9c..00000000 --- a/cmd/fleet-registration-control/main.go +++ /dev/null @@ -1,56 +0,0 @@ -package main - -import ( - "crypto/ed25519" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "flag" - "fmt" - "io" - "os" - - "go.datum.net/fleet/internal/registration" -) - -func main() { - requestPath := flag.String("request", "", "unsigned ControlRequest JSON, exact observed root UID/resourceVersion/epoch and scope") - keyPath := flag.String("key", "", "offline Ed25519 PKCS8 private key; never mount in the service") - flag.Parse() - if err := sign(*requestPath, *keyPath, os.Stdout); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func sign(requestPath, keyPath string, output io.Writer) error { - encoded, err := os.ReadFile(requestPath) - if err != nil { - return err - } - if len(encoded) > 8192 { - return errors.New("request exceeds budget") - } - var request registration.ControlRequest - if err := json.Unmarshal(encoded, &request); err != nil { - return err - } - encoded, err = os.ReadFile(keyPath) - if err != nil { - return err - } - block, rest := pem.Decode(encoded) - if block == nil || len(rest) != 0 { - return errors.New("expected one PKCS8 private key") - } - parsed, err := x509.ParsePKCS8PrivateKey(block.Bytes) - if err != nil { - return err - } - key, ok := parsed.(ed25519.PrivateKey) - if !ok { - return errors.New("control key must be Ed25519") - } - return json.NewEncoder(output).Encode(registration.SignControl(request, key)) -} diff --git a/cmd/fleet-registration-control/main_test.go b/cmd/fleet-registration-control/main_test.go deleted file mode 100644 index 18c185da..00000000 --- a/cmd/fleet-registration-control/main_test.go +++ /dev/null @@ -1,51 +0,0 @@ -package main - -import ( - "bytes" - "crypto/ed25519" - "crypto/rand" - "crypto/x509" - "encoding/json" - "encoding/pem" - "os" - "path/filepath" - "reflect" - "testing" - - "go.datum.net/fleet/internal/registration" -) - -func TestOfflineControlSigner(t *testing.T) { - _, key, err := ed25519.GenerateKey(rand.Reader) - if err != nil { - t.Fatal(err) - } - request := registration.ControlRequest{Action: "expand", ID: "change", Reason: "synthetic", RootUID: "root", ResourceVersion: "9", Epoch: 2, Authority: "milo", Projects: []string{"provider"}} - encoded, _ := json.Marshal(request) - directory := t.TempDir() - requestPath, keyPath := filepath.Join(directory, "request"), filepath.Join(directory, "private") - if err := os.WriteFile(requestPath, encoded, 0600); err != nil { - t.Fatal(err) - } - der, err := x509.MarshalPKCS8PrivateKey(key) - if err != nil { - t.Fatal(err) - } - if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}), 0600); err != nil { - t.Fatal(err) - } - var output bytes.Buffer - if err := sign(requestPath, keyPath, &output); err != nil { - t.Fatal(err) - } - actual, err := registration.ParseControl(output.Bytes()) - if err != nil || !reflect.DeepEqual(actual, registration.SignControl(request, key)) { - t.Fatal("signer changed request", err) - } - if err := os.WriteFile(keyPath, []byte("not a private key"), 0600); err != nil { - t.Fatal(err) - } - if err := sign(requestPath, keyPath, &output); err == nil { - t.Fatal("invalid key accepted") - } -} diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index f37c2e8a..a6e33268 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -20,40 +20,33 @@ import ( resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" ) func main() { - var configFile, providers, privateNamespace, cert, key, clientCA, controlKey, controlRequest string + var configFile, providers, cert, key, clientCA string flag.StringVar(&configFile, "config", "", "Fleet manager discovery configuration") - flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider identity scope, fixed in the private ledger") - flag.StringVar(&privateNamespace, "private-namespace", "fleet-system-private", "private registration ledger namespace") + flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider scope searched for duplicate hardware identity") 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.StringVar(&controlKey, "control-key", "/etc/fleet/registration-control/public.pem", "operator Ed25519 public key; never a private key") - flag.StringVar(&controlRequest, "control-request", "/etc/fleet/registration-control/request.json", "optional signed activation or expansion request") flag.Parse() - if err := run(ctrl.SetupSignalHandler(), configFile, providers, privateNamespace, cert, key, clientCA, controlKey, controlRequest); err != nil { + if err := run(ctrl.SetupSignalHandler(), configFile, providers, cert, key, clientCA); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run(ctx context.Context, configFile, providers, namespace, cert, key, clientCA, controlKey, controlRequest string) error { +func run(ctx context.Context, configFile, providers, cert, key, clientCA string) error { config, err := projectdiscovery.LoadConfig(configFile) if err != nil { return err } - projects := strings.Split(providers, ",") - sort.Strings(projects) - for index, name := range projects { - if name == "" || strings.TrimSpace(name) != name || (index > 0 && projects[index-1] == name) { - return errors.New("a nonempty, unique provider scope is required") - } + projects, err := providerScope(providers) + if err != nil { + return err } scheme := runtime.NewScheme() for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, inventory.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme} { @@ -61,14 +54,6 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien return err } } - host, err := rest.InClusterConfig() - if err != nil { - return err - } - private, err := client.New(host, client.Options{Scheme: scheme}) - if err != nil { - return err - } rootConfig, err := clientcmd.BuildConfigFromFlags("", config.Discovery.DiscoveryKubeconfigPath) if err != nil { return err @@ -84,52 +69,17 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien return err } } - keyBytes, err := os.ReadFile(controlKey) - if err != nil { - return err - } - publicKey, err := registration.ParseControlKey(keyBytes) - if err != nil { - return err - } - handler := registration.NewHandler(registration.Store{Client: private, Namespace: namespace, Authority: config.AuthorityID, Projects: projects, ControlKey: publicKey}, root, template, scheme) + handler := registration.NewHandler(config.AuthorityID, projects, root, template, scheme) tlsConfig, err := webhookTLS(clientCA) if err != nil { return err } server := &http.Server{Addr: ":9443", Handler: http.MaxBytesHandler(handler.Transport(), 2<<20), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, TLSConfig: tlsConfig} go func() { - ticker := time.NewTicker(30 * time.Second) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _ = server.Shutdown(shutdown) - return - case <-ticker.C: - operation, cancel := context.WithTimeout(ctx, 20*time.Second) - if err := handler.Store.ResumeExpansion(operation); err != nil { - fmt.Fprintln(os.Stderr, "registration expansion remains fenced:", err) - } - if encoded, err := os.ReadFile(controlRequest); err == nil { - control, err := registration.ParseControl(encoded) - if err == nil { - err = handler.ApplyControl(operation, control) - } - if err != nil { - fmt.Fprintln(os.Stderr, "registration control not applied:", err) - } - } else if !os.IsNotExist(err) { - fmt.Fprintln(os.Stderr, "registration control unavailable:", err) - } - if err := handler.Recover(operation); err != nil { - fmt.Fprintln(os.Stderr, "registration recovery remains unknown:", err) - } - cancel() - } - } + <-ctx.Done() + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) }() err = server.ListenAndServeTLS(cert, key) if errors.Is(err, http.ErrServerClosed) { @@ -138,6 +88,17 @@ func run(ctx context.Context, configFile, providers, namespace, cert, key, clien return err } +func providerScope(providers string) ([]string, error) { + projects := strings.Split(providers, ",") + sort.Strings(projects) + for index, name := range projects { + if name == "" || strings.TrimSpace(name) != name || (index > 0 && projects[index-1] == name) { + return nil, errors.New("a nonempty, unique provider scope is required") + } + } + return projects, nil +} + func webhookTLS(clientCA string) (*tls.Config, error) { caBytes, err := os.ReadFile(clientCA) if err != nil { diff --git a/config/base/registration/deployment.yaml b/config/base/registration/deployment.yaml index c48eff73..327f18fe 100644 --- a/config/base/registration/deployment.yaml +++ b/config/base/registration/deployment.yaml @@ -33,6 +33,9 @@ spec: app.kubernetes.io/name: fleet-registration spec: serviceAccountName: fleet-registration + # The service reads Milo through mounted credentials only; it needs no + # host Kubernetes API access. + automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 65532 @@ -66,12 +69,7 @@ spec: - {name: root, mountPath: /var/run/fleet/milo, readOnly: true} - {name: projects, mountPath: /var/run/fleet/projects, readOnly: true} - {name: tls, mountPath: /etc/fleet/registration, readOnly: true} - - {name: control, mountPath: /etc/fleet/registration-control, readOnly: true} volumes: - - name: control - configMap: - name: fleet-registration-control - defaultMode: 0440 - name: config configMap: name: fleet-manager-config diff --git a/config/base/registration/kustomization.yaml b/config/base/registration/kustomization.yaml index ab998324..9c2d28b0 100644 --- a/config/base/registration/kustomization.yaml +++ b/config/base/registration/kustomization.yaml @@ -2,5 +2,3 @@ apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - deployment.yaml - - rbac.yaml - - protection.yaml diff --git a/config/base/registration/protection.yaml b/config/base/registration/protection.yaml deleted file mode 100644 index cabc8fbd..00000000 --- a/config/base/registration/protection.yaml +++ /dev/null @@ -1,55 +0,0 @@ -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-ledger-protection -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - - apiGroups: [''] - apiVersions: [v1] - operations: [CREATE, UPDATE, DELETE] - resources: [secrets] - matchConditions: - - name: registration-ledger - expression: request.namespace == 'fleet-system-private' && (request.name == 'fleet-capacity-registration-v1' || request.name.startsWith('fleet-registration-segment-') || request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration') - validations: - - expression: >- - (request.operation == 'CREATE' && request.name == 'fleet-capacity-registration-v1' && request.userInfo.username != 'system:serviceaccount:fleet-system:fleet-registration') || - (request.operation == 'UPDATE' && request.name == 'fleet-capacity-registration-v1' && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' && - (!has(oldObject.data) || !('routing.json' in oldObject.data) || - (has(object.data) && 'routing.json' in object.data && 'ledger.json' in object.data && object.data['ledger.json'] == oldObject.data['ledger.json']))) || - (request.operation == 'CREATE' && request.name.startsWith('fleet-registration-segment-') && request.userInfo.username == 'system:serviceaccount:fleet-system:fleet-registration' && has(object.immutable) && object.immutable) - message: Registration roots cannot be downgraded or deleted; only the service may update the root or create immutable retained segments. ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-ledger-protection -spec: - policyName: fleet-registration-ledger-protection - validationActions: [Deny] ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-namespace-protection -spec: - failurePolicy: Fail - matchConstraints: - resourceRules: - - apiGroups: [''] - apiVersions: [v1] - operations: [DELETE] - resources: [namespaces] - validations: - - expression: request.name != 'fleet-system-private' - message: The private registration namespace contains permanent reservations and cannot be deleted. ---- -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-namespace-protection -spec: - policyName: fleet-registration-namespace-protection - validationActions: [Deny] diff --git a/config/base/registration/rbac.yaml b/config/base/registration/rbac.yaml deleted file mode 100644 index 1e08d94c..00000000 --- a/config/base/registration/rbac.yaml +++ /dev/null @@ -1,27 +0,0 @@ -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private -rules: - - apiGroups: [''] - resources: [secrets] - verbs: [get, create] - - apiGroups: [''] - resources: [secrets] - resourceNames: [fleet-capacity-registration-v1] - verbs: [get, update] ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: fleet-registration-ledger -subjects: - - kind: ServiceAccount - name: fleet-registration - namespace: fleet-system diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml index 25069d84..b75500a9 100644 --- a/config/components/registration-admission/webhook.yaml +++ b/config/components/registration-admission/webhook.yaml @@ -3,11 +3,13 @@ kind: ValidatingWebhookConfiguration metadata: name: fleet-capacity-registration webhooks: + # Every capacity write is fail-closed. Creates are checked against live + # Devices; updates, status writes and deletes are always denied. - name: registration.fleet.datumapis.com admissionReviewVersions: [v1] failurePolicy: Fail matchPolicy: Equivalent - sideEffects: NoneOnDryRun + sideEffects: None timeoutSeconds: 20 clientConfig: url: https://fleet-registration.fleet-system.svc:9443/validate-registration @@ -17,59 +19,3 @@ webhooks: operations: [CREATE, UPDATE, DELETE] resources: [machinecapacities, machinecapacities/status] scope: Namespaced - - name: inventory.registration.fleet.datumapis.com - admissionReviewVersions: [v1] - failurePolicy: Fail - matchPolicy: Equivalent - sideEffects: NoneOnDryRun - timeoutSeconds: 20 - clientConfig: - url: https://fleet-registration.fleet-system.svc:9443/validate-registration - matchConditions: - - name: provider-project-context - expression: >- - !(has(request.userInfo.extra) && "iam.miloapis.com/parent-type" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-type"] == ['Project'] && "iam.miloapis.com/parent-api-group" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-api-group"] == ['resourcemanager.miloapis.com'] && "iam.miloapis.com/parent-name" in request.userInfo.extra && size(request.userInfo.extra["iam.miloapis.com/parent-name"]) == 1 && request.userInfo.extra["iam.miloapis.com/parent-name"][0] != '') || request.userInfo.extra["iam.miloapis.com/parent-name"][0] in ["datum-cloud"] - rules: - - apiGroups: [fleet.datumapis.com] - apiVersions: [v1alpha1] - operations: [CREATE, UPDATE, DELETE] - resources: [devices, devices/status] - scope: Namespaced - - name: namespace.registration.fleet.datumapis.com - admissionReviewVersions: [v1] - failurePolicy: Fail - matchPolicy: Equivalent - sideEffects: NoneOnDryRun - timeoutSeconds: 20 - clientConfig: - url: https://fleet-registration.fleet-system.svc:9443/validate-registration - matchConditions: - - name: provider-project-context - expression: >- - !(has(request.userInfo.extra) && "iam.miloapis.com/parent-type" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-type"] == ['Project'] && "iam.miloapis.com/parent-api-group" in request.userInfo.extra && request.userInfo.extra["iam.miloapis.com/parent-api-group"] == ['resourcemanager.miloapis.com'] && "iam.miloapis.com/parent-name" in request.userInfo.extra && size(request.userInfo.extra["iam.miloapis.com/parent-name"]) == 1 && request.userInfo.extra["iam.miloapis.com/parent-name"][0] != '') || request.userInfo.extra["iam.miloapis.com/parent-name"][0] in ["datum-cloud"] - - name: inventory-namespace - expression: "!has(request.name) || request.name == '' || request.name == 'default'" - rules: - - apiGroups: [''] - apiVersions: [v1] - operations: [DELETE] - resources: [namespaces] - scope: Cluster - - name: project.registration.fleet.datumapis.com - admissionReviewVersions: [v1] - failurePolicy: Fail - matchPolicy: Equivalent - sideEffects: NoneOnDryRun - timeoutSeconds: 20 - clientConfig: - url: https://fleet-registration.fleet-system.svc:9443/validate-registration - matchConditions: - - name: provider-project-name - expression: >- - !has(request.name) || request.name == '' || request.name in ["datum-cloud"] - rules: - - apiGroups: [resourcemanager.miloapis.com] - apiVersions: [v1alpha1] - operations: [DELETE] - resources: [projects] - scope: Cluster diff --git a/config/overlays/synthetic-staging/registration-exclusion.yaml b/config/overlays/synthetic-staging/registration-exclusion.yaml index 3b18c0a9..e4801d66 100644 --- a/config/overlays/synthetic-staging/registration-exclusion.yaml +++ b/config/overlays/synthetic-staging/registration-exclusion.yaml @@ -1,3 +1,5 @@ +# The synthetic Milo root (config/milo-synthetic) installs no registration +# webhook, so the registration workload has nothing to serve here. $patch: delete apiVersion: apps/v1 kind: Deployment @@ -18,41 +20,3 @@ kind: ServiceAccount metadata: name: fleet-registration namespace: fleet-system ---- -$patch: delete -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private ---- -$patch: delete -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: fleet-registration-ledger - namespace: fleet-system-private ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-ledger-protection ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-ledger-protection ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicy -metadata: - name: fleet-registration-namespace-protection ---- -$patch: delete -apiVersion: admissionregistration.k8s.io/v1 -kind: ValidatingAdmissionPolicyBinding -metadata: - name: fleet-registration-namespace-protection diff --git a/docs/development/registration-storage-rollout.md b/docs/development/registration-storage-rollout.md deleted file mode 100644 index 44ed4512..00000000 --- a/docs/development/registration-storage-rollout.md +++ /dev/null @@ -1,232 +0,0 @@ -# Registration storage expansion and non-admitting bootstrap - -[Stage-1 contract](inventory-capacity-registration.md) · [Packaging](../../config/README.md) - -## Delivery boundary - -Implemented against feature revision `32c3c200b7afd50a43ae705609f8f5fad0c63d40`. -This change is independent of pending PR144 (`dc0f872977ecf817557b96fa82d53b853110a198`), -whose staging integration document was read in full. It does not replace that -PR's availability work or evidence; reconcile overlapping deployment/ledger edits -when combining them. **Parent independent adversarial review is required.** - -The two Fleet prerequisites are addressed by bounded, lossless expansion (not -alias release) and transport-first, deny-only startup. This is not live acceptance. -No live mutation, grant, deployment, allocation or provider effect is authorized -by this change. The reported mixed live pairing (synthetic host without the service, -production Milo Fail webhook without caBundle) must not be repaired by relaxing -admission or changing host overlays indiscriminately. Existing Enabled capacity -and synthetic consumers are not disposable acceptance fixtures. - -## Single-CAS storage protocol - -The original `fleet-capacity-registration-v1` Secret and UID remain the sole CAS -root. Version 2 adds `routing.json` and `tail.json`. Immutable Secrets named -`fleet-registration-segment--` retain sealed tails. -Every read verifies segment name, UID, immutability, deletion state, payload digest -and authority/provider scope. Missing/replaced/corrupt/unreadable storage is never -an empty partition. The same root still serializes all aliases and provider projects. - -Segments are ordered overlays, not independently admitting hash shards. Groups -are keyed by admission operation UID for registrations and Project route/Device UID -for Device fences. Only changed groups are copied into the mutable tail, whole. -Legacy multiple-version groups are sealed without reinterpretation. Existing -authoritative update/coalescing rules alone supersede pending versions. The writer -also rejects dropping registrations, aliases, tombstones or known lifetime identity. -New Device fences retain Project UID, namespace name/UID and Device name; missing -legacy fields are not backfilled or proof of safe release. Creates and edits -require a live namespace. Deletes and finalizer-only updates do not, so a -terminating provider namespace can drain its Devices. They bind the terminating -namespace's UID, or the UID already recorded once the namespace is gone, and -still write a permanent tombstone. Registered Devices remain undeletable. - -An operator signs `expand`, binding exact root UID, resourceVersion, epoch, -authority, sorted provider scope, change ID and reason. The service: - -1. Verifies the pinned Ed25519 key and CAS-retains the request as pending before - effects. First conversion replaces `ledger.json` with an incompatible authority - sentinel, retaining its original bytes in `tail.json`. Old binaries reject it; - old in-flight writes lose CAS. Host policy forbids reverting the v2 format. -2. Creates one deterministic immutable segment with the frozen tail, root UID and - signed request. Every replica resumes the same name. AlreadyExists requires - exact content and immutable lifetime checks, never overwrite permission. -3. Reads back the segment, then CAS-appends its name/UID/digest, advances epoch and - empties the tail. Prior segments, activation and audit history remain retained. -4. Resumes admission under the same activation and full fence checks. Migration - never changes `Unknown`, `Recorded`, tombstones, reservations or eligibility. - -Crash/timeout before freeze has no authorized storage effect. After freeze, any -replica resumes retained authority even without the request file. A prepared -segment is associated with the pending operation, not garbage. A lost final CAS -response is reconciled from the root. No timeout/lease/age/absence cancels pending -work. Stale plans fail; inspect before re-signing. A public request admitted before -freeze may persist afterwards: its reservation was copied, so no claim of fencing -the API server's later storage commit is needed. A not-yet-reserved writer must win -the current root CAS or be denied/re-evaluated. No orphan alias is discarded. - -This does not implement release, scope changes, arbitrary restore or custody -compaction. Rollbacks need a v2-aware binary. Never restore an old root alone; -root plus all segments are one retained recovery set. Administrators who remove -policies or restore arbitrary storage remain outside the guarantee. - -## Enforced budgets - -| Surface | Hard bound | -| --- | --- | -| Mutable tail | 650,000 encoded bytes; larger candidate denied before admission success | -| Legacy tail accepted for sealing | 750,000 bytes, including an already-full v1 ledger | -| Root data including routing/control | 850,000 bytes, below the 1 MiB Secret data limit | -| Sealed segments | 16 plus the mutable tail; expansion is operator-authorized, not infinite | -| Signed payload / mounted envelope | 8,192 / 16,384 bytes | -| Activation audit | Current activation plus seven previous signed activations, never pruned; the ninth activation fails (lifetime limit) | - -The ordinary stop leaves 100 KB relative to the former ledger cap for safe sealing; -the root budget additionally accommodates routing/control. A segment is at most -750 KB plus its small control envelope. Failed creates, aliases, distinct Device -incarnations and failed registrations consume budget. Oversized requests cannot -consume transition reserve. Segment retries target one name, not orphan snapshots. -Maximum ledger payload is 16 × 750,000 + 650,000 bytes plus bounded control metadata. -This deliberately retains complete provider scans and the single-root bottleneck; -it is not a throughput qualification. Pod memory is bounded at 512 MiB. - -The mTLS-only `/status` reports tail bytes, headroom, remaining segments, epoch, -pending state, root UID/RV, scope and verified fence digest, without reservation -contents or actor data. Parent monitoring must alert below 100,000 bytes headroom -and before only two segments remain. Sign expansion before exhaustion. A full v1 -ledger reports `registration ledger is full; sign an expand control request`; -a full v2 tail with segments left reports `registration growth stopped`. Both -mean sign `expand` as in step 7 below. Once all 16 segments are sealed, writes -and `expand` report `registration segments exhausted`: expansion is refused, so -re-signing it cannot help. At that terminal bound, stop protected growth and -escalate for a separately reviewed storage migration; never increase caps or -delete/reset/release records manually. -Public inventory reads remain unaffected. Denied/timed-out private writes deny -admission even if reads succeed; uncertain commits stay retained. - -## Transport versus activation - -The process loads credentials, TLS material and the operator public key, then -listens without requiring the ledger or installed webhook. It denies **every** -admission in bootstrap. `/transportz` returns 204 on the same mTLS listener for -SAN/CA/routing verification. The pod TCP readiness probe intentionally supplies -Service endpoints during bootstrap; it is not the UI admission gate. -`/activationz` returns 503 until activation and current readable dependencies -verify. It is not proof of write permission, future availability or capacity -eligibility. Request headers/labels/annotations/extras cannot enable admission; -there is no bootstrap bypass flag or public control endpoint. - -Signed `activate` also pins the digest of the installed, API-defaulted webhook -`webhooks` array, obtained from `/status` after `VerifyFence` succeeds. Activation -CAS and every admission retain full fence verification. Missing trust, changed -endpoint/CA, partial deployment, relaxed rules or degraded dependencies deny. -Approved trust changes require another exact signed activation; prior signatures -remain in bounded root audit history. The configured signing key is an operator -trust boundary, not caller authority; coordinate changes with pending signatures. -Global capacity fencing and privileged/root-context limitations are unchanged. - -### Activation budget is a lifetime limit - -The root keeps the current activation plus seven previous ones. The ninth -activation of a root fails with `activation audit budget exhausted`. Nothing -prunes or compacts this history, so the limit applies to the root's whole life -until a separately reviewed compaction migration exists. Every change to the -pinned fence digest needs a new activation and uses one slot. That includes -webhook CA rotation (the `caBundle` is part of the digest) and API-server drift -in defaulted webhook fields after an upgrade. Batch planned trust changes into -one activation where possible, and count the remaining slots before each one. -At the cap, admission stays on its current activation while that activation's -fence still verifies. If the fence has already changed, registration stays -non-admitting. Do not delete or edit `routing.json`, and do not create a new -root to reset the count. Escalate for the reviewed compaction migration. - -### Rotating the operator signing key - -The public key is read once at process startup from `public.pem`, and every -signature is verified against the key the process currently holds. A pending -expansion cannot be cancelled, and `ResumeExpansion` re-verifies the pending -signature against the current key. If the key rotates while an expansion is -pending, the expansion cannot complete and the root stays fenced. Rotate in -this order: - -1. Fetch `/status` and confirm no expansion is pending. If one is, let it - complete under the current key and confirm the epoch advanced. Do not sign - a new `expand` until the rotation is finished. -2. Replace `public.pem` in `fleet-registration-control`, then restart every - registration replica, because a running process keeps the key it loaded. -3. The retained activation was signed by the old key, so the restarted - processes stay non-admitting. Sign a fresh `activate` with the new key - (step 7 below). This uses one activation slot. - -## Exact staged parent infrastructure contract - -These steps require a separately approved infra PR; none authorizes live execution. - -1. Preserve private baseline evidence. Resolve registration authority and complete - provider scope separately from synthetic consumers. Do not narrow scope to - conceal legacy capacity or reuse manager root grants. Capacity writes remain - globally fenced, including outside `datum-cloud`. -2. Install retention policies before bootstrap or broader RBAC. The service gets - get/create Secrets in the dedicated private namespace and update only on the - root. Fail host admission restricts its creates to immutable segment names; - it cannot create the root/arbitrary Secrets or update/delete segments. Prove - negative cases and retain backups of **all** segments; never use GitOps to - reconcile an empty root. Namespace/root deletion remains forbidden. -3. Provision separate root/project read-and-SAR identities, serving SAN/CA, - dedicated webhook client certificate/CA, and `fleet-registration-control` - ConfigMap in `fleet-system` with `public.pem` (Ed25519 PKIX PEM). Restrict - ConfigMap/workload writers as operator trust authorities. No signing private - key, kubeconfig or rendered secret-bearing configuration belongs in Git. -4. Pin the reviewed image and deploy registration before activating a new Fail - webhook. With the already-broken live fence, leave protection installed. - Verify `/transportz` from the API-server route with trusted client TLS, and - reject missing/untrusted clients. No public write is a health probe; never - remove/relax the existing fence to test routing. -5. Create the empty root once with exact authority and sorted projects in - `ledger.json`, after retention acceptance. Abort on AlreadyExists and inspect - rather than replace. Existing v1 roots activate/migrate in place with the same UID. -6. Wire Milo's dedicated webhook client and serving caBundle in environment-owned - overlays. Verify complete Fail rules. Fetch `/status` over trusted transport - and review the installed fence and root UID/RV/epoch/scope/fence digest. -7. Sign a `ControlRequest` JSON containing `action: "activate"`, `id`, `reason`, - `authority`, `projects`, `rootUID`, `resourceVersion`, `epoch`, `fenceDigest`: - - ```sh - go run ./cmd/fleet-registration-control --request="$PRIVATE_REQUEST" --key="$OFFLINE_KEY" > "$PRIVATE_SIGNED_REQUEST" - ``` - - The helper requires a PKCS8 Ed25519 private key. Only its signed envelope goes - into ConfigMap `request.json`; the private key is never mounted. The process - checks every 30 seconds. Reconcile through `/status` and `/activationz`, not - ConfigMap update success. For expansion use `action: "expand"`; no fence - digest is required, and expansion cannot activate a bootstrap root. -8. Keep UI registration gated until real staff proxy identity, named Device and - create authorization denials, direct mutation denials, duplicate contention, - lifetime/legacy behavior, Unknown recovery and unchanged baselines are accepted - on intended Milo routes. Use disposable environments for outages/failures, - never shared-service disruption or real-asset smoke tests. Only the parent - can then report environment acceptance. - -## Local verification - -Tests exercise real Secret CAS/retention, bounded expansion, legacy integrity, -multi-replica migration, signature/scope/epoch spoofing, read-only RBAC and -persisted-but-timed-out writes. A real API request paused after admission fails -public persistence after migration; its aliases remain reserved and Unknown. -Five subprocess exits cover freeze, before/after segment persistence and -before/after root switch, recovered by new processes. Missing/replaced segments -fail closed. Existing identity, authorization, legacy and outage tests remain. - -```sh -KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" go test -race ./... -go vet ./... -go build ./... -kustomize build config/milo >/dev/null -kustomize build config/overlays/management-plane >/dev/null -./hack/validate-overlay-isolation.sh -./hack/test-overlay-isolation.sh -./hack/validate-doc-links.sh -git diff --check -``` - -No UI files change. These checks do not accept deployed Milo routing, credential -mounts, grants, GitOps ordering or real inventory. Disabled/Retain remains inert. diff --git a/internal/registration/admission.go b/internal/registration/admission.go index f4959d2b..0982a8b8 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -1,15 +1,19 @@ +// Package registration admits inert, inventory-backed MachineCapacity records. +// +// The webhook keeps no state of its own. Every decision is made against live +// Devices and capacities in the configured provider projects, so the API +// server remains the only store. One capacity per Device is enforced by the +// API server itself: the capacity name is derived from the Device UID, and two +// creates for the same Device collide on that name. package registration import ( - "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" - "io" - "log/slog" "reflect" "regexp" "slices" @@ -21,7 +25,6 @@ import ( iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" admissionv1 "k8s.io/api/admission/v1" authenticationv1 "k8s.io/api/authentication/v1" - corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -32,22 +35,39 @@ const ( DeviceUIDAnnotation = "fleet.datumapis.com/registration-device-uid" DeviceVersionAnnotation = "fleet.datumapis.com/registration-device-version" OperationAnnotation = "fleet.datumapis.com/registration-operation" + + // CapacityNamePrefix starts every registered capacity name. The rest of + // the name is the backing Device's UID. + CapacityNamePrefix = "device-" + + // InventoryNamespace is the only namespace registration reads and writes. + InventoryNamespace = "default" ) +// CapacityName is the only name a registered capacity for this Device +// incarnation may have. Because the API server rejects a second object with +// the same name, concurrent registrations of one Device cannot both persist. +func CapacityName(deviceUID types.UID) string { + return CapacityNamePrefix + string(deviceUID) +} + type Project struct { Identity controller.ProjectIdentity Client client.Client } type Handler struct { - Store Store - VerifyFence func(context.Context) error - FenceDigest func(context.Context) (string, error) - Resolve func(context.Context, string) (Project, error) - Authorize func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error + // Projects is the complete provider scope. Duplicate identities are + // searched across all of it. + Projects []string + Resolve func(context.Context, string) (Project, error) + Authorize func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error } -func aliases(device *inventory.Device) []string { +// Aliases returns the normalized hardware identifiers of a Device: serial, +// system UUID and, when present, the provider host reference. Two Devices +// sharing any alias may be the same machine. +func Aliases(device *inventory.Device) []string { var result []string pairs := [][2]string{{"serial", strings.ToLower(strings.TrimSpace(device.Spec.Identity.Serial))}, {"uuid", strings.ToLower(strings.TrimSpace(device.Spec.Identity.SystemUUID))}} if reference := device.Spec.ProviderHostRef; reference != nil { @@ -88,130 +108,69 @@ func projectName(actor authenticationv1.UserInfo) (string, error) { } func (handler *Handler) Handle(ctx context.Context, request admission.Request) admission.Response { - if !handler.Store.AllowInactiveForTests { - if err := handler.Ready(ctx); err != nil { - return admission.Denied(err.Error()) - } - } - if request.Operation == admissionv1.Delete && request.Name == "" && ((request.Resource.Group == "" && request.Resource.Resource == "namespaces") || (request.Resource.Group == "resourcemanager.miloapis.com" && request.Resource.Resource == "projects")) { - return admission.Denied("lifetime deletion requires an exact resource name; collection deletion cannot prove exclusion of retained lifetimes") + if request.Resource.Group != metal.GroupVersion.Group || request.Resource.Resource != "machinecapacities" { + return admission.Denied("unsupported registration admission resource") } - if request.Resource.Group == "" && request.Resource.Resource == "namespaces" && request.Name != "default" { - return admission.Allowed("outside the retained inventory namespace") - } - if request.Resource.Group == "resourcemanager.miloapis.com" && request.Resource.Resource == "projects" && request.Operation == admissionv1.Delete { - if slices.Contains(handler.Store.Projects, request.Name) { - return admission.Denied("provider project lifetime is retained by the registration authority") - } - return admission.Allowed("outside the provider registration scope") - } - if request.DryRun != nil && *request.DryRun { - return admission.Denied("registration admission retains reservations and does not support dry-run") + if request.Operation != admissionv1.Create || request.SubResource != "" { + return admission.Denied("capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation") } name, err := projectName(request.UserInfo) if err != nil { return admission.Denied(err.Error()) } - if !slices.Contains(handler.Store.Projects, name) { - if (request.Resource.Group == "fleet.datumapis.com" && request.Resource.Resource == "devices") || (request.Resource.Group == "" && request.Resource.Resource == "namespaces") { - return admission.Allowed("outside the configured provider identity scope") - } - return admission.Denied("project is outside the configured registration authority") - } - if request.UID == "" { - return admission.Denied("admission operation identity is required") + if !slices.Contains(handler.Projects, name) { + return admission.Denied("project is outside the configured provider registration scope") } - for attempt := 0; attempt < 6; attempt++ { - err = handler.evaluate(ctx, name, request) - if !apierrors.IsConflict(err) { - break - } - } - if err != nil { - if apierrors.IsConflict(err) { - slog.ErrorContext(ctx, "registration ledger CAS retries exhausted", "attempts", 6, "project", name, "operation", request.UID) - } + if err := handler.evaluate(ctx, name, request); err != nil { return admission.Denied(err.Error()) } return admission.Allowed("inert inventory registration only; no availability or preparation authority") } func (handler *Handler) evaluate(ctx context.Context, name string, request admission.Request) error { - if handler.VerifyFence != nil { - if err := handler.VerifyFence(ctx); err != nil { - return err - } - } - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - return fmt.Errorf("registration unavailable: %w", err) - } - if _, exists := secret.Data["routing.json"]; exists { - route, err := decodeRouting(secret) - if err != nil { - return err - } - if route.Pending != nil { - return errors.New("registration expansion is fenced") - } - } - project, err := handler.Resolve(ctx, name) - if err != nil { - return err - } - if !project.Identity.Valid() || project.Identity.RouteName != name || project.Identity.AuthorityID != ledger.Authority { - return errors.New("project lifetime unavailable") - } - if request.Resource.Group == "" && request.Resource.Resource == "namespaces" { - if request.Name == "default" && request.Operation == admissionv1.Delete { - return errors.New("the inventory namespace cannot be deleted within the registration authority") - } - return nil - } - if request.Resource.Group == "fleet.datumapis.com" && request.Resource.Resource == "devices" { - return handler.device(ctx, project, request, secret, ledger) - } - if request.Resource.Group != "metal.datumapis.com" || request.Resource.Resource != "machinecapacities" { - return errors.New("unsupported registration admission resource") - } - if request.Operation != admissionv1.Create || request.SubResource != "" { - return errors.New("capacity mutation and deletion are disabled; retained and legacy capacity require operator reconciliation") - } - if request.Namespace != "default" { + if request.Namespace != InventoryNamespace { return errors.New("registration requires the default inventory namespace") } var capacity metal.MachineCapacity if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { return err } - if capacity.UID == "" || capacity.Name == "" || capacity.Name != request.Name || capacity.Namespace != "default" || capacity.GenerateName != "" || !capacity.DeletionTimestamp.IsZero() { - return errors.New("an explicit capacity name and API-assigned incarnation are required") + if capacity.Name == "" || capacity.Name != request.Name || capacity.Namespace != InventoryNamespace || capacity.GenerateName != "" || !capacity.DeletionTimestamp.IsZero() { + return errors.New("an explicit capacity name in the default namespace is required") } if capacity.Spec.AllocationPolicy != "Disabled" || capacity.Spec.ReclaimPolicy != "Retain" || capacity.Spec.CleaningPolicyRef.Name != "" || !reflect.DeepEqual(capacity.Status, metal.MachineCapacityStatus{}) || len(capacity.OwnerReferences) != 0 || len(capacity.Finalizers) != 0 { return errors.New("only Disabled/Retain registration with an explicitly unconfigured cleaning policy and no status or ownership is supported") } annotations := capacity.Annotations if len(annotations) != 3 || annotations[DeviceUIDAnnotation] == "" || annotations[DeviceVersionAnnotation] == "" || annotations[OperationAnnotation] == "" { - return errors.New("exact Device UID/resourceVersion and a stable registration operation are required") + return errors.New("exact Device UID/resourceVersion and a client operation ID are required") } if len(annotations[OperationAnnotation]) > 128 { return errors.New("registration operation is too long") } - if err := handler.Authorize(ctx, project, request.UserInfo, "metal.datumapis.com", "machinecapacities", ""); err != nil { - return err + if capacity.Name != CapacityName(types.UID(annotations[DeviceUIDAnnotation])) { + return fmt.Errorf("capacity name must be %q, derived from the selected Device UID, so one Device can back only one capacity", CapacityName(types.UID(annotations[DeviceUIDAnnotation]))) } - if err := handler.Authorize(ctx, project, request.UserInfo, "fleet.datumapis.com", "devices", capacity.Spec.DeviceRef.Name); err != nil { - return err + project, err := handler.Resolve(ctx, name) + if err != nil { + return errors.New("provider project lifetime is unavailable") } - namespace := &corev1.Namespace{} - if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, namespace); err != nil { + if !project.Identity.Valid() || project.Identity.RouteName != name { + return errors.New("provider project lifetime is unavailable") + } + // Authorize before reading the Device so an unauthorized caller cannot + // learn whether it exists. + if err := handler.Authorize(ctx, project, request.UserInfo, metal.GroupVersion.Group, "machinecapacities", ""); err != nil { return err } - if namespace.UID == "" || !namespace.DeletionTimestamp.IsZero() { - return errors.New("inventory namespace lifetime unavailable") + if err := handler.Authorize(ctx, project, request.UserInfo, inventory.GroupVersion.Group, "devices", capacity.Spec.DeviceRef.Name); err != nil { + return err } device := &inventory.Device{} - if err := project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + if err := project.Client.Get(ctx, client.ObjectKey{Namespace: InventoryNamespace, Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + if apierrors.IsNotFound(err) { + return errors.New("selected Device does not exist in the provider project") + } return errors.New("selected Device is unavailable") } if device.UID != types.UID(annotations[DeviceUIDAnnotation]) || device.ResourceVersion != annotations[DeviceVersionAnnotation] || !device.DeletionTimestamp.IsZero() { @@ -220,72 +179,15 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis if !eligible(device) { return errors.New("registration requires non-placeholder serial, canonical system UUID, and complete provider aliases; incomplete identity is ambiguous") } - entry := Entry{Operation: request.UID, Actor: request.UserInfo, Project: name, ProjectUID: project.Identity.UID, NamespaceUID: namespace.UID, Name: capacity.Name, CapacityUID: capacity.UID, DeviceName: device.Name, DeviceUID: device.UID, DeviceVersion: device.ResourceVersion, Aliases: aliases(device), Input: append(json.RawMessage(nil), request.Object.Raw...), Outcome: "Unknown"} - entry.AssetID = entry.Aliases[1] - for _, retained := range ledger.Entries { - if retained.Operation == entry.Operation && reflect.DeepEqual(retained, entry) { - return nil - } - if overlaps(retained.Aliases, entry.Aliases) || (retained.Project == name && (retained.Name == entry.Name || retained.DeviceUID == entry.DeviceUID)) { - return ErrConflict - } - var prior metal.MachineCapacity - if json.Unmarshal(retained.Input, &prior) != nil { - return errors.New("retained registration is corrupt") - } - if retained.Project == name && prior.Annotations[OperationAnnotation] == annotations[OperationAnnotation] { - return ErrConflict - } - } - for _, fence := range ledger.DeviceFences { - if fence.Project == name && fence.UID == device.UID { - if (fence.ProjectUID != "" && fence.ProjectUID != entry.ProjectUID) || (fence.NamespaceUID != "" && fence.NamespaceUID != entry.NamespaceUID) || (fence.Name != "" && (fence.Name != device.Name || fence.Namespace != device.Namespace)) { - return ErrConflict - } - if fence.Deleted || (fence.Version != "" && fence.Version == device.ResourceVersion) { - return ErrConflict - } - continue - } - if overlaps(fence.Aliases, entry.Aliases) { - return ErrConflict - } - } - if err := handler.scan(ctx, entry); err != nil { - return err - } - current, err := handler.Resolve(ctx, name) - if err != nil || current.Identity != project.Identity { - return errors.New("project lifetime changed") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() { - return errors.New("namespace lifetime changed") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.UID != entry.DeviceUID || device.ResourceVersion != entry.DeviceVersion || !device.DeletionTimestamp.IsZero() { - return errors.New("selected Device changed") - } - if err := handler.Authorize(ctx, project, request.UserInfo, "metal.datumapis.com", "machinecapacities", ""); err != nil { - return err - } - if err := handler.Authorize(ctx, project, request.UserInfo, "fleet.datumapis.com", "devices", device.Name); err != nil { - return err - } - current, err = handler.Resolve(ctx, name) - if err != nil || current.Identity != project.Identity { - return errors.New("project lifetime changed during authorization") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() { - return errors.New("namespace lifetime changed during authorization") - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.UID != entry.DeviceUID || device.ResourceVersion != entry.DeviceVersion || !device.DeletionTimestamp.IsZero() { - return errors.New("selected Device changed during authorization") - } - ledger.Entries = append(ledger.Entries, entry) - return handler.Store.Write(ctx, secret, ledger) + return handler.scan(ctx, name, device) } -func (handler *Handler) scan(ctx context.Context, entry Entry) error { - for _, name := range handler.Store.Projects { +// scan compares the selected Device with every live Device and capacity in the +// provider scope. It is a point-in-time read: see the stage-1 contract for the +// race with a concurrently created duplicate Device. +func (handler *Handler) scan(ctx context.Context, selectedProject string, selected *inventory.Device) error { + selectedAliases := Aliases(selected) + for _, name := range handler.Projects { project, err := handler.Resolve(ctx, name) if err != nil { return errors.New("provider identity scope is unavailable") @@ -298,17 +200,18 @@ func (handler *Handler) scan(ctx context.Context, entry Entry) error { if err := project.Client.List(ctx, &capacities); err != nil { return errors.New("provider capacity inventory is unavailable") } - for _, device := range devices.Items { - if name == entry.Project && device.UID == entry.DeviceUID { + for index := range devices.Items { + device := &devices.Items[index] + if name == selectedProject && device.UID == selected.UID { continue } - if overlaps(aliases(&device), entry.Aliases) { - return errors.New("another Device shares recorded hardware identity; resolve aliases before registration") + if overlaps(Aliases(device), selectedAliases) { + return fmt.Errorf("another Device (%s) shares recorded hardware identity; resolve the duplicate before registration", describe(name, selectedProject, device.Namespace, device.Name)) } } for _, capacity := range capacities.Items { - if name == entry.Project && capacity.Namespace == "default" && capacity.Name == entry.Name { - return ErrConflict + if name == selectedProject && capacity.Namespace == selected.Namespace && (capacity.Spec.DeviceRef.Name == selected.Name || capacity.Annotations[DeviceUIDAnnotation] == string(selected.UID)) { + return fmt.Errorf("Device already backs capacity %s; one Device can back only one capacity", capacity.Name) } var matched *inventory.Device for index := range devices.Items { @@ -319,203 +222,31 @@ func (handler *Handler) scan(ctx context.Context, entry Entry) error { } } if matched == nil || inventory.CapacityBackingError(matched) != nil { - return errors.New("legacy capacity has unresolved physical identity; registration cannot establish non-conflict") + return fmt.Errorf("capacity %s has unresolved physical identity; registration cannot establish non-conflict", describe(name, selectedProject, capacity.Namespace, capacity.Name)) } - if overlaps(aliases(matched), entry.Aliases) { - return ErrConflict + if overlaps(Aliases(matched), selectedAliases) { + return fmt.Errorf("capacity %s is backed by a Device sharing recorded hardware identity", describe(name, selectedProject, capacity.Namespace, capacity.Name)) } } } return nil } -func (handler *Handler) device(ctx context.Context, project Project, request admission.Request, secret *corev1.Secret, ledger Ledger) error { - var device, old inventory.Device - if request.Operation != admissionv1.Create { - if err := json.Unmarshal(request.OldObject.Raw, &old); err != nil { - return err - } - } - if request.Operation != admissionv1.Delete { - if err := json.Unmarshal(request.Object.Raw, &device); err != nil { - return err - } - } else { - device = old - } - for _, entry := range ledger.Entries { - bound := entry.Project == project.Identity.RouteName && entry.DeviceUID == device.UID - if entry.Project == project.Identity.RouteName && device.Namespace == "default" && entry.DeviceName == device.Name && !bound { - return ErrConflict - } - if bound && (entry.ProjectUID != project.Identity.UID || request.Operation == admissionv1.Delete) { - return ErrConflict - } - if overlaps(entry.Aliases, aliases(&device)) && !bound { - return ErrConflict - } - if bound && !reflect.DeepEqual(device.Spec, old.Spec) { - return errors.New("registered Device specification is frozen") - } - } - if request.Operation == admissionv1.Update { - if device.UID != old.UID || !reflect.DeepEqual(device.Spec.Identity, old.Spec.Identity) || !reflect.DeepEqual(aliases(&device), aliases(&old)) { - return errors.New("Device incarnation and identity are immutable") - } - if old.ResourceVersion == "" { - return errors.New("Device update baseline is unavailable") - } - } - if request.Operation != admissionv1.Create && request.Operation != admissionv1.Delete && request.Operation != admissionv1.Update { - return errors.New("unsupported Device operation") - } - if device.UID == "" { - return errors.New("Device incarnation unavailable") - } - if request.Operation == admissionv1.Update && identicalObjects(request.OldObject.Raw, request.Object.Raw) { - return nil - } - // Deletes and finalizer removals are how a terminating namespace drains its - // Devices, so they must not depend on the namespace still being live. - releasing := request.Operation == admissionv1.Delete || (request.Operation == admissionv1.Update && finalizerRemoval(request.OldObject.Raw, request.Object.Raw)) - deleting := request.Operation == admissionv1.Delete || (releasing && !old.DeletionTimestamp.IsZero()) - namespaceUID, err := deviceNamespace(ctx, project, device, ledger, releasing) - if err != nil { - return err - } - fence := DeviceFence{Project: project.Identity.RouteName, ProjectUID: project.Identity.UID, Namespace: device.Namespace, NamespaceUID: namespaceUID, Name: device.Name, UID: device.UID, Deleted: deleting} - if request.Operation == admissionv1.Update { - current := &inventory.Device{} - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(&old), current); err != nil { - return err - } - if current.UID != old.UID || current.ResourceVersion != old.ResourceVersion || device.ResourceVersion != old.ResourceVersion || (!current.DeletionTimestamp.IsZero() && !deleting) { - return errors.New("Device update baseline is no longer current") - } - if !deleting { - fence.Version = old.ResourceVersion - } - } - if request.Operation == admissionv1.Create { - fence.Aliases = aliases(&device) - for _, retained := range ledger.DeviceFences { - if overlaps(retained.Aliases, fence.Aliases) && !reflect.DeepEqual(retained, fence) { - return ErrConflict - } - } - } - coalesced := make([]DeviceFence, 0, len(ledger.DeviceFences)+1) - for _, retained := range ledger.DeviceFences { - if retained.Project != fence.Project || retained.UID != fence.UID { - coalesced = append(coalesced, retained) - continue - } - if (retained.Deleted && !fence.Deleted) || (request.Operation == admissionv1.Create && !reflect.DeepEqual(retained, fence)) { - return ErrConflict - } - if (retained.ProjectUID != "" && retained.ProjectUID != fence.ProjectUID) || (retained.NamespaceUID != "" && retained.NamespaceUID != fence.NamespaceUID) || (retained.Name != "" && (retained.Name != fence.Name || retained.Namespace != fence.Namespace)) { - return ErrConflict - } - for _, alias := range retained.Aliases { - if !slices.Contains(fence.Aliases, alias) { - fence.Aliases = append(fence.Aliases, alias) - } - } - } - slices.Sort(fence.Aliases) - coalesced = append(coalesced, fence) - if reflect.DeepEqual(ledger.DeviceFences, coalesced) { - return nil - } - ledger.DeviceFences = coalesced - return handler.Store.Write(ctx, secret, ledger) -} - -// deviceNamespace returns the namespace lifetime to bind into the Device fence. -// Ordinary writes require a live namespace. Releasing writes accept a -// terminating namespace, and once the namespace is gone they fall back to the -// lifetime already recorded for this Device so the tombstone never loses it. -func deviceNamespace(ctx context.Context, project Project, device inventory.Device, ledger Ledger, releasing bool) (types.UID, error) { - var namespace corev1.Namespace - err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, &namespace) - if err != nil && (!releasing || !apierrors.IsNotFound(err)) { - return "", err - } - if err == nil { - if namespace.UID == "" || (!releasing && !namespace.DeletionTimestamp.IsZero()) { - return "", errors.New("Device namespace lifetime unavailable") - } - return namespace.UID, nil - } - for _, retained := range ledger.DeviceFences { - if retained.Project == project.Identity.RouteName && retained.UID == device.UID && retained.NamespaceUID != "" { - return retained.NamespaceUID, nil - } +// describe names a conflicting record for the caller. Records in other +// provider projects are not named, because the caller may not be able to read +// them. +func describe(project, selectedProject, namespace, name string) string { + if project != selectedProject { + return "in another provider project" } - // A legacy fence never recorded the namespace; the tombstone stays - // legacy-shaped rather than inventing a lifetime or denying the delete. - return "", nil + return namespace + "/" + name } -// finalizerRemoval reports whether an update only removes finalizers. Server -// managed field bookkeeping is ignored; any other change is a real edit. -func finalizerRemoval(old, current []byte) bool { - decode := func(raw []byte) (map[string]any, []string, bool) { - decoder := json.NewDecoder(bytes.NewReader(raw)) - decoder.UseNumber() - var object map[string]any - if err := decoder.Decode(&object); err != nil || object == nil || decoder.Decode(new(any)) != io.EOF { - return nil, nil, false - } - metadata, _ := object["metadata"].(map[string]any) - if metadata == nil { - return nil, nil, false - } - var finalizers []string - if values, exists := metadata["finalizers"]; exists { - list, ok := values.([]any) - if !ok { - return nil, nil, false - } - for _, value := range list { - name, ok := value.(string) - if !ok { - return nil, nil, false - } - finalizers = append(finalizers, name) - } - } - delete(metadata, "finalizers") - delete(metadata, "managedFields") - return object, finalizers, true - } - before, beforeFinalizers, beforeOK := decode(old) - after, afterFinalizers, afterOK := decode(current) - if !beforeOK || !afterOK || len(afterFinalizers) >= len(beforeFinalizers) || !reflect.DeepEqual(before, after) { - return false - } - for _, name := range afterFinalizers { - if !slices.Contains(beforeFinalizers, name) { - return false - } - } - return true -} - -func identicalObjects(old, current []byte) bool { - decode := func(raw []byte) (map[string]any, error) { - decoder := json.NewDecoder(bytes.NewReader(raw)) - decoder.UseNumber() - var object map[string]any - if err := decoder.Decode(&object); err != nil { - return nil, err - } - if err := decoder.Decode(new(any)); err != io.EOF { - return nil, errors.New("expected exactly one JSON object") +func overlaps(left, right []string) bool { + for _, first := range left { + if slices.Contains(right, first) { + return true } - return object, nil } - before, beforeErr := decode(old) - after, afterErr := decode(current) - return beforeErr == nil && afterErr == nil && before != nil && after != nil && reflect.DeepEqual(before, after) + return false } diff --git a/internal/registration/admission_regression_envtest_test.go b/internal/registration/admission_regression_envtest_test.go deleted file mode 100644 index ff65a8f7..00000000 --- a/internal/registration/admission_regression_envtest_test.go +++ /dev/null @@ -1,436 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "fmt" - "net/http/httptest" - "os" - "path/filepath" - "strings" - "sync" - "testing" - "time" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - metal "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - resourcemanager "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" - admissionv1 "k8s.io/api/admission/v1" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - extensions "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/yaml" -) - -func TestRealNoopRegistrationAndScopedTransportFailure(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - ctx := context.Background() - projectCRD := &extensions.CustomResourceDefinition{ObjectMeta: metav1.ObjectMeta{Name: "projects.resourcemanager.miloapis.com"}, Spec: extensions.CustomResourceDefinitionSpec{Group: "resourcemanager.miloapis.com", Names: extensions.CustomResourceDefinitionNames{Plural: "projects", Singular: "project", Kind: "Project", ListKind: "ProjectList"}, Scope: extensions.ClusterScoped, Versions: []extensions.CustomResourceDefinitionVersion{{Name: "v1alpha1", Served: true, Storage: true, Schema: &extensions.CustomResourceValidation{OpenAPIV3Schema: &extensions.JSONSchemaProps{Type: "object"}}}}}} - environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, CRDs: []*extensions.CustomResourceDefinition{projectCRD}, ErrorIfCRDPathMissing: true} - environment.ControlPlane.GetAPIServer().Configure().Append("disable-admission-plugins", "NamespaceLifecycle") - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, resourcemanager.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { - if err := add(scheme); err != nil { - t.Fatal(err) - } - } - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - if err := extensions.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - deviceCRD := &extensions.CustomResourceDefinition{} - if err := api.Get(ctx, client.ObjectKey{Name: "devices.fleet.datumapis.com"}, deviceCRD); err != nil { - t.Fatal(err) - } - deviceCRD.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties["status"] = extensions.JSONSchemaProps{Type: "object", Properties: map[string]extensions.JSONSchemaProps{"observation": {Type: "integer"}}} - if err := api.Update(ctx, deviceCRD); err != nil { - t.Fatal(err) - } - devices := []*inventory.Device{ - {ObjectMeta: metav1.ObjectMeta{Name: "noop-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "noop-serial", SystemUUID: "11111111-1111-1111-1111-111111111111"}}}, - {ObjectMeta: metav1.ObjectMeta{Name: "real-edit-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "edit-serial", SystemUUID: "22222222-2222-2222-2222-222222222222"}}}, - {ObjectMeta: metav1.ObjectMeta{Name: "collector-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "collector-serial", SystemUUID: "33333333-3333-3333-3333-333333333333"}}}, - {ObjectMeta: metav1.ObjectMeta{Name: "concurrent-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "concurrent-serial", SystemUUID: "44444444-4444-4444-4444-444444444444"}}}, - } - for _, device := range devices { - if err := api.Create(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - } - for _, name := range []string{"datum-cloud", "unrelated-consumer"} { - if err := api.Create(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: name}}); err != nil { - t.Fatal(err) - } - } - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "other-namespace"}}); err != nil { - t.Fatal(err) - } - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"datum-cloud"}}) - if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "default"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { - t.Fatal(err) - } - handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"datum-cloud"}, AllowInactiveForTests: true}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { - return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil - }, Authorize: Authorize} - type gate struct { - entered, release chan struct{} - once sync.Once - } - gates := map[string]*gate{ - "first": {entered: make(chan struct{}), release: make(chan struct{})}, - "second": {entered: make(chan struct{}), release: make(chan struct{})}, - } - server := httptest.NewTLSServer(&admission.Webhook{Handler: admission.HandlerFunc(func(ctx context.Context, request admission.Request) admission.Response { - response := handler.Handle(ctx, request) - if response.Allowed && request.Operation == admissionv1.Update && request.Resource.Resource == "devices" && request.Name == "concurrent-hardware" { - var device inventory.Device - if json.Unmarshal(request.Object.Raw, &device) == nil { - if pending := gates[device.Labels["admission-delay"]]; pending != nil { - pending.once.Do(func() { - close(pending.entered) - select { - case <-pending.release: - case <-ctx.Done(): - } - }) - } - } - } - return response - })}) - t.Cleanup(server.Close) - data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") - if err != nil { - t.Fatal(err) - } - var webhooks admissionregistrationv1.ValidatingWebhookConfiguration - if err := yaml.UnmarshalStrict(data, &webhooks); err != nil { - t.Fatal(err) - } - url := server.URL - for index := range webhooks.Webhooks { - webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} - } - if err := api.Create(ctx, &webhooks); err != nil { - t.Fatal(err) - } - actorConfig := rest.CopyConfig(config) - actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "review-operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} - actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - outsideConfig := rest.CopyConfig(actorConfig) - outsideConfig.Impersonate.Extra = map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}} - outside, err := client.New(outsideConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - deadline := time.Now().Add(10 * time.Second) - for { - err := actor.Update(ctx, devices[0].DeepCopyObject().(*inventory.Device), client.DryRunAll) - if apierrors.IsForbidden(err) { - break - } - if time.Now().After(deadline) { - t.Fatalf("inventory webhook did not engage: %v", err) - } - time.Sleep(30 * time.Millisecond) - } - register := func(t *testing.T, device *inventory.Device, name string) error { - t.Helper() - request := registrationRequest(t, device, name) - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { - t.Fatal(err) - } - capacity.UID = "" - return actor.Create(ctx, &capacity) - } - t.Run("unchanged-success-retains-current-RV-and-registers", func(t *testing.T) { - device := devices[0] - unchanged := false - for attempt := 0; attempt < 3; attempt++ { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - before := device.ResourceVersion - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if before == device.ResourceVersion { - unchanged = true - break - } - } - if !unchanged { - t.Fatal("API server did not reproduce the unchanged resourceVersion") - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-noop"); err != nil { - t.Fatalf("unchanged successful update poisoned the current selection: %v", err) - } - }) - t.Run("genuine-edit-requires-explicit-new-selection", func(t *testing.T) { - device := devices[1] - baseline := device.DeepCopyObject().(*inventory.Device) - device.Labels = map[string]string{"review-control": "real-change"} - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if baseline.ResourceVersion == device.ResourceVersion { - t.Fatal("real edit did not change the version") - } - if err := register(t, baseline, "stale-selection"); !apierrors.IsForbidden(err) { - t.Fatalf("stale selection not fenced: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-real-edit"); err != nil { - t.Fatal(err) - } - }) - t.Run("repeated-status-and-metadata-writes-remain-bounded", func(t *testing.T) { - device := devices[2] - var initialSize int - for observation := 1; observation <= 120; observation++ { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - device.Labels = map[string]string{"observation": fmt.Sprint(observation)} - if err := actor.Update(ctx, device); err != nil { - t.Fatal(err) - } - current := &unstructured.Unstructured{} - current.SetAPIVersion("fleet.datumapis.com/v1alpha1") - current.SetKind("Device") - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), current); err != nil { - t.Fatal(err) - } - before := current.GetResourceVersion() - current.Object["status"] = map[string]any{"observation": int64(observation)} - if err := actor.Status().Update(ctx, current, client.FieldOwner("inventory-collector")); err != nil { - t.Fatal(err) - } - if before == current.GetResourceVersion() { - t.Fatal("status observation did not persist") - } - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - count := 0 - for _, fence := range ledger.DeviceFences { - if fence.UID == device.UID { - count++ - } - } - if count != 1 { - t.Fatalf("%d fences after %d observations", count, observation) - } - if observation == 1 { - initialSize = len(secret.Data["ledger.json"]) - } - if len(secret.Data["ledger.json"]) > initialSize+20 { - t.Fatal("ledger grows with routine observations") - } - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-collector"); err != nil { - t.Fatal(err) - } - }) - t.Run("delayed-old-write-cannot-commit-after-coalescing", func(t *testing.T) { - firstRelease := sync.OnceFunc(func() { close(gates["first"].release) }) - secondRelease := sync.OnceFunc(func() { close(gates["second"].release) }) - defer firstRelease() - defer secondRelease() - wait := func(pending *gate) { - t.Helper() - select { - case <-pending.entered: - case <-time.After(5 * time.Second): - t.Fatal("pending update did not enter admission") - } - } - device := devices[3] - first := device.DeepCopyObject().(*inventory.Device) - first.Labels = map[string]string{"admission-delay": "first"} - firstDone := make(chan error, 1) - go func() { firstDone <- actor.Update(ctx, first) }() - wait(gates["first"]) - device.Labels = map[string]string{"competing": "persisted"} - if err := actor.Update(ctx, device); err != nil { - t.Fatal(err) - } - currentVersion := device.ResourceVersion - second := device.DeepCopyObject().(*inventory.Device) - second.Labels = map[string]string{"admission-delay": "second"} - secondDone := make(chan error, 1) - go func() { secondDone <- actor.Update(ctx, second) }() - wait(gates["second"]) - firstRelease() - if err := <-firstDone; !apierrors.IsConflict(err) { - t.Fatalf("old in-flight baseline must conflict at storage: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if device.ResourceVersion != currentVersion { - t.Fatal("old in-flight write changed current version") - } - if err := register(t, device, "during-second-pending"); !apierrors.IsForbidden(err) { - t.Fatalf("coalescing lost current pending fence: %v", err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - count := 0 - for _, fence := range ledger.DeviceFences { - if fence.UID == device.UID { - count++ - if fence.Version != currentVersion { - t.Fatal("retained wrong pending version") - } - } - } - if count != 1 { - t.Fatalf("concurrent versions created %d fences", count) - } - secondRelease() - if err := <-secondDone; err != nil { - t.Fatal(err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - if err := register(t, device, "after-concurrent-writes"); err != nil { - t.Fatal(err) - } - }) - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.Entries) != 4 { - t.Fatalf("expected all registrations: %+v %v", ledger, err) - } - for _, entry := range ledger.Entries { - if entry.Outcome != "Recorded" || entry.CapacityUID == "" { - t.Fatalf("registration not recorded: %+v", entry) - } - } - if err := api.DeleteAllOf(ctx, &resourcemanager.Project{}); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "collection deletion") { - t.Fatalf("healthy authority did not reject unnamed lifetime deletion: %v", err) - } - server.Close() - for _, test := range []struct { - name string - write func() error - blocked bool - }{ - {"unrelated Device create", func() error { - device := devices[0].DeepCopyObject().(*inventory.Device) - device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "outside-after-outage", "", "", nil - device.Labels = map[string]string{"provider": "datum-cloud"} - return outside.Create(ctx, device) - }, false}, - {"provider Device create without opt-in labels", func() error { - device := devices[0].DeepCopyObject().(*inventory.Device) - device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "inside-after-outage", "", "", nil - device.Namespace = "other-namespace" - device.Labels = map[string]string{"provider": "unrelated-consumer"} - return actor.Create(ctx, device) - }, true}, - {"provider Device update", func() error { return actor.Update(ctx, devices[0], client.DryRunAll) }, true}, - {"provider Device status update", func() error { return actor.Status().Update(ctx, devices[0], client.DryRunAll) }, true}, - {"provider Device delete", func() error { return actor.Delete(ctx, devices[0]) }, true}, - {"unrelated default namespace delete", func() error { - return outside.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll) - }, false}, - {"provider other namespace delete", func() error { - return actor.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "other-namespace"}}) - }, false}, - {"provider default namespace delete", func() error { - return actor.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll) - }, true}, - {"unrelated root Project delete", func() error { - return api.Delete(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: "unrelated-consumer"}}) - }, false}, - {"protected root Project delete", func() error { - return api.Delete(ctx, &resourcemanager.Project{ObjectMeta: metav1.ObjectMeta{Name: "datum-cloud"}}) - }, true}, - {"protected root Project collection delete", func() error { return api.DeleteAllOf(ctx, &resourcemanager.Project{}) }, true}, - {"global capacity create", func() error { - return outside.Create(ctx, &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "outside-capacity", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: devices[0].Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}}) - }, true}, - } { - t.Run(test.name, func(t *testing.T) { - err := test.write() - if test.blocked { - if err == nil || !strings.Contains(err.Error(), "failed calling webhook") { - t.Fatalf("expected fail-closed transport error, got %v", err) - } - } else if err != nil { - t.Fatalf("unrelated operation depends on unavailable webhook: %v", err) - } - }) - } - for _, test := range []struct { - name string - extra map[string][]string - }{ - {"missing context", nil}, - {"nested organization context", map[string][]string{iam.ParentKindExtraKey: {"Organization"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}}}, - {"nested user context", map[string][]string{iam.ParentKindExtraKey: {"User"}, iam.ParentAPIGroupExtraKey: {"iam.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}}}, - {"ambiguous context", map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer", "datum-cloud"}}}, - {"empty context", map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {""}}}, - } { - t.Run(test.name, func(t *testing.T) { - unprovenConfig := rest.CopyConfig(actorConfig) - unprovenConfig.Impersonate.Extra = test.extra - unproven, err := client.New(unprovenConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - device := devices[0].DeepCopyObject().(*inventory.Device) - device.Name, device.UID, device.ResourceVersion, device.ManagedFields = "unproven-context", "", "", nil - for _, err := range []error{unproven.Create(ctx, device), unproven.Delete(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}}, client.DryRunAll)} { - if err == nil || !strings.Contains(err.Error(), "failed calling webhook") { - t.Fatalf("ambiguous routing context bypassed fail-closed transport: %v", err) - } - } - }) - } -} diff --git a/internal/registration/admission_regression_test.go b/internal/registration/admission_regression_test.go deleted file mode 100644 index 763d9732..00000000 --- a/internal/registration/admission_regression_test.go +++ /dev/null @@ -1,75 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "testing" - - admissionv1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func TestIdenticalAdmissionObjects(t *testing.T) { - for _, test := range []struct { - name, old, current string - identical bool - }{ - {"key order and whitespace", `{"metadata":{"resourceVersion":"1"},"spec":{}}`, ` {"spec":{},"metadata":{"resourceVersion":"1"}} `, true}, - {"unknown field", `{"future":1}`, `{"future":2}`, false}, - {"large exact integers", `{"future":9007199254740992}`, `{"future":9007199254740993}`, false}, - {"managed fields", `{"metadata":{"managedFields":[]}}`, `{"metadata":{"managedFields":[{"manager":"new"}]}}`, false}, - {"status", `{"status":{}}`, `{"status":{"ready":true}}`, false}, - {"null versus absent", `{}`, `{"future":null}`, false}, - {"array order", `{"future":[1,2]}`, `{"future":[2,1]}`, false}, - {"null objects", `null`, `null`, false}, - {"malformed", `{`, `{`, false}, - {"trailing document", `{} {}`, `{}`, false}, - } { - t.Run(test.name, func(t *testing.T) { - if identicalObjects([]byte(test.old), []byte(test.current)) != test.identical { - t.Fatal("unexpected whole-object comparison") - } - }) - } -} - -func TestNoopCannotClearPendingRealUpdateFence(t *testing.T) { - handler, device := fixture(t) - ctx := context.Background() - registration := registrationRequest(t, device, "record") - update := registration - update.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - update.Operation = admissionv1.Update - update.OldObject.Raw, _ = json.Marshal(device) - changed := device.DeepCopyObject() - raw, _ := json.Marshal(changed) - var object map[string]any - _ = json.Unmarshal(raw, &object) - object["futureField"] = "changed" - update.Object.Raw, _ = json.Marshal(object) - if !handler.Handle(ctx, update).Allowed { - t.Fatal("real update rejected") - } - update.Object.Raw = update.OldObject.Raw - if !handler.Handle(ctx, update).Allowed { - t.Fatal("no-op rejected") - } - if handler.Handle(ctx, registration).Allowed { - t.Fatal("no-op cleared the pending real-update reservation") - } -} - -func TestLifetimeCollectionDeletionDenied(t *testing.T) { - for _, resource := range []metav1.GroupVersionResource{{Version: "v1", Resource: "namespaces"}, {Group: "resourcemanager.miloapis.com", Version: "v1alpha1", Resource: "projects"}} { - t.Run(resource.Resource, func(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "unused") - request.Operation = admissionv1.Delete - request.Name = "" - request.Resource = resource - if handler.Handle(context.Background(), request).Allowed { - t.Fatal("unnamed deletion cannot exclude a protected lifetime") - } - }) - } -} diff --git a/internal/registration/admission_test.go b/internal/registration/admission_test.go index 14ac05b5..cfde8b47 100644 --- a/internal/registration/admission_test.go +++ b/internal/registration/admission_test.go @@ -4,9 +4,8 @@ import ( "context" "encoding/json" "errors" - "fmt" + "strings" "sync" - "sync/atomic" "testing" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" @@ -24,7 +23,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) -func fixture(t *testing.T) (*Handler, *inventory.Device) { +func testScheme(t *testing.T) *runtime.Scheme { t.Helper() scheme := runtime.NewScheme() for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, metal.AddToScheme, inventory.AddToScheme} { @@ -32,18 +31,21 @@ func fixture(t *testing.T) (*Handler, *inventory.Device) { t.Fatal(err) } } + return scheme +} + +func fixture(t *testing.T) (*Handler, *inventory.Device) { + t.Helper() device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "server", Namespace: "default", UID: "device-1", ResourceVersion: "1"}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "SERIAL-1", SystemUUID: "11111111-1111-1111-1111-111111111111", Model: "test"}}} - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-1"}} - api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(device, namespace).Build() - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) - private := fake.NewClientBuilder().WithScheme(scheme).WithObjects(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "private", UID: "ledger-1"}, Data: map[string][]byte{"ledger.json": encoded}}).Build() - return &Handler{Store: Store{Client: private, Namespace: "private", Authority: "milo", Projects: []string{"provider"}, AllowInactiveForTests: true}, Resolve: func(context.Context, string) (Project, error) { + api := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(device).Build() + return &Handler{Projects: []string{"provider"}, Resolve: func(context.Context, string) (Project, error) { return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { return nil }}, device } -func registrationRequest(t *testing.T, device *inventory.Device, name string) admission.Request { +func registrationRequest(t *testing.T, device *inventory.Device) admission.Request { t.Helper() + name := CapacityName(device.UID) capacity := metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default", UID: types.UID("capacity-" + name), Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID), DeviceVersionAnnotation: device.ResourceVersion, OperationAnnotation: "client-" + name}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} raw, err := json.Marshal(capacity) if err != nil { @@ -52,47 +54,51 @@ func registrationRequest(t *testing.T, device *inventory.Device, name string) ad return admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{UID: types.UID("request-" + name), Name: name, Namespace: "default", Operation: admissionv1.Create, Resource: metav1.GroupVersionResource{Group: "metal.datumapis.com", Version: "v1alpha1", Resource: "machinecapacities"}, UserInfo: authenticationv1.UserInfo{Username: "operator", UID: "actor-1", Extra: map[string]authenticationv1.ExtraValue{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}}, Object: runtime.RawExtension{Raw: raw}}} } -func TestConcurrentRegistrationReservesOnce(t *testing.T) { - handler, device := fixture(t) - var allowed atomic.Int32 - var workers sync.WaitGroup - for index := 0; index < 20; index++ { - request := registrationRequest(t, device, fmt.Sprintf("capacity-%d", index)) - workers.Add(1) - go func() { - defer workers.Done() - if handler.Handle(context.Background(), request).Allowed { - allowed.Add(1) - } - }() - } - workers.Wait() - if allowed.Load() != 1 { - t.Fatalf("allowed %d registrations", allowed.Load()) - } - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil || len(ledger.Entries) != 1 { - t.Fatalf("ledger: %+v %v", ledger, err) +func changeCapacity(request *admission.Request, mutate func(*metal.MachineCapacity)) { + var capacity metal.MachineCapacity + _ = json.Unmarshal(request.Object.Raw, &capacity) + mutate(&capacity) + request.Name = capacity.Name + request.Object.Raw, _ = json.Marshal(capacity) +} + +func providerClient(t *testing.T, handler *Handler) client.Client { + t.Helper() + project, err := handler.Resolve(context.Background(), "provider") + if err != nil { + t.Fatal(err) } - entry := ledger.Entries[0] - if entry.Actor.UID != "actor-1" || entry.DeviceUID != device.UID || entry.DeviceVersion != device.ResourceVersion || entry.ProjectUID != "project-1" || entry.NamespaceUID != "namespace-1" || entry.Outcome != "Unknown" { - t.Fatalf("authority not retained: %+v", entry) + return project.Client +} + +func TestRegistrationAllowsLiveEligibleDeviceWithoutEffects(t *testing.T) { + handler, device := fixture(t) + request := registrationRequest(t, device) + dryRun := true + request.DryRun = &dryRun + if response := handler.Handle(context.Background(), request); !response.Allowed { + t.Fatalf("eligible registration denied: %s", response.Result.Message) } - project, _ := handler.Resolve(context.Background(), "provider") var capacities metal.MachineCapacityList - if err := project.Client.List(context.Background(), &capacities); err != nil || len(capacities.Items) != 0 { - t.Fatal("admission caused public effects") + if err := providerClient(t, handler).List(context.Background(), &capacities); err != nil || len(capacities.Items) != 0 { + t.Fatal("admission caused public effects", err) } } func TestRegistrationNegatives(t *testing.T) { tests := map[string]func(*Handler, *inventory.Device, *admission.Request){ "stale UID": func(_ *Handler, _ *inventory.Device, request *admission.Request) { - changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations[DeviceUIDAnnotation] = "old" }) + changeCapacity(request, func(capacity *metal.MachineCapacity) { + capacity.Annotations[DeviceUIDAnnotation] = "old" + capacity.Name = CapacityName("old") + }) }, "stale RV": func(_ *Handler, _ *inventory.Device, request *admission.Request) { changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations[DeviceVersionAnnotation] = "old" }) }, + "authored name": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Name = "authored-name" }) + }, "enabled": func(_ *Handler, _ *inventory.Device, request *admission.Request) { changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Spec.AllocationPolicy = "Enabled" }) }, @@ -101,6 +107,11 @@ func TestRegistrationNegatives(t *testing.T) { capacity.Spec.CleaningPolicyRef.Name = "synthetic-tenant-reuse-v1" }) }, + "owner reference": func(_ *Handler, device *inventory.Device, request *admission.Request) { + changeCapacity(request, func(capacity *metal.MachineCapacity) { + capacity.OwnerReferences = []metav1.OwnerReference{{APIVersion: inventory.GroupVersion.String(), Kind: "Device", Name: device.Name, UID: device.UID}} + }) + }, "no baseline": func(_ *Handler, _ *inventory.Device, request *admission.Request) { changeCapacity(request, func(capacity *metal.MachineCapacity) { capacity.Annotations = nil }) }, @@ -110,28 +121,52 @@ func TestRegistrationNegatives(t *testing.T) { "direct delete": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.Operation = admissionv1.Delete }, - "status": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.SubResource = "status" }, + "status": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.SubResource = "status" }, + "other resource": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + request.Resource.Resource = "devices" + }, "missing project": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.UserInfo.Extra = nil }, + "missing actor": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.UserInfo.UID = "" }, + "organization context": func(_ *Handler, _ *inventory.Device, request *admission.Request) { + request.UserInfo.Extra[iam.ParentKindExtraKey] = authenticationv1.ExtraValue{"Organization"} + }, "wrong project": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.UserInfo.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{"consumer"} }, "namespace": func(_ *Handler, _ *inventory.Device, request *admission.Request) { request.Namespace = "other" }, - "permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { - handler.Authorize = func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { - return errors.New("denied") + "project lifetime unavailable": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + handler.Resolve = func(context.Context, string) (Project, error) { return Project{}, errors.New("deleting") } + }, + "capacity permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + if resource == "machinecapacities" { + return errors.New("denied") + } + return nil + } + }, + "device permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + if resource == "devices" { + return errors.New("denied") + } + return nil + } + }, + "missing device": func(handler *Handler, device *inventory.Device, _ *admission.Request) { + if err := providerClient(t, handler).Delete(context.Background(), device); err != nil { + t.Fatal(err) } }, "partial identity": func(handler *Handler, device *inventory.Device, request *admission.Request) { - project, _ := handler.Resolve(context.Background(), "provider") device.Spec.Identity.SystemUUID = "" - if err := project.Client.Update(context.Background(), device); err != nil { + if err := providerClient(t, handler).Update(context.Background(), device); err != nil { t.Fatal(err) } - *request = registrationRequest(t, device, request.Name) + *request = registrationRequest(t, device) }, "unresolved legacy": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { - project, _ := handler.Resolve(context.Background(), "provider") - if err := project.Client.Create(context.Background(), &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "missing"}, AllocationPolicy: "Enabled"}}); err != nil { + if err := providerClient(t, handler).Create(context.Background(), &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "missing"}, AllocationPolicy: "Enabled"}}); err != nil { t.Fatal(err) } }, @@ -139,144 +174,83 @@ func TestRegistrationNegatives(t *testing.T) { for name, mutate := range tests { t.Run(name, func(t *testing.T) { handler, device := fixture(t) - request := registrationRequest(t, device, "record") + request := registrationRequest(t, device) mutate(handler, device, &request) if response := handler.Handle(context.Background(), request); response.Allowed { t.Fatal("unsafe registration allowed") } - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil || len(ledger.Entries) != 0 { - t.Fatal("negative modified registration ledger", err) - } }) } } -func changeCapacity(request *admission.Request, mutate func(*metal.MachineCapacity)) { - var capacity metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &capacity) - mutate(&capacity) - request.Object.Raw, _ = json.Marshal(capacity) -} - -func TestUnknownRecoveryDoesNotAdoptCopiedAnnotation(t *testing.T) { +func TestMissingDeviceIsNamed(t *testing.T) { handler, device := fixture(t) - request := registrationRequest(t, device, "record") - if !handler.Handle(context.Background(), request).Allowed { - t.Fatal("registration denied") - } - restarted := *handler - if err := restarted.Recover(context.Background()); err != nil { + if err := providerClient(t, handler).Delete(context.Background(), device); err != nil { t.Fatal(err) } - if handler.Handle(context.Background(), registrationRequest(t, device, "different-name")).Allowed { - t.Fatal("unknown reservation was released") + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "does not exist") { + t.Fatalf("missing Device not reported: %+v", response.Result) } - var recreated metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &recreated) - recreated.UID = "recreated-with-copied-annotations" - project, _ := handler.Resolve(context.Background(), "provider") - if err := project.Client.Create(context.Background(), &recreated); err != nil { +} + +func TestUnauthorizedCallerCannotProbeDeviceExistence(t *testing.T) { + handler, device := fixture(t) + if err := providerClient(t, handler).Delete(context.Background(), device); err != nil { t.Fatal(err) } - if err := restarted.Recover(context.Background()); err != nil { - t.Fatal(err) + handler.Authorize = func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { + return errors.New("current get permission on devices is required") } - _, ledger, _ := handler.Store.Read(context.Background()) - if ledger.Entries[0].Outcome != "IncarnationConflict" { - t.Fatal("recreated capacity was adopted") + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || strings.Contains(response.Result.Message, "does not exist") { + t.Fatalf("unauthorized caller learned Device existence: %+v", response.Result) } } -func TestSharedAliasesAndProjectScope(t *testing.T) { - for _, alias := range []string{"serial", "uuid"} { +func TestSharedAliasesAcrossLiveDevices(t *testing.T) { + for _, alias := range []string{"serial", "uuid", "normalized serial", "provider"} { t.Run(alias, func(t *testing.T) { handler, device := fixture(t) - project, _ := handler.Resolve(context.Background(), "provider") + api := providerClient(t, handler) duplicate := device.DeepCopyObject().(*inventory.Device) duplicate.Name, duplicate.UID, duplicate.ResourceVersion = "alias", "alias-uid", "" - if alias == "serial" { - duplicate.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" - } else { - duplicate.Spec.Identity.Serial = "other" + duplicate.Spec.Identity.Serial = "other" + duplicate.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" + switch alias { + case "serial": + duplicate.Spec.Identity.Serial = device.Spec.Identity.Serial + case "normalized serial": + duplicate.Spec.Identity.Serial = " serial-1 " + case "uuid": + duplicate.Spec.Identity.SystemUUID = device.Spec.Identity.SystemUUID + case "provider": + device.Spec.ProviderHostRef = &inventory.ExternalReference{System: "Provider", Type: "server", ID: "shared-asset"} + duplicate.Spec.ProviderHostRef = &inventory.ExternalReference{System: "provider", Type: " SERVER", ID: "shared-asset"} + if err := api.Update(context.Background(), device); err != nil { + t.Fatal(err) + } } - if err := project.Client.Create(context.Background(), duplicate); err != nil { + if err := api.Create(context.Background(), duplicate); err != nil { t.Fatal(err) } - if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { - t.Fatal("ambiguous alias accepted") - } - }) - } -} - -func TestDeviceDeleteRaceRetainsFence(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "record") - deletion := request - deletion.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - deletion.Operation = admissionv1.Delete - deletion.OldObject.Raw, _ = json.Marshal(device) - if !handler.Handle(context.Background(), deletion).Allowed { - t.Fatal("unbound deletion denied") - } - if handler.Handle(context.Background(), request).Allowed { - t.Fatal("registration raced a pending Device deletion") - } - other, selected := fixture(t) - if !other.Handle(context.Background(), registrationRequest(t, selected, "record")).Allowed { - t.Fatal("registration denied") - } - if other.Handle(context.Background(), deletion).Allowed { - t.Fatal("bound Device deletion allowed") - } -} - -func TestProjectLifetimeRecheck(t *testing.T) { - handler, device := fixture(t) - resolve := handler.Resolve - var calls int - handler.Resolve = func(ctx context.Context, name string) (Project, error) { - project, err := resolve(ctx, name) - calls++ - if calls > 1 { - project.Identity.UID = "recreated" - } - return project, err - } - if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { - t.Fatal("project recreation accepted") - } -} - -func TestNamespaceRecreationAndPermissionRevocationDuringAdmission(t *testing.T) { - for _, mode := range []string{"namespace", "permission"} { - t.Run(mode, func(t *testing.T) { - handler, device := fixture(t) - var calls int - handler.Authorize = func(ctx context.Context, project Project, _ authenticationv1.UserInfo, _, _, _ string) error { - calls++ - if calls == 3 { - if mode == "permission" { - return errors.New("revoked") - } - var namespace corev1.Namespace - if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil { - return err - } - if err := project.Client.Delete(ctx, &namespace); err != nil { - return err - } - return project.Client.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "recreated"}}) + for _, selected := range []*inventory.Device{device, duplicate} { + if err := api.Get(context.Background(), client.ObjectKeyFromObject(selected), selected); err != nil { + t.Fatal(err) } - return nil + response := handler.Handle(context.Background(), registrationRequest(t, selected)) + if response.Allowed || !strings.Contains(response.Result.Message, "shares recorded hardware identity") { + t.Fatalf("duplicate identity accepted for %s: %+v", selected.Name, response.Result) + } + } + if err := api.Delete(context.Background(), duplicate); err != nil { + t.Fatal(err) } - response := handler.Handle(context.Background(), registrationRequest(t, device, "record")) - if mode == "permission" && response.Allowed { - t.Fatal("revocation accepted") + if err := api.Get(context.Background(), client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) } - if mode == "namespace" && response.Allowed { - t.Fatal("namespace recreation admitted") + if response := handler.Handle(context.Background(), registrationRequest(t, device)); !response.Allowed { + t.Fatalf("resolved duplicate still blocks registration: %s", response.Result.Message) } }) } @@ -303,30 +277,29 @@ func TestCrossProjectAmbiguityAndSharedProviderAlias(t *testing.T) { t.Fatal(err) } } - second := fake.NewClientBuilder().WithScheme(first.Client.Scheme()).WithObjects(other, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default", UID: "namespace-2"}}).Build() - secret, ledger, _ := handler.Store.Read(context.Background()) - ledger.Projects = []string{"provider", "second"} - if err := handler.Store.Write(context.Background(), secret, ledger); err != nil { - t.Fatal(err) - } - handler.Store.Projects = ledger.Projects + second := fake.NewClientBuilder().WithScheme(first.Client.Scheme()).WithObjects(other).Build() + handler.Projects = []string{"provider", "second"} handler.Resolve = func(_ context.Context, name string) (Project, error) { if name == "provider" { return first, nil } return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "second", UID: "project-2"}, Client: second}, nil } - firstRequest := registrationRequest(t, device, "one") - secondRequest := registrationRequest(t, other, "two") + firstRequest := registrationRequest(t, device) + secondRequest := registrationRequest(t, other) secondRequest.UserInfo.Extra[iam.ParentNameExtraKey] = authenticationv1.ExtraValue{"second"} var workers sync.WaitGroup for _, request := range []admission.Request{firstRequest, secondRequest} { workers.Add(1) go func() { defer workers.Done() - if handler.Handle(context.Background(), request).Allowed { + response := handler.Handle(context.Background(), request) + if response.Allowed { t.Error("cross-project alias ambiguity accepted") } + if strings.Contains(response.Result.Message, "second/") || strings.Contains(response.Result.Message, "default/server") { + t.Errorf("conflict in another provider project was named: %s", response.Result.Message) + } }() } workers.Wait() @@ -334,99 +307,77 @@ func TestCrossProjectAmbiguityAndSharedProviderAlias(t *testing.T) { } } -type timeoutAfterWrite struct{ client.Client } - -func (api timeoutAfterWrite) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { - if err := api.Client.Update(ctx, object, options...); err != nil { - return err +func TestDeviceAlreadyBackingCapacity(t *testing.T) { + for _, binding := range []string{"device reference", "device UID annotation"} { + t.Run(binding, func(t *testing.T) { + handler, device := fixture(t) + existing := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "earlier-record", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if binding == "device UID annotation" { + // A capacity whose Device was renamed away still binds the UID. + other := device.DeepCopyObject().(*inventory.Device) + other.Name, other.UID, other.ResourceVersion = "renamed", "device-renamed", "" + other.Spec.Identity.Serial, other.Spec.Identity.SystemUUID = "renamed-serial", "33333333-3333-3333-3333-333333333333" + if err := providerClient(t, handler).Create(context.Background(), other); err != nil { + t.Fatal(err) + } + existing.Spec.DeviceRef.Name = other.Name + existing.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} + } + if err := providerClient(t, handler).Create(context.Background(), existing); err != nil { + t.Fatal(err) + } + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "already backs capacity earlier-record") { + t.Fatalf("second capacity for one Device accepted: %+v", response.Result) + } + }) } - return errors.New("timeout after commit") } -func TestLedgerWriteTimeoutRetainsReservationAcrossRestart(t *testing.T) { +func TestReplacementDeviceUnderSameNameCannotRegister(t *testing.T) { handler, device := fixture(t) - private := handler.Store.Client - handler.Store.Client = timeoutAfterWrite{private} - if handler.Handle(context.Background(), registrationRequest(t, device, "record")).Allowed { - t.Fatal("timeout became success") - } - handler.Store.Client = private - restarted := *handler - if err := restarted.Recover(context.Background()); err != nil { + api := providerClient(t, handler) + registered := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName(device.UID), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID)}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := api.Create(context.Background(), registered); err != nil { t.Fatal(err) } - if restarted.Handle(context.Background(), registrationRequest(t, device, "new-name")).Allowed { - t.Fatal("unknown reservation was reused") - } - _, ledger, _ := restarted.Store.Read(context.Background()) - if len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Unknown" { - t.Fatal("unknown reservation lost") - } -} - -func TestDeviceCreatedThroughAdmissionCanRegister(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "record") - creation := request - creation.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Resource: "devices", Version: "v1alpha1"} - creation.Object.Raw, _ = json.Marshal(device) - if !handler.Handle(context.Background(), creation).Allowed { - t.Fatal("Device create admission denied") - } - if !handler.Handle(context.Background(), request).Allowed { - t.Fatal("own Device creation fence prevented registration") - } -} - -func TestRootProjectDeletionAndDeviceNameReuseAreFenced(t *testing.T) { - handler, device := fixture(t) - request := registrationRequest(t, device, "record") - if !handler.Handle(context.Background(), request).Allowed { - t.Fatal("registration denied") - } - deletion := request - deletion.Name = "provider" - deletion.Operation = admissionv1.Delete - deletion.Resource = metav1.GroupVersionResource{Group: "resourcemanager.miloapis.com", Version: "v1alpha1", Resource: "projects"} - deletion.UserInfo.Extra = nil - if handler.Handle(context.Background(), deletion).Allowed { - t.Fatal("root Project deletion bypass") + if err := api.Delete(context.Background(), device); err != nil { + t.Fatal(err) } replacement := device.DeepCopyObject().(*inventory.Device) - replacement.UID = "recreated" - replacement.Spec.Identity.Serial = "new-serial" - replacement.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" - creation := registrationRequest(t, device, "record") - creation.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - creation.Object.Raw, _ = json.Marshal(replacement) - if handler.Handle(context.Background(), creation).Allowed { - t.Fatal("registered Device name was reused by a new incarnation") + replacement.UID, replacement.ResourceVersion = "device-replacement", "" + replacement.Spec.Identity.Serial, replacement.Spec.Identity.SystemUUID = "replacement-serial", "44444444-4444-4444-4444-444444444444" + if err := api.Create(context.Background(), replacement); err != nil { + t.Fatal(err) + } + if handler.Handle(context.Background(), registrationRequest(t, replacement)).Allowed { + t.Fatal("replacement Device adopted capacity that names its predecessor") } } func TestNonConflictingLegacyCapacityAndAllocationRemainUntouched(t *testing.T) { handler, device := fixture(t) ctx := context.Background() - project, _ := handler.Resolve(ctx, "provider") + api := providerClient(t, handler) legacyDevice := device.DeepCopyObject().(*inventory.Device) legacyDevice.Name, legacyDevice.UID, legacyDevice.ResourceVersion = "legacy-device", "legacy-device-uid", "" legacyDevice.Spec.Identity.Serial, legacyDevice.Spec.Identity.SystemUUID = "legacy-serial", "22222222-2222-2222-2222-222222222222" legacy := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy", Namespace: "default", UID: "legacy-uid"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: legacyDevice.Name}, AllocationPolicy: "Enabled", ReclaimPolicy: "Retain", CleaningPolicyRef: metal.LocalReference{Name: "synthetic-tenant-reuse-v1"}}, Status: metal.MachineCapacityStatus{Conditions: []metav1.Condition{{Type: "Available", Status: metav1.ConditionFalse, Reason: "Occupied"}}}} allocation := &metal.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: "occupied", Namespace: "default", UID: "allocation-uid"}} for _, object := range []client.Object{legacyDevice, legacy, allocation} { - if err := project.Client.Create(ctx, object); err != nil { + if err := api.Create(ctx, object); err != nil { t.Fatal(err) } } beforeCapacity, _ := json.Marshal(legacy) beforeAllocation, _ := json.Marshal(allocation) - if !handler.Handle(ctx, registrationRequest(t, device, "record")).Allowed { - t.Fatal("non-conflicting legacy capacity blocked registration") + if response := handler.Handle(ctx, registrationRequest(t, device)); !response.Allowed { + t.Fatalf("non-conflicting legacy capacity blocked registration: %s", response.Result.Message) } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(legacy), legacy); err != nil { + if err := api.Get(ctx, client.ObjectKeyFromObject(legacy), legacy); err != nil { t.Fatal(err) } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { + if err := api.Get(ctx, client.ObjectKeyFromObject(allocation), allocation); err != nil { t.Fatal(err) } afterCapacity, _ := json.Marshal(legacy) @@ -434,69 +385,17 @@ func TestNonConflictingLegacyCapacityAndAllocationRemainUntouched(t *testing.T) if string(beforeCapacity) != string(afterCapacity) || string(beforeAllocation) != string(afterAllocation) { t.Fatal("registration modified legacy state") } - if handler.Handle(ctx, registrationRequest(t, legacyDevice, "conflicting")).Allowed { - t.Fatal("occupied legacy asset was registered") - } -} - -func TestRecoveryReadFailureBecomesUnknownWithoutReleasing(t *testing.T) { - handler, device := fixture(t) - ctx := context.Background() - request := registrationRequest(t, device, "record") - if !handler.Handle(ctx, request).Allowed { - t.Fatal("registration denied") - } - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + if err := api.Get(ctx, client.ObjectKeyFromObject(legacyDevice), legacyDevice); err != nil { t.Fatal(err) } - project, _ := handler.Resolve(ctx, "provider") - if err := project.Client.Create(ctx, &capacity); err != nil { - t.Fatal(err) - } - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, before, _ := handler.Store.Read(ctx) - if before.Entries[0].Outcome != "Recorded" { - t.Fatal("exact completion not recovered") - } - handler.Resolve = func(context.Context, string) (Project, error) { - return Project{}, errors.New("read authority unavailable") - } - if err := handler.Recover(ctx); err == nil { - t.Fatal("read failure became success") - } - _, after, _ := handler.Store.Read(ctx) - if len(after.Entries) != 1 || after.Entries[0].Outcome != "Unknown" || after.Entries[0].CapacityUID != before.Entries[0].CapacityUID { - t.Fatal("uncertain recovery lost its reservation or retained a positive observation") + if handler.Handle(ctx, registrationRequest(t, legacyDevice)).Allowed { + t.Fatal("occupied legacy asset was registered") } } -func TestPendingDeviceUpdateCannotRaceSelectedVersion(t *testing.T) { - handler, device := fixture(t) - ctx := context.Background() - registration := registrationRequest(t, device, "record") - update := registration - update.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - update.Operation = admissionv1.Update - update.OldObject.Raw, _ = json.Marshal(device) - device.Labels = map[string]string{"display": "changed"} - update.Object.Raw, _ = json.Marshal(device) - if !handler.Handle(ctx, update).Allowed { - t.Fatal("unbound Device update rejected") - } - if handler.Handle(ctx, registration).Allowed { - t.Fatal("registration raced an admitted but uncompleted Device update") - } - project, _ := handler.Resolve(ctx, "provider") - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if handler.Handle(ctx, registration).Allowed { - t.Fatal("stale UI selection silently refreshed") - } - if !handler.Handle(ctx, registrationRequest(t, device, "explicit-new-selection")).Allowed { - t.Fatal("explicit new persisted baseline rejected") +func TestCapacityNameIsDerivedFromDeviceUID(t *testing.T) { + name := CapacityName("0b1f0a52-6f0e-4f43-9c1e-4c8b7f3d2a10") + if name != "device-0b1f0a52-6f0e-4f43-9c1e-4c8b7f3d2a10" || len(name) > 63 { + t.Fatalf("unexpected capacity name %q", name) } } diff --git a/internal/registration/bounded_fences_test.go b/internal/registration/bounded_fences_test.go deleted file mode 100644 index 8121d7f0..00000000 --- a/internal/registration/bounded_fences_test.go +++ /dev/null @@ -1,200 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "strings" - "testing" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - admissionv1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" -) - -func deviceUpdate(t *testing.T, device *inventory.Device) admission.Request { - t.Helper() - request := registrationRequest(t, device, "unused") - request.Resource = metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} - request.Name = device.Name - request.Operation = admissionv1.Update - request.OldObject.Raw, _ = json.Marshal(device) - changed := device.DeepCopyObject().(*inventory.Device) - changed.Labels = map[string]string{"observation": "changed"} - request.Object.Raw, _ = json.Marshal(changed) - return request -} - -func TestCoalescingRetainsPendingAndUnknownVersions(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - project, _ := handler.Resolve(ctx, "provider") - oldRequest := deviceUpdate(t, device) - for attempt := 0; attempt < 10; attempt++ { - if response := handler.Handle(ctx, oldRequest); !response.Allowed { - t.Fatal(response.Result) - } - } - if handler.Handle(ctx, registrationRequest(t, device, "pending-first")).Allowed { - t.Fatal("pending concurrent updates did not fence current version") - } - device.Labels = map[string]string{"committed": "first"} - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - newRequest := deviceUpdate(t, device) - if response := handler.Handle(ctx, newRequest); !response.Allowed { - t.Fatal(response.Result) - } - if handler.Handle(ctx, oldRequest).Allowed { - t.Fatal("late stale admission replaced the current pending fence") - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.DeviceFences) != 1 || ledger.DeviceFences[0].Version != device.ResourceVersion { - t.Fatalf("not coalesced at current pending baseline: %+v %v", ledger, err) - } - restarted := *handler - if restarted.Handle(ctx, registrationRequest(t, device, "unknown-second")).Allowed { - t.Fatal("unknown or rejected write released after restart") - } - noop := newRequest - noop.Object = noop.OldObject - if !restarted.Handle(ctx, noop).Allowed || restarted.Handle(ctx, registrationRequest(t, device, "after-noop")).Allowed { - t.Fatal("no-op must neither fail nor release a pending baseline") - } - device.Labels["committed"] = "second" - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if response := restarted.Handle(ctx, registrationRequest(t, device, "fresh")); !response.Allowed { - t.Fatal(response.Result) - } -} - -func TestCoalescingLegacyFencesPreservesAliasesAndTombstones(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - secret, ledger, _ := handler.Store.Read(ctx) - ledger.DeviceFences = []DeviceFence{ - {Project: "provider", UID: device.UID, Aliases: aliases(device)}, - {Project: "provider", UID: device.UID, Version: "older"}, - {Project: "provider", UID: device.UID, Version: device.ResourceVersion}, - {Project: "other", UID: device.UID, Version: "unrelated"}, - } - if err := handler.Store.Write(ctx, secret, ledger); err != nil { - t.Fatal(err) - } - update := deviceUpdate(t, device) - if response := handler.Handle(ctx, update); !response.Allowed { - t.Fatal(response.Result) - } - _, ledger, _ = handler.Store.Read(ctx) - if len(ledger.DeviceFences) != 2 || len(ledger.DeviceFences[1].Aliases) != len(aliases(device)) || ledger.DeviceFences[0].Project != "other" { - t.Fatalf("lost aliases or unrelated fences: %+v", ledger) - } - deletion := update - deletion.Operation = admissionv1.Delete - if !handler.Handle(ctx, deletion).Allowed || handler.Handle(ctx, update).Allowed { - t.Fatal("delete must permanently dominate pending update fences") - } - create := update - create.Operation = admissionv1.Create - recreated := device.DeepCopyObject().(*inventory.Device) - recreated.UID = "recreated" - create.Object.Raw, _ = json.Marshal(recreated) - if handler.Handle(ctx, create).Allowed { - t.Fatal("never-registered deleted hardware aliases were released") - } - _, ledger, _ = handler.Store.Read(ctx) - if len(ledger.DeviceFences) != 2 || !ledger.DeviceFences[1].Deleted || ledger.DeviceFences[1].Version != "" { - t.Fatalf("delete did not coalesce into permanent tombstone: %+v", ledger) - } -} - -func TestLedgerExactSizeCap(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - secret, ledger, _ := handler.Store.Read(ctx) - ledger.DeviceFences = []DeviceFence{{Project: "provider", UID: "device", Aliases: []string{""}}} - encoded, _ := json.Marshal(ledger) - ledger.DeviceFences[0].Aliases[0] = strings.Repeat("x", TailBudget-len(encoded)) - if err := handler.Store.Write(ctx, secret, ledger); err != nil { - t.Fatalf("exact tail budget must fit: %v", err) - } - before := secret.ResourceVersion - ledger.DeviceFences[0].Aliases[0] += "x" - if err := handler.Store.Write(ctx, secret, ledger); err == nil || !strings.Contains(err.Error(), "ledger is full") { - t.Fatalf("tail budget plus one must fail closed: %v", err) - } - current, _, err := handler.Store.Read(ctx) - if err != nil || current.ResourceVersion != before || len(current.Data["ledger.json"]) != TailBudget { - t.Fatal("oversized write changed durable reservations") - } -} - -func TestDryRunCannotReserve(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - before, _, _ := handler.Store.Read(ctx) - for _, request := range []admission.Request{registrationRequest(t, device, "dry"), deviceUpdate(t, device)} { - dry := true - request.DryRun = &dry - if response := handler.Handle(ctx, request); response.Allowed || !strings.Contains(response.Result.Message, "dry-run") { - t.Fatalf("dry run was not explicitly denied: %+v", response) - } - } - after, ledger, _ := handler.Store.Read(ctx) - if before.ResourceVersion != after.ResourceVersion || len(ledger.Entries) != 0 || len(ledger.DeviceFences) != 0 { - t.Fatal("dry-run retained effects") - } - project, _ := handler.Resolve(ctx, "provider") - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil || device.ResourceVersion != "1" { - t.Fatal("dry-run changed Device") - } -} - -type afterDeviceReadClient struct { - client.Client - after func() -} - -func (api *afterDeviceReadClient) Get(ctx context.Context, key client.ObjectKey, object client.Object, options ...client.GetOption) error { - err := api.Client.Get(ctx, key, object, options...) - if _, device := object.(*inventory.Device); err == nil && device && api.after != nil { - after := api.after - api.after = nil - after() - } - return err -} - -func TestConcurrentNewerPendingFenceForcesBaselineRecheck(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - project, _ := handler.Resolve(ctx, "provider") - oldRequest := deviceUpdate(t, device) - interleaved := &afterDeviceReadClient{Client: project.Client} - interleaved.after = func() { - device.Labels = map[string]string{"committed": "first"} - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if response := handler.Handle(ctx, deviceUpdate(t, device)); !response.Allowed { - t.Fatal(response.Result) - } - } - handler.Resolve = func(context.Context, string) (Project, error) { - return Project{Identity: project.Identity, Client: interleaved}, nil - } - if handler.Handle(ctx, oldRequest).Allowed { - t.Fatal("stale admission survived newer pending fence CAS") - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.DeviceFences) != 1 || ledger.DeviceFences[0].Version != device.ResourceVersion { - t.Fatalf("newer pending fence lost: %+v %v", ledger, err) - } - if handler.Handle(ctx, registrationRequest(t, device, "still-pending")).Allowed { - t.Fatal("newer pending version became registrable") - } -} diff --git a/internal/registration/contention_envtest_test.go b/internal/registration/contention_envtest_test.go deleted file mode 100644 index f6862092..00000000 --- a/internal/registration/contention_envtest_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package registration - -import ( - "bytes" - "context" - "fmt" - "log/slog" - "os" - "strings" - "testing" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" -) - -type contendedLedgerClient struct { - client.Client - remaining int - attempts int - conflicts int -} - -func (contender *contendedLedgerClient) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { - contender.attempts++ - if contender.remaining > 0 { - contender.remaining-- - completed := make(chan error, 1) - go func() { - current := &corev1.Secret{} - if err := contender.Client.Get(ctx, client.ObjectKeyFromObject(object), current); err != nil { - completed <- err - return - } - current.Annotations = map[string]string{"competing-writer": fmt.Sprint(contender.attempts)} - completed <- contender.Client.Update(ctx, current) - }() - if err := <-completed; err != nil { - return err - } - } - err := contender.Client.Update(ctx, object, options...) - if apierrors.IsConflict(err) { - contender.conflicts++ - } - return err -} - -func TestRealLedgerCASRetryBudget(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - environment := &envtest.Environment{} - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - for _, conflicts := range []int{5, 6} { - t.Run(fmt.Sprintf("conflicts-%d", conflicts), func(t *testing.T) { - handler, device := fixture(t) - secret, _, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - namespace := fmt.Sprintf("cas-%d", conflicts) - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}); err != nil { - t.Fatal(err) - } - secret.Namespace, secret.UID, secret.ResourceVersion = namespace, "", "" - if err := api.Create(ctx, secret); err != nil { - t.Fatal(err) - } - contender := &contendedLedgerClient{Client: api, remaining: conflicts} - handler.Store.Client, handler.Store.Namespace = contender, namespace - var logs bytes.Buffer - previous := slog.Default() - slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) - defer slog.SetDefault(previous) - response := handler.Handle(ctx, registrationRequest(t, device, "contended")) - if response.Allowed != (conflicts == 5) || contender.attempts != 6 || contender.conflicts != conflicts { - t.Fatalf("real CAS retry budget: allowed=%v attempts=%d conflicts=%d result=%v", response.Allowed, contender.attempts, contender.conflicts, response.Result) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - if conflicts == 5 && (len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Unknown") { - t.Fatal("successful CAS did not retain unknown reservation") - } - if conflicts == 6 && (len(ledger.Entries) != 0 || !strings.Contains(logs.String(), "CAS retries exhausted") || !strings.Contains(logs.String(), `"attempts":6`)) { - t.Fatalf("exhaustion was not observable or wrote reservation: %s", logs.String()) - } - }) - } -} diff --git a/internal/registration/control.go b/internal/registration/control.go deleted file mode 100644 index 4e46d7d0..00000000 --- a/internal/registration/control.go +++ /dev/null @@ -1,235 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "encoding/json" - "errors" - "log/slog" - "reflect" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -type ControlRequest struct { - Action string `json:"action"` - ID string `json:"id"` - Reason string `json:"reason"` - Authority string `json:"authority"` - Projects []string `json:"projects"` - RootUID types.UID `json:"rootUID"` - ResourceVersion string `json:"resourceVersion"` - Epoch uint64 `json:"epoch"` - FenceDigest string `json:"fenceDigest,omitempty"` -} - -type SignedControl struct { - Request ControlRequest `json:"request"` - Signature []byte `json:"signature"` -} - -func SignControl(request ControlRequest, key ed25519.PrivateKey) SignedControl { - encoded, _ := json.Marshal(request) - return SignedControl{Request: request, Signature: ed25519.Sign(key, append([]byte("fleet-registration-control-v2\n"), encoded...))} -} - -func (store Store) verifyControl(control SignedControl, uid types.UID) error { - request := control.Request - encoded, err := json.Marshal(request) - if err != nil { - return err - } - if len(store.ControlKey) != ed25519.PublicKeySize || len(encoded) > 8192 || !ed25519.Verify(store.ControlKey, append([]byte("fleet-registration-control-v2\n"), encoded...), control.Signature) { - return errors.New("registration control signature unavailable or invalid") - } - if request.RootUID != uid || request.Authority != store.Authority || !reflect.DeepEqual(request.Projects, store.Projects) || request.ResourceVersion == "" || request.ID == "" || request.Reason == "" || (request.Action != "expand" && request.Action != "activate") { - return errors.New("registration control authority or action mismatch") - } - return nil -} - -func (store Store) root(ctx context.Context) (*corev1.Secret, Routing, error) { - secret := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { - return nil, Routing{}, err - } - if secret.UID == "" || !secret.DeletionTimestamp.IsZero() { - return nil, Routing{}, errors.New("ledger lifetime unavailable") - } - if _, exists := secret.Data["routing.json"]; exists { - route, err := decodeRouting(secret) - return secret, route, err - } - return secret, Routing{Version: 2, RootUID: secret.UID}, nil -} - -func encodeRoute(secret *corev1.Secret, route Routing) error { - encoded, err := json.Marshal(route) - if err != nil { - return err - } - if _, exists := secret.Data["routing.json"]; !exists { - secret.Data["tail.json"] = secret.Data["ledger.json"] - secret.Data["ledger.json"] = []byte(`{"authority":"v2-routing-required","projects":[]}`) - } - secret.Data["routing.json"] = encoded - return nil -} - -func (handler *Handler) ApplyControl(ctx context.Context, control SignedControl) error { - secret, route, err := handler.Store.root(ctx) - if err != nil { - return err - } - if err := handler.Store.verifyControl(control, secret.UID); err != nil { - return err - } - if control.Request.Action == "expand" && control.Request.Epoch < route.Epoch { - reference := route.Segments[control.Request.Epoch] - segment := &corev1.Secret{} - if err := handler.Store.Client.Get(ctx, client.ObjectKey{Namespace: handler.Store.Namespace, Name: reference.Name}, segment); err != nil { - return err - } - encoded, _ := json.Marshal(control) - if segment.UID != reference.UID || segment.Immutable == nil || !*segment.Immutable || !segment.DeletionTimestamp.IsZero() || digest(segment.Data["ledger.json"]) != reference.Digest || string(segment.Data["control.json"]) != string(encoded) { - return errors.New("stale expansion does not match retained completion") - } - return nil - } - if route.Pending != nil { - if !reflect.DeepEqual(*route.Pending, control) { - return errors.New("another signed expansion is pending") - } - return handler.Store.ResumeExpansion(ctx) - } - if route.Activation != nil && reflect.DeepEqual(*route.Activation, control) { - return nil - } - if route.Epoch != control.Request.Epoch || secret.ResourceVersion != control.Request.ResourceVersion { - return errors.New("stale control epoch or CAS baseline; inspect current root") - } - if _, _, err := handler.Store.Read(ctx); err != nil { - return err - } - switch control.Request.Action { - case "activate": - if err := handler.verifyActivation(ctx, control); err != nil { - return err - } - if route.Activation != nil { - if len(route.ActivationHistory) >= 7 { - return errors.New("activation audit budget exhausted; retained history requires a reviewed migration") - } - route.ActivationHistory = append(route.ActivationHistory, *route.Activation) - } - route.Activation = &control - case "expand": - if len(route.Segments) >= MaxSegments { - return ErrSegmentsExhausted - } - route.Pending = &control - } - if err := encodeRoute(secret, route); err != nil { - return err - } - if err := handler.Store.updateRoot(ctx, secret); err != nil { - return err - } - slog.InfoContext(ctx, "registration signed control retained", "action", control.Request.Action, "id", control.Request.ID, "rootUID", secret.UID, "epoch", route.Epoch, "signer", digest(handler.Store.ControlKey)) - if route.Pending != nil { - return handler.Store.ResumeExpansion(ctx) - } - return nil -} - -func (store Store) ResumeExpansion(ctx context.Context) error { - secret, route, err := store.root(ctx) - if err != nil || route.Pending == nil { - return err - } - if err := store.verifyControl(*route.Pending, secret.UID); err != nil { - return err - } - if route.Pending.Request.Action != "expand" || route.Pending.Request.Epoch != route.Epoch || len(route.Segments) >= MaxSegments { - return errors.New("invalid pending expansion") - } - if _, _, err := store.readSnapshot(ctx, secret); err != nil { - return err - } - tail := secret.Data["tail.json"] - if len(tail) > SegmentBudget { - return ErrGrowthStopped - } - control, _ := json.Marshal(route.Pending) - immutable := true - segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: store.Namespace, Name: segmentName(secret.UID, route.Epoch)}, Immutable: &immutable, Data: map[string][]byte{"ledger.json": tail, "control.json": control, "rootUID": []byte(secret.UID)}} - if err := store.Client.Create(ctx, segment); err != nil && !apierrors.IsAlreadyExists(err) { - return err - } - stored := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKeyFromObject(segment), stored); err != nil { - return err - } - if stored.UID == "" || !stored.DeletionTimestamp.IsZero() || stored.Immutable == nil || !*stored.Immutable || !reflect.DeepEqual(stored.Data, segment.Data) { - return errors.New("expansion segment identity or contents conflict; remain fenced") - } - route.Segments = append(route.Segments, Segment{Name: stored.Name, UID: stored.UID, Digest: digest(tail)}) - route.Epoch++ - route.Pending = nil - empty, _ := json.Marshal(Ledger{Authority: store.Authority, Projects: store.Projects}) - secret.Data["tail.json"] = empty - if err := encodeRoute(secret, route); err != nil { - return err - } - if err := store.updateRoot(ctx, secret); err != nil { - return err - } - slog.InfoContext(ctx, "registration expansion committed", "rootUID", secret.UID, "epoch", route.Epoch, "segmentUID", stored.UID) - return nil -} - -func (handler *Handler) verifyActivation(ctx context.Context, control SignedControl) error { - if handler.VerifyFence == nil || handler.FenceDigest == nil { - return errors.New("activation fence verification unavailable") - } - if err := handler.VerifyFence(ctx); err != nil { - return err - } - actual, err := handler.FenceDigest(ctx) - if err != nil { - return err - } - if actual == "" || actual != control.Request.FenceDigest { - return errors.New("installed fence differs from signed activation") - } - return nil -} - -func (handler *Handler) Ready(ctx context.Context) error { - secret, route, err := handler.Store.root(ctx) - if err != nil { - return err - } - return handler.readySnapshot(ctx, secret, route) -} - -func (handler *Handler) readySnapshot(ctx context.Context, secret *corev1.Secret, route Routing) error { - if route.Pending != nil || route.Activation == nil { - return errors.New("registration is non-admitting: signed activation or expansion incomplete") - } - if err := handler.Store.verifyControl(*route.Activation, secret.UID); err != nil { - return err - } - if route.Activation.Request.Action != "activate" { - return errors.New("invalid activation action") - } - if err := handler.verifyActivation(ctx, *route.Activation); err != nil { - return err - } - _, _, err := handler.Store.readSnapshot(ctx, secret) - return err -} diff --git a/internal/registration/control_test.go b/internal/registration/control_test.go deleted file mode 100644 index 4b7572d7..00000000 --- a/internal/registration/control_test.go +++ /dev/null @@ -1,150 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "crypto/rand" - "encoding/json" - "errors" - "net/http" - "net/http/httptest" - "reflect" - "testing" - - admissionv1 "k8s.io/api/admission/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" -) - -func controlFor(t *testing.T, handler *Handler, key ed25519.PrivateKey, action string) SignedControl { - t.Helper() - secret, route, err := handler.Store.root(context.Background()) - if err != nil { - t.Fatal(err) - } - return SignControl(ControlRequest{Action: action, ID: "operator-change-" + secret.ResourceVersion, Reason: "synthetic test approval", Authority: handler.Store.Authority, Projects: handler.Store.Projects, RootUID: secret.UID, ResourceVersion: secret.ResourceVersion, Epoch: route.Epoch, FenceDigest: "approved-fence"}, key) -} - -func controlFixture(t *testing.T, handler *Handler) ed25519.PrivateKey { - t.Helper() - public, private, err := ed25519.GenerateKey(rand.Reader) - if err != nil { - t.Fatal(err) - } - handler.Store.ControlKey = public - handler.Store.AllowInactiveForTests = false - handler.VerifyFence = func(context.Context) error { return nil } - handler.FenceDigest = func(context.Context) (string, error) { return "approved-fence", nil } - return private -} - -func TestBootstrapDoesNotAdmitOrInterpretCallerConfiguration(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - private := controlFixture(t, handler) - server := httptest.NewServer(handler.Transport()) - defer server.Close() - for path, expected := range map[string]int{"/transportz": http.StatusNoContent, "/activationz": http.StatusServiceUnavailable} { - response, err := server.Client().Get(server.URL + path) - if err != nil { - t.Fatal(err) - } - response.Body.Close() - if response.StatusCode != expected { - t.Fatalf("%s: %d", path, response.StatusCode) - } - } - request := registrationRequest(t, device, "bootstrap") - for _, resource := range []metav1.GroupVersionResource{{Group: "metal.datumapis.com", Resource: "machinecapacities"}, {Group: "fleet.datumapis.com", Resource: "devices"}, {Resource: "namespaces"}, {Group: "resourcemanager.miloapis.com", Resource: "projects"}} { - request.Resource, request.Operation, request.Name = resource, admissionv1.Delete, "unrelated" - if handler.Handle(ctx, request).Allowed { - t.Fatal("bootstrap admitted a request") - } - } - control := controlFor(t, handler, private, "activate") - for name, mutate := range map[string]func(*SignedControl){ - "signature": func(control *SignedControl) { control.Signature[0] ^= 1 }, - "authority": func(control *SignedControl) { control.Request.Authority = "other" }, - "scope": func(control *SignedControl) { control.Request.Projects = []string{"other"} }, - "epoch": func(control *SignedControl) { control.Request.Epoch++ }, - "root": func(control *SignedControl) { control.Request.RootUID = "replacement" }, - "fence": func(control *SignedControl) { control.Request.FenceDigest = "relaxed" }, - } { - t.Run(name, func(t *testing.T) { - encoded, _ := json.Marshal(control) - var changed SignedControl - _ = json.Unmarshal(encoded, &changed) - mutate(&changed) - if handler.ApplyControl(ctx, changed) == nil { - t.Fatal("tampered configuration accepted") - } - if name != "signature" { - changed = SignControl(changed.Request, private) - if handler.ApplyControl(ctx, changed) == nil { - t.Fatal("wrong signed target accepted") - } - } - }) - } - handler.VerifyFence = func(context.Context) error { return errors.New("missing Fail webhook") } - if handler.ApplyControl(ctx, control) == nil { - t.Fatal("missing fence activated") - } - handler.VerifyFence = func(context.Context) error { return nil } - if err := handler.ApplyControl(ctx, control); err != nil { - t.Fatal(err) - } - if err := handler.ApplyControl(ctx, control); err != nil { - t.Fatal("activation retry", err) - } - if err := handler.Ready(ctx); err != nil { - t.Fatal(err) - } - secret, before, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - var legacy Ledger - if err := json.Unmarshal(secret.Data["ledger.json"], &legacy); err != nil || legacy.Authority == handler.Store.Authority { - t.Fatal("old binary not fenced") - } - handler.FenceDigest = func(context.Context) (string, error) { return "changed-fence", nil } - if handler.Handle(ctx, registrationRequest(t, device, "changed-trust")).Allowed { - t.Fatal("changed fence bypassed activation") - } - _, after, _ := handler.Store.Read(ctx) - if !reflect.DeepEqual(before, after) { - t.Fatal("denial changed reservations") - } - handler.FenceDigest = func(context.Context) (string, error) { return "approved-fence", nil } - handler.VerifyFence = func(context.Context) error { return errors.New("unavailable") } - if handler.Ready(ctx) == nil { - t.Fatal("lost fence reported active") - } - handler.VerifyFence = func(context.Context) error { return nil } - for range 7 { - if err := handler.ApplyControl(ctx, controlFor(t, handler, private, "activate")); err != nil { - t.Fatal(err) - } - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, private, "activate")); err == nil { - t.Fatal("activation audit history exceeded its bound") - } - current, _, err := handler.Store.root(ctx) - if err != nil { - t.Fatal(err) - } - if err := handler.Store.Client.Delete(ctx, current); err != nil { - t.Fatal(err) - } - if handler.Handle(ctx, registrationRequest(t, device, "lost-ledger")).Allowed { - t.Fatal("missing ledger admitted") - } - response, err := server.Client().Get(server.URL + "/transportz") - if err != nil { - t.Fatal(err) - } - response.Body.Close() - if response.StatusCode != http.StatusNoContent { - t.Fatal("missing ledger prevented transport inspection") - } -} diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index 8e21127f..7332f72b 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -3,14 +3,14 @@ package registration import ( "bytes" "context" - "encoding/json" "encoding/pem" + "errors" "io" "net/http/httptest" "os" "path/filepath" + "strings" "sync" - "sync/atomic" "testing" "time" @@ -19,9 +19,9 @@ import ( "go.datum.net/fleet/internal/controller" iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - authenticationv1 "k8s.io/api/authentication/v1" authorizationv1 "k8s.io/api/authorization/v1" corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -34,11 +34,15 @@ import ( "sigs.k8s.io/yaml" ) -func pemCertificate(raw []byte) []byte { - return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: raw}) +type liveAPI struct { + t *testing.T + config *rest.Config + scheme *runtime.Scheme + admin client.Client } -func TestRealAPIServerAdmissionAndCAS(t *testing.T) { +func startAPI(t *testing.T) *liveAPI { + t.Helper() if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS required") } @@ -53,307 +57,326 @@ func TestRealAPIServerAdmissionAndCAS(t *testing.T) { } }) scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, rbacv1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { if err := add(scheme); err != nil { t.Fatal(err) } } - api, err := client.New(config, client.Options{Scheme: scheme}) + admin, err := client.New(config, client.Options{Scheme: scheme}) if err != nil { t.Fatal(err) } - ctx := context.Background() - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system-private"}}); err != nil { - t.Fatal(err) - } - device := &inventory.Device{TypeMeta: metav1.TypeMeta{APIVersion: inventory.GroupVersion.String(), Kind: "Device"}, ObjectMeta: metav1.ObjectMeta{Name: "hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "serial-1", SystemUUID: "11111111-1111-1111-1111-111111111111"}}} - if err := api.Create(ctx, device); err != nil { - t.Fatal(err) - } - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"datum-cloud"}}) - if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "fleet-system-private"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { - t.Fatal(err) - } - protection, err := os.ReadFile("../../config/base/registration/protection.yaml") - if err != nil { - t.Fatal(err) - } - decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(protection), 4096) - for { - var object unstructured.Unstructured - err := decoder.Decode(&object.Object) - if err == io.EOF { - break - } - if err != nil { - t.Fatal(err) - } - if err := api.Create(ctx, &object); err != nil { - t.Fatal(err) - } - } - protectionDeadline := time.Now().Add(10 * time.Second) - for { - probe := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "fleet-system-private"}} - err := api.Delete(ctx, probe, client.DryRunAll) - if apierrors.IsInvalid(err) || apierrors.IsForbidden(err) { - break - } - if time.Now().After(protectionDeadline) { - t.Fatalf("ledger retention policy did not engage: %v", err) - } - time.Sleep(30 * time.Millisecond) - } - for { - probe := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "fleet-system-private"}} - err := api.Delete(ctx, probe, client.DryRunAll) - if apierrors.IsInvalid(err) || apierrors.IsForbidden(err) { - break - } - if time.Now().After(protectionDeadline) { - t.Fatalf("namespace retention policy did not engage: %v", err) - } - time.Sleep(30 * time.Millisecond) - } - privateConfig := rest.CopyConfig(config) - privateConfig.Impersonate = rest.ImpersonationConfig{UserName: "system:serviceaccount:fleet-system:fleet-registration", Groups: []string{"system:masters"}} - private, err := client.New(privateConfig, client.Options{Scheme: scheme}) + return &liveAPI{t: t, config: config, scheme: scheme, admin: admin} +} + +// actor impersonates a caller routed through the provider project, as Milo's +// routing filters establish it. +func (api *liveAPI) actor(name string, groups ...string) client.Client { + api.t.Helper() + config := rest.CopyConfig(api.config) + config.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: groups, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} + actor, err := client.New(config, client.Options{Scheme: api.scheme}) if err != nil { - t.Fatal(err) + api.t.Fatal(err) } - var denied atomic.Bool - handler := &Handler{Store: Store{Client: private, Namespace: "fleet-system-private", Authority: "milo", Projects: []string{"datum-cloud"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) }, Resolve: func(context.Context, string) (Project, error) { - return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api}, nil - }, Authorize: func(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { - if denied.Load() { - return ErrConflict - } - return Authorize(ctx, project, actor, group, resource, name) - }} - privateKey := controlFixture(t, handler) - handler.VerifyFence = func(ctx context.Context) error { return VerifyFence(ctx, api, []string{"datum-cloud"}) } - handler.FenceDigest = func(ctx context.Context) (string, error) { - var current admissionregistrationv1.ValidatingWebhookConfiguration - if err := api.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, ¤t); err != nil { - return "", err - } - encoded, err := json.Marshal(current.Webhooks) - return digest(encoded), err + return actor +} + +func (api *liveAPI) device(name, namespace, serial, uuid string) *inventory.Device { + api.t.Helper() + device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: serial, SystemUUID: uuid}}} + if err := api.admin.Create(context.Background(), device); err != nil { + api.t.Fatal(err) } - lateAdmission, release := make(chan struct{}), make(chan struct{}) - server := httptest.NewTLSServer(&admission.Webhook{Handler: admission.HandlerFunc(func(ctx context.Context, request admission.Request) admission.Response { - response := handler.Handle(ctx, request) - if response.Allowed && request.Resource.Resource == "machinecapacities" && request.Name == "admitted-never-persisted" { - close(lateAdmission) - select { - case <-release: - case <-ctx.Done(): - } - return admission.Denied("synthetic later admission/storage failure") - } - return response - })}) - t.Cleanup(server.Close) - url := server.URL + return device +} + +// installWebhook serves the production handler behind the packaged webhook +// configuration and returns the server so a test can take it away. +func (api *liveAPI) installWebhook() *httptest.Server { + api.t.Helper() + handler := &Handler{Projects: []string{"datum-cloud"}, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api.admin}, nil + }, Authorize: Authorize} + server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) + api.t.Cleanup(server.Close) data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") if err != nil { - t.Fatal(err) + api.t.Fatal(err) } webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} if err := yaml.UnmarshalStrict(data, webhooks); err != nil { - t.Fatal(err) + api.t.Fatal(err) } + url := server.URL for index := range webhooks.Webhooks { - webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} - } - if err := api.Create(ctx, webhooks); err != nil { - t.Fatal(err) + webhooks.Webhooks[index].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw})} } - activation := controlFor(t, handler, privateKey, "activate").Request - activation.FenceDigest, err = handler.FenceDigest(ctx) - if err != nil { - t.Fatal(err) + if err := api.admin.Create(context.Background(), webhooks); err != nil { + api.t.Fatal(err) } - if err := handler.ApplyControl(ctx, SignControl(activation, privateKey)); err != nil { - t.Fatal(err) - } - actorConfig := rest.CopyConfig(config) - actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} - actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) + operator := api.actor("operator", "system:masters") + api.eventually("registration webhook", func() bool { + probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "webhook-probe", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "absent"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + return apierrors.IsForbidden(operator.Create(context.Background(), probe, client.DryRunAll)) + }) + return server +} + +// installDeletionProtection applies the optional component's manifests as an +// environment that opts in would. +func (api *liveAPI) installDeletionProtection(probe *inventory.Device) { + api.t.Helper() + data, err := os.ReadFile("../../config/components/device-deletion-protection/policy.yaml") if err != nil { - t.Fatal(err) + api.t.Fatal(err) } - deadline := time.Now().Add(10 * time.Second) + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) for { - probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "dry-run-probe", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} - err = actor.Create(ctx, probe, client.DryRunAll) - if apierrors.IsForbidden(err) { + var object unstructured.Unstructured + err := decoder.Decode(&object.Object) + if errors.Is(err, io.EOF) { break } - if time.Now().After(deadline) { - t.Fatalf("webhook did not engage: %v", err) + if err != nil { + api.t.Fatal(err) + } + if err := api.admin.Create(context.Background(), &object); err != nil { + api.t.Fatal(err) } - time.Sleep(30 * time.Millisecond) - } - var wins atomic.Int32 - var workers sync.WaitGroup - for _, name := range []string{"first", "second", "third"} { - request := registrationRequest(t, device, name) - var capacity metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &capacity) - capacity.UID = "forged-client-uid" - workers.Add(1) - go func() { - defer workers.Done() - if actor.Create(ctx, &capacity) == nil { - wins.Add(1) - } - }() - } - workers.Wait() - if wins.Load() != 1 { - t.Fatalf("wanted one admission, got %d", wins.Load()) - } - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Recorded" || ledger.Entries[0].CapacityUID == "forged-client-uid" { - t.Fatalf("incarnation not bound by real API: %+v %v", ledger, err) - } - var capacity metal.MachineCapacity - if err := actor.Get(ctx, client.ObjectKey{Namespace: "default", Name: ledger.Entries[0].Name}, &capacity); err != nil { - t.Fatal(err) - } - capacity.Spec.AllocationPolicy = "Enabled" - capacity.Spec.CleaningPolicyRef.Name = "invented-policy" - if err := actor.Update(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("direct enabling bypass: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(&capacity), &capacity); err != nil { - t.Fatal(err) - } - capacity.Annotations[DeviceUIDAnnotation] = "copied-other-incarnation" - if err := actor.Update(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("binding annotation bypass: %v", err) - } - if err := actor.Get(ctx, client.ObjectKeyFromObject(&capacity), &capacity); err != nil { - t.Fatal(err) - } - capacity.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionTrue, Reason: "Fabricated", Message: "Must not be accepted", LastTransitionTime: metav1.Now()}} - if err := actor.Status().Update(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("positive readiness bypass: %v", err) - } - if err := actor.Delete(ctx, &capacity); !apierrors.IsForbidden(err) { - t.Fatalf("direct deletion bypass: %v", err) - } - if err := actor.Delete(ctx, device); !apierrors.IsForbidden(err) { - t.Fatalf("Device deletion bypass: %v", err) - } - var namespace corev1.Namespace - if err := actor.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil { - t.Fatal(err) - } - if err := actor.Delete(ctx, &namespace); !apierrors.IsForbidden(err) { - t.Fatalf("inventory namespace deletion bypass: %v", err) - } - var privateNamespace corev1.Namespace - if err := api.Get(ctx, client.ObjectKey{Name: "fleet-system-private"}, &privateNamespace); err != nil { - t.Fatal(err) - } - if err := api.Delete(ctx, &privateNamespace); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatalf("private namespace deletion bypass: %v", err) - } - secret, _, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - if err := api.Delete(ctx, secret); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatalf("ledger deletion bypass: %v", err) } - if err := api.Update(ctx, secret); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatalf("ledger overwrite bypass: %v", err) + api.eventually("Device deletion policy", func() bool { + return apierrors.IsForbidden(api.admin.Delete(context.Background(), probe, client.DryRunAll)) + }) +} + +func (api *liveAPI) eventually(what string, condition func() bool) { + api.t.Helper() + deadline := time.Now().Add(15 * time.Second) + for !condition() { + if time.Now().After(deadline) { + api.t.Fatalf("%s did not engage", what) + } + time.Sleep(50 * time.Millisecond) } - duplicate := device.DeepCopyObject().(*inventory.Device) - duplicate.Name, duplicate.UID, duplicate.ResourceVersion = "other", "", "" - if err := actor.Create(ctx, duplicate); !apierrors.IsForbidden(err) { - t.Fatalf("alias bypass: %v", err) +} + +func (api *liveAPI) exists(object client.Object) bool { + api.t.Helper() + err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(object), object) + if err != nil && !apierrors.IsNotFound(err) { + api.t.Fatal(err) } - denied.Store(true) - request := registrationRequest(t, device, "denied") - var rejected metal.MachineCapacity - _ = json.Unmarshal(request.Object.Raw, &rejected) - rejected.UID = "" - if err := actor.Create(ctx, &rejected); !apierrors.IsForbidden(err) { - t.Fatalf("revoked authorization bypass: %v", err) + return err == nil +} + +// registration builds the exact create the staff portal sends for the +// Device's current incarnation. +func (api *liveAPI) registration(device *inventory.Device) *metal.MachineCapacity { + api.t.Helper() + if err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(device), device); err != nil { + api.t.Fatal(err) + } + return &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName(device.UID), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID), DeviceVersionAnnotation: device.ResourceVersion, OperationAnnotation: "operation-" + device.Name}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} +} + +func requireDenied(t *testing.T, err error, message string) { + t.Helper() + if !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("expected denial containing %q, got %v", message, err) } - denied.Store(false) - pendingDevice := device.DeepCopyObject().(*inventory.Device) - pendingDevice.Name, pendingDevice.UID, pendingDevice.ResourceVersion = "pending-hardware", "", "" - pendingDevice.Spec.Identity.Serial = "pending-serial" - pendingDevice.Spec.Identity.SystemUUID = "22222222-2222-2222-2222-222222222222" - if err := actor.Create(ctx, pendingDevice); err != nil { +} + +func TestRegistrationAgainstLiveDevices(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + server := api.device("server", "default", "serial-1", "11111111-1111-1111-1111-111111111111") + duplicateA := api.device("duplicate-a", "default", "Shared-Serial", "22222222-2222-2222-2222-222222222222") + duplicateB := api.device("duplicate-b", "default", " shared-serial", "33333333-3333-3333-3333-333333333333") + legacyBacked := api.device("legacy-backed", "default", "legacy-serial", "44444444-4444-4444-4444-444444444444") + limitedTarget := api.device("limited-target", "default", "limited-serial", "55555555-5555-5555-5555-555555555555") + // Capacity that existed before registration admission was installed. + legacy := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "legacy-record", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: legacyBacked.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := api.admin.Create(ctx, legacy); err != nil { t.Fatal(err) } - pendingRequest := registrationRequest(t, pendingDevice, "admitted-never-persisted") - var pendingCapacity metal.MachineCapacity - _ = json.Unmarshal(pendingRequest.Object.Raw, &pendingCapacity) - completed := make(chan error, 1) - go func() { completed <- actor.Create(ctx, &pendingCapacity) }() - select { - case <-lateAdmission: - case <-time.After(10 * time.Second): - t.Fatal("admission did not reach pause") - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, privateKey, "expand")); err != nil { - close(release) + // The limited caller may create capacity but may not read Devices. + if err := api.admin.Create(ctx, &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Name: "capacity-creator", Namespace: "default"}, Rules: []rbacv1.PolicyRule{{APIGroups: []string{"metal.datumapis.com"}, Resources: []string{"machinecapacities"}, Verbs: []string{"create"}}}}); err != nil { t.Fatal(err) } - close(release) - if err := <-completed; !apierrors.IsForbidden(err) { - t.Fatal("expected later admission failure", err) - } - if err := handler.Recover(ctx); err != nil { + if err := api.admin.Create(ctx, &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Name: "capacity-creator", Namespace: "default"}, RoleRef: rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "Role", Name: "capacity-creator"}, Subjects: []rbacv1.Subject{{APIGroup: "rbac.authorization.k8s.io", Kind: "User", Name: "limited"}}}); err != nil { t.Fatal(err) } - _, retained, err := handler.Store.Read(ctx) - if err != nil || len(retained.Entries) != 2 { - t.Fatal("lost pending public create", err) - } - for _, entry := range retained.Entries { - if entry.Name == pendingCapacity.Name && entry.Outcome != "Unknown" { - t.Fatal("absent object became free or recorded") + webhook := api.installWebhook() + operator := api.actor("operator", "system:masters") + + t.Run("duplicate alias across two live Devices is denied", func(t *testing.T) { + for _, device := range []*inventory.Device{duplicateA, duplicateB} { + requireDenied(t, operator.Create(ctx, api.registration(device)), "shares recorded hardware identity") } - } - duplicateRequest := registrationRequest(t, pendingDevice, "after-expansion") - var duplicateCapacity metal.MachineCapacity - _ = json.Unmarshal(duplicateRequest.Object.Raw, &duplicateCapacity) - if err := actor.Create(ctx, &duplicateCapacity); !apierrors.IsForbidden(err) { - t.Fatal("expansion orphaned aliases", err) - } - _, route, err := handler.Store.root(ctx) - if err != nil { + }) + t.Run("missing Device is denied", func(t *testing.T) { + missing := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName("9d0c3c2e-1f5b-4f37-9e43-2f5c6a1b7d80"), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: "9d0c3c2e-1f5b-4f37-9e43-2f5c6a1b7d80", DeviceVersionAnnotation: "1", OperationAnnotation: "missing"}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "never-recorded"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + requireDenied(t, operator.Create(ctx, missing), "does not exist") + }) + t.Run("unauthorized caller is denied", func(t *testing.T) { + limited := api.actor("limited") + requireDenied(t, limited.Create(ctx, api.registration(limitedTarget)), "permission on devices is required") + outsider := api.actor("outsider") + if err := outsider.Create(ctx, api.registration(limitedTarget)); !apierrors.IsForbidden(err) { + t.Fatalf("caller without capacity permission: %v", err) + } + if api.exists(api.registration(limitedTarget)) { + t.Fatal("unauthorized registration persisted") + } + }) + t.Run("authored names cannot bypass one capacity per Device", func(t *testing.T) { + authored := api.registration(server) + authored.Name = "authored-name" + requireDenied(t, operator.Create(ctx, authored), "derived from the selected Device UID") + }) + t.Run("legacy capacity already backing the Device is refused", func(t *testing.T) { + requireDenied(t, operator.Create(ctx, api.registration(legacyBacked)), "already backs capacity legacy-record") + }) + t.Run("concurrent registrations of one Device persist once", func(t *testing.T) { + var workers sync.WaitGroup + results := make(chan error, 8) + for range 8 { + capacity := api.registration(server) + workers.Add(1) + go func() { + defer workers.Done() + results <- operator.Create(ctx, capacity) + }() + } + workers.Wait() + close(results) + wins := 0 + for err := range results { + switch { + case err == nil: + wins++ + case apierrors.IsAlreadyExists(err) || (apierrors.IsForbidden(err) && strings.Contains(err.Error(), "already backs capacity")): + default: + t.Fatalf("unexpected registration failure: %v", err) + } + } + if wins != 1 { + t.Fatalf("wanted exactly one persisted registration, got %d", wins) + } + }) + t.Run("a second capacity for the same Device is refused", func(t *testing.T) { + // Admission sees the existing capacity first; if two creates race past + // it, the derived name makes the API server reject the second. + if err := operator.Create(ctx, api.registration(server)); !apierrors.IsAlreadyExists(err) && (!apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "already backs capacity")) { + t.Fatalf("second capacity under the derived name: %v", err) + } + var capacities metal.MachineCapacityList + if err := api.admin.List(ctx, &capacities); err != nil { + t.Fatal(err) + } + bound := 0 + for _, capacity := range capacities.Items { + if capacity.Spec.DeviceRef.Name == server.Name { + bound++ + } + } + if bound != 1 { + t.Fatalf("Device backs %d capacities", bound) + } + }) + t.Run("without the component Device DELETE is allowed and its capacity stays Disabled", func(t *testing.T) { + registered := api.registration(server) + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), registered); err != nil { + t.Fatal(err) + } + if err := api.admin.Delete(ctx, server); err != nil { + t.Fatalf("Device deletion without the component: %v", err) + } + if api.exists(server) { + t.Fatal("Device survived deletion without the component") + } + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), registered); err != nil || registered.Spec.AllocationPolicy != "Disabled" { + t.Fatalf("orphaned capacity is not Disabled: %v", err) + } + registered.Spec.AllocationPolicy = "Enabled" + registered.Spec.CleaningPolicyRef.Name = "invented-policy" + if err := operator.Update(ctx, registered); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "mutation and deletion are disabled") { + t.Fatalf("orphaned capacity was enabled: %v", err) + } + if err := operator.Delete(ctx, registered); !apierrors.IsForbidden(err) { + t.Fatalf("orphaned capacity was deleted: %v", err) + } + replacement := api.device("server", "default", "replacement-serial", "66666666-6666-6666-6666-666666666666") + requireDenied(t, operator.Create(ctx, api.registration(replacement)), "already backs capacity") + }) + + cascade := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "cascade"}} + if err := api.admin.Create(ctx, cascade); err != nil { t.Fatal(err) } - segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: route.Segments[0].Name, Namespace: "fleet-system-private"}} - if err := api.Delete(ctx, segment); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("segment deletion bypass", err) - } - if err := private.Delete(ctx, segment); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("service segment deletion bypass", err) - } - downgrade, _, err := handler.Store.Read(ctx) - if err != nil { + cascaded := api.device("cascaded", "cascade", "cascade-serial", "77777777-7777-7777-7777-777777777777") + sibling := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "sibling", Namespace: "cascade"}} + if err := api.admin.Create(ctx, sibling); err != nil { t.Fatal(err) } - delete(downgrade.Data, "routing.json") - if err := private.Update(ctx, downgrade); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("v2 format downgrade bypass", err) - } - for _, name := range []string{"arbitrary-credential", LedgerName, SegmentPrefix + "mutable"} { - probe := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: "fleet-system-private", Name: name}} - if err := private.Create(ctx, probe); !apierrors.IsInvalid(err) && !apierrors.IsForbidden(err) { - t.Fatal("service create boundary bypass", name, err) + api.installDeletionProtection(duplicateA) + + t.Run("installed component denies Device DELETE for every caller", func(t *testing.T) { + for _, caller := range []client.Client{api.admin, operator} { + if err := caller.Delete(ctx, duplicateA); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "cannot be deleted") { + t.Fatalf("Device deletion: %v", err) + } } - } + if !api.exists(duplicateA) { + t.Fatal("Device removed despite deletion protection") + } + }) + t.Run("deletecollection is denied per Device", func(t *testing.T) { + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("default")); !apierrors.IsForbidden(err) { + t.Fatalf("deletecollection: %v", err) + } + for _, device := range []*inventory.Device{duplicateA, duplicateB, legacyBacked, limitedTarget} { + if !api.exists(device) { + t.Fatalf("deletecollection removed %s", device.Name) + } + } + }) + t.Run("namespace deletion stays Terminating with its Devices", func(t *testing.T) { + if err := api.admin.Delete(ctx, cascade); err != nil { + t.Fatal(err) + } + // envtest runs no namespace controller. Issue the same content + // deletions the controller would: deletecollection, then per item. + if err := api.admin.DeleteAllOf(ctx, &corev1.ConfigMap{}, client.InNamespace("cascade")); err != nil { + t.Fatal(err) + } + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("cascade")); !apierrors.IsForbidden(err) { + t.Fatalf("namespace cascade deletecollection: %v", err) + } + if err := api.admin.Delete(ctx, cascaded); !apierrors.IsForbidden(err) { + t.Fatalf("namespace cascade item deletion: %v", err) + } + if !api.exists(cascaded) || api.exists(sibling) { + t.Fatal("cascade must stop at Devices while other content drains") + } + if !api.exists(cascade) || cascade.DeletionTimestamp.IsZero() { + t.Fatal("namespace must remain Terminating") + } + }) + t.Run("webhook outage blocks only capacity writes", func(t *testing.T) { + webhook.Close() + other := api.device("outage-device", "default", "outage-serial", "88888888-8888-8888-8888-888888888888") + other.Labels = map[string]string{"edited": "true"} + if err := api.admin.Update(ctx, other); err != nil { + t.Fatalf("Device update during outage: %v", err) + } + capacity := api.registration(other) + if err := operator.Create(ctx, capacity); err == nil { + t.Fatal("capacity registration admitted without the webhook") + } + if api.exists(capacity) { + t.Fatal("capacity persisted during outage") + } + }) } diff --git a/internal/registration/fence.go b/internal/registration/fence.go deleted file mode 100644 index 3cb3fa9c..00000000 --- a/internal/registration/fence.go +++ /dev/null @@ -1,75 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "reflect" - "slices" - - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - admissionv1 "k8s.io/api/admissionregistration/v1" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -func requiredFences(projects []string) []admissionv1.ValidatingWebhook { - names, _ := json.Marshal(projects) - projectContext := fmt.Sprintf("has(request.userInfo.extra) && %q in request.userInfo.extra && request.userInfo.extra[%q] == ['Project'] && %q in request.userInfo.extra && request.userInfo.extra[%q] == ['resourcemanager.miloapis.com'] && %q in request.userInfo.extra && size(request.userInfo.extra[%q]) == 1 && request.userInfo.extra[%q][0] != ''", iam.ParentKindExtraKey, iam.ParentKindExtraKey, iam.ParentAPIGroupExtraKey, iam.ParentAPIGroupExtraKey, iam.ParentNameExtraKey, iam.ParentNameExtraKey, iam.ParentNameExtraKey) - protectedContext := fmt.Sprintf("!(%s) || request.userInfo.extra[%q][0] in %s", projectContext, iam.ParentNameExtraKey, names) - namespaced, cluster := admissionv1.NamespacedScope, admissionv1.ClusterScope - writes := []admissionv1.OperationType{admissionv1.Create, admissionv1.Update, admissionv1.Delete} - return []admissionv1.ValidatingWebhook{ - {Name: "registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: writes, Rule: admissionv1.Rule{APIGroups: []string{"metal.datumapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"machinecapacities", "machinecapacities/status"}, Scope: &namespaced}}}}, - {Name: "inventory.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: writes, Rule: admissionv1.Rule{APIGroups: []string{"fleet.datumapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"devices", "devices/status"}, Scope: &namespaced}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-context", Expression: protectedContext}}}, - {Name: "namespace.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: []admissionv1.OperationType{admissionv1.Delete}, Rule: admissionv1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"namespaces"}, Scope: &cluster}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-context", Expression: protectedContext}, {Name: "inventory-namespace", Expression: "!has(request.name) || request.name == '' || request.name == 'default'"}}}, - {Name: "project.registration.fleet.datumapis.com", Rules: []admissionv1.RuleWithOperations{{Operations: []admissionv1.OperationType{admissionv1.Delete}, Rule: admissionv1.Rule{APIGroups: []string{"resourcemanager.miloapis.com"}, APIVersions: []string{"v1alpha1"}, Resources: []string{"projects"}, Scope: &cluster}}}, MatchConditions: []admissionv1.MatchCondition{{Name: "provider-project-name", Expression: "!has(request.name) || request.name == '' || request.name in " + string(names)}}}, - } -} - -func VerifyFence(ctx context.Context, reader client.Reader, projects []string) error { - _, err := VerifiedFenceDigest(ctx, reader, projects) - return err -} - -func VerifiedFenceDigest(ctx context.Context, reader client.Reader, projects []string) (string, error) { - var configuration admissionv1.ValidatingWebhookConfiguration - if err := reader.Get(ctx, client.ObjectKey{Name: "fleet-capacity-registration"}, &configuration); err != nil { - return "", errors.New("project-plane registration admission configuration is unavailable") - } - if err := verifyFenceConfiguration(configuration, projects); err != nil { - return "", err - } - encoded, err := json.Marshal(configuration.Webhooks) - return digest(encoded), err -} - -func verifyFenceConfiguration(configuration admissionv1.ValidatingWebhookConfiguration, projects []string) error { - if len(projects) == 0 || slices.Contains(projects, "") || !slices.IsSorted(projects) || len(slices.Compact(slices.Clone(projects))) != len(projects) { - return errors.New("registration admission requires the exact sorted provider scope") - } - if !configuration.DeletionTimestamp.IsZero() { - return errors.New("registration admission configuration is deleting") - } - required := requiredFences(projects) - if len(configuration.Webhooks) != len(required) { - return errors.New("registration admission requires separate capacity, inventory, namespace and project fences") - } - for _, expected := range required { - index := slices.IndexFunc(configuration.Webhooks, func(webhook admissionv1.ValidatingWebhook) bool { return webhook.Name == expected.Name }) - if index < 0 { - return errors.New("registration admission webhook is missing") - } - webhook := configuration.Webhooks[index] - if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionv1.SideEffectClassNoneOnDryRun || webhook.MatchPolicy == nil || *webhook.MatchPolicy != admissionv1.Equivalent || !slices.Contains(webhook.AdmissionReviewVersions, "v1") || (webhook.NamespaceSelector != nil && (len(webhook.NamespaceSelector.MatchLabels) != 0 || len(webhook.NamespaceSelector.MatchExpressions) != 0)) || (webhook.ObjectSelector != nil && (len(webhook.ObjectSelector.MatchLabels) != 0 || len(webhook.ObjectSelector.MatchExpressions) != 0)) || len(webhook.ClientConfig.CABundle) == 0 { - return errors.New("registration admission must be fail-closed, without label selectors, and have an explicit serving CA") - } - if !reflect.DeepEqual(webhook.Rules, expected.Rules) || !slices.Equal(webhook.MatchConditions, expected.MatchConditions) { - return errors.New("registration admission rules and trusted-context conditions must exactly match the retained provider scope") - } - if !reflect.DeepEqual(webhook.ClientConfig, configuration.Webhooks[0].ClientConfig) { - return errors.New("registration fences must use the same authenticated authority endpoint") - } - } - return nil -} diff --git a/internal/registration/fence_test.go b/internal/registration/fence_test.go deleted file mode 100644 index 6aa89617..00000000 --- a/internal/registration/fence_test.go +++ /dev/null @@ -1,113 +0,0 @@ -package registration - -import ( - "context" - "os" - "testing" - - admissionv1 "k8s.io/api/admissionregistration/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client/fake" - "sigs.k8s.io/yaml" -) - -func TestPackagedProjectAdmissionFence(t *testing.T) { - data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") - if err != nil { - t.Fatal(err) - } - var configured admissionv1.ValidatingWebhookConfiguration - if err := yaml.UnmarshalStrict(data, &configured); err != nil { - t.Fatal(err) - } - for index := range configured.Webhooks { - configured.Webhooks[index].ClientConfig.CABundle = []byte("environment-owned-serving-ca") - } - for _, test := range []struct { - name string - mutate func(*admissionv1.ValidatingWebhookConfiguration) - allowed bool - }{ - {"complete", func(*admissionv1.ValidatingWebhookConfiguration) {}, true}, - {"incomplete deployment", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks = configuration.Webhooks[:1] - }, false}, - {"no serving CA", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].ClientConfig.CABundle = nil - }, false}, - {"fail open", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - policy := admissionv1.Ignore - configuration.Webhooks[0].FailurePolicy = &policy - }, false}, - {"missing Device protection", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].Rules = nil - }, false}, - {"global inventory blast radius", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].MatchConditions = nil - }, false}, - {"broadened inventory rule", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].Rules = append(configuration.Webhooks[0].Rules, configuration.Webhooks[1].Rules...) - }, false}, - {"wrong retained project scope", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].MatchConditions = requiredFences([]string{"different"})[1].MatchConditions - }, false}, - {"namespace name omitted", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[2].MatchConditions = configuration.Webhooks[2].MatchConditions[:1] - }, false}, - {"global project deletion blast radius", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[3].MatchConditions = nil - }, false}, - {"caller label condition", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].MatchConditions[0].Expression = "object.metadata.labels['provider'] == 'datum-cloud'" - }, false}, - {"Device status protection omitted", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[1].Rules[0].Resources = []string{"devices"} - }, false}, - {"inventory fail open", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - policy := admissionv1.Ignore - configuration.Webhooks[1].FailurePolicy = &policy - }, false}, - {"capacity exemption", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].MatchConditions = configuration.Webhooks[1].MatchConditions - }, false}, - {"split authority", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - other := "https://another.invalid/webhook" - configuration.Webhooks[1].ClientConfig.URL = &other - }, false}, - {"caller annotation selector", func(configuration *admissionv1.ValidatingWebhookConfiguration) { - configuration.Webhooks[0].ObjectSelector = &metav1.LabelSelector{MatchLabels: map[string]string{"registration": "true"}} - }, false}, - } { - t.Run(test.name, func(t *testing.T) { - configuration := configured.DeepCopy() - test.mutate(configuration) - scheme := runtime.NewScheme() - if err := admissionv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configuration).Build() - if err := VerifyFence(context.Background(), api, []string{"datum-cloud"}); (err == nil) != test.allowed { - t.Fatalf("unexpected fence result: %v", err) - } - }) - } -} - -func TestIncompleteFenceDeniesRegistrationWithoutReservation(t *testing.T) { - handler, device := fixture(t) - scheme := runtime.NewScheme() - if err := admissionv1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - configuration := &admissionv1.ValidatingWebhookConfiguration{ObjectMeta: metav1.ObjectMeta{Name: "fleet-capacity-registration"}} - api := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configuration).Build() - handler.VerifyFence = func(ctx context.Context) error { return VerifyFence(ctx, api, handler.Store.Projects) } - if handler.Handle(context.Background(), registrationRequest(t, device, "incomplete")).Allowed { - t.Fatal("incomplete admission deployment admitted registration") - } - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil || len(ledger.Entries) != 0 { - t.Fatalf("incomplete fence changed registration state: %+v %v", ledger, err) - } -} diff --git a/internal/registration/ledger.go b/internal/registration/ledger.go deleted file mode 100644 index eec32ac5..00000000 --- a/internal/registration/ledger.go +++ /dev/null @@ -1,106 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "encoding/json" - "errors" - "reflect" - - authenticationv1 "k8s.io/api/authentication/v1" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -const LedgerName = "fleet-capacity-registration-v1" - -var ErrConflict = errors.New("registration conflicts with retained identity or an unknown operation; operator reconciliation is required") - -type Entry struct { - Operation types.UID `json:"operation"` - Actor authenticationv1.UserInfo `json:"actor"` - Project string `json:"project"` - ProjectUID types.UID `json:"projectUID"` - NamespaceUID types.UID `json:"namespaceUID"` - Name string `json:"name"` - CapacityUID types.UID `json:"capacityUID"` - DeviceName string `json:"deviceName"` - DeviceUID types.UID `json:"deviceUID"` - DeviceVersion string `json:"deviceVersion"` - Aliases []string `json:"aliases"` - AssetID string `json:"assetID"` - Input json.RawMessage `json:"input"` - Outcome string `json:"outcome"` -} - -type DeviceFence struct { - Project string `json:"project"` - ProjectUID types.UID `json:"projectUID,omitempty"` - Namespace string `json:"namespace,omitempty"` - NamespaceUID types.UID `json:"namespaceUID,omitempty"` - Name string `json:"name,omitempty"` - UID types.UID `json:"uid"` - Aliases []string `json:"aliases,omitempty"` - Deleted bool `json:"deleted,omitempty"` - Version string `json:"version,omitempty"` -} - -type Ledger struct { - Authority string `json:"authority"` - Projects []string `json:"projects"` - Entries []Entry `json:"entries"` - DeviceFences []DeviceFence `json:"deviceFences"` -} - -type Store struct { - Client client.Client - Namespace string - Authority string - Projects []string - ControlKey ed25519.PublicKey - // AllowInactiveForTests skips the signed activation gate. The zero value - // is gated; production wiring forces it off. - AllowInactiveForTests bool -} - -func (store Store) Read(ctx context.Context) (*corev1.Secret, Ledger, error) { - secret := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { - return nil, Ledger{}, err - } - ledger, _, err := store.readSnapshot(ctx, secret) - if err != nil { - return nil, Ledger{}, err - } - if secret.UID == "" || !secret.DeletionTimestamp.IsZero() || ledger.Authority != store.Authority || !reflect.DeepEqual(ledger.Projects, store.Projects) { - return nil, Ledger{}, errors.New("registration ledger lifetime or configured scope is unavailable") - } - return secret, ledger, nil -} - -func (store Store) Write(ctx context.Context, secret *corev1.Secret, ledger Ledger) error { - if _, exists := secret.Data["routing.json"]; exists { - return store.writeSnapshot(ctx, secret, ledger) - } - encoded, err := json.Marshal(ledger) - if err != nil { - return err - } - if len(encoded) > TailBudget { - return errors.New("registration ledger is full; sign an expand control request to seal it losslessly, see docs/development/registration-storage-rollout.md; reservations were not released") - } - secret.Data["ledger.json"] = encoded - return store.Client.Update(ctx, secret) -} - -func overlaps(left, right []string) bool { - for _, first := range left { - for _, second := range right { - if first == second { - return true - } - } - } - return false -} diff --git a/internal/registration/manifest_test.go b/internal/registration/manifest_test.go new file mode 100644 index 00000000..8c981b23 --- /dev/null +++ b/internal/registration/manifest_test.go @@ -0,0 +1,40 @@ +package registration + +import ( + "os" + "slices" + "testing" + + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + "sigs.k8s.io/yaml" +) + +// The packaged webhook is the only gate on capacity writes, so it must stay +// fail-closed over every capacity write and must not reach anything else. +func TestPackagedWebhookFencesOnlyCapacityWrites(t *testing.T) { + data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") + if err != nil { + t.Fatal(err) + } + var configuration admissionregistrationv1.ValidatingWebhookConfiguration + if err := yaml.UnmarshalStrict(data, &configuration); err != nil { + t.Fatal(err) + } + if len(configuration.Webhooks) != 1 { + t.Fatalf("want one capacity webhook, got %d", len(configuration.Webhooks)) + } + webhook := configuration.Webhooks[0] + if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionregistrationv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionregistrationv1.SideEffectClassNone || webhook.MatchPolicy == nil || *webhook.MatchPolicy != admissionregistrationv1.Equivalent { + t.Fatal("capacity webhook must fail closed, be side-effect free and match equivalent versions") + } + if webhook.NamespaceSelector != nil || webhook.ObjectSelector != nil || len(webhook.MatchConditions) != 0 { + t.Fatal("capacity webhook must not be narrowed by selectors or conditions") + } + if len(webhook.Rules) != 1 { + t.Fatal("capacity webhook must have exactly one rule") + } + rule := webhook.Rules[0] + if !slices.Equal(rule.APIGroups, []string{"metal.datumapis.com"}) || !slices.Equal(rule.Resources, []string{"machinecapacities", "machinecapacities/status"}) || !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete}) { + t.Fatalf("capacity webhook rule drifted: %+v", rule) + } +} diff --git a/internal/registration/namespace_lifetime_test.go b/internal/registration/namespace_lifetime_test.go deleted file mode 100644 index ff2270e0..00000000 --- a/internal/registration/namespace_lifetime_test.go +++ /dev/null @@ -1,167 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "testing" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - admissionv1 "k8s.io/api/admission/v1" - authenticationv1 "k8s.io/api/authentication/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" -) - -// terminatingDevice creates a Device in a provider-project namespace other -// than default, records its fence while the namespace is live, and then -// deletes the namespace while a finalizer still holds it in Terminating. -func terminatingDevice(t *testing.T, handler *Handler, name, uuid string) (Project, *inventory.Device) { - t.Helper() - ctx := context.Background() - project, _ := handler.Resolve(ctx, "provider") - namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "decommissioned-" + name, UID: types.UID("namespace-" + name), Finalizers: []string{"synthetic.example/hold"}}} - if err := project.Client.Create(ctx, namespace); err != nil { - t.Fatal(err) - } - device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace.Name, UID: types.UID("device-" + name)}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "SERIAL-" + name, SystemUUID: uuid, Model: "test"}}} - if err := project.Client.Create(ctx, device); err != nil { - t.Fatal(err) - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Create, nil, device)); !response.Allowed { - t.Fatalf("live namespace Device create denied: %s", response.Result.Message) - } - if err := project.Client.Delete(ctx, namespace); err != nil { - t.Fatal(err) - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err != nil || namespace.DeletionTimestamp.IsZero() { - t.Fatalf("namespace is not terminating: %v", err) - } - return project, device -} - -func deviceRequest(t *testing.T, operation admissionv1.Operation, old, current *inventory.Device) admission.Request { - t.Helper() - request := admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{UID: types.UID("device-request-" + string(operation)), Operation: operation, Resource: metav1.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"}, UserInfo: authenticationv1.UserInfo{Username: "operator", UID: "actor-1", Extra: map[string]authenticationv1.ExtraValue{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}}}} - for _, pair := range []struct { - device *inventory.Device - raw *runtime.RawExtension - }{{old, &request.OldObject}, {current, &request.Object}} { - if pair.device == nil { - continue - } - encoded, err := json.Marshal(pair.device) - if err != nil { - t.Fatal(err) - } - pair.raw.Raw = encoded - request.Name, request.Namespace = pair.device.Name, pair.device.Namespace - } - return request -} - -func retainedFence(t *testing.T, handler *Handler, uid types.UID) DeviceFence { - t.Helper() - _, ledger, err := handler.Store.Read(context.Background()) - if err != nil { - t.Fatal(err) - } - var found []DeviceFence - for _, fence := range ledger.DeviceFences { - if fence.UID == uid { - found = append(found, fence) - } - } - if len(found) != 1 { - t.Fatalf("expected one retained fence for %s: %+v", uid, ledger.DeviceFences) - } - return found[0] -} - -func TestDeviceDeleteInTerminatingNamespaceRetainsTombstone(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - _, device := terminatingDevice(t, handler, "retired", "22222222-2222-2222-2222-222222222222") - created := retainedFence(t, handler, device.UID) - if created.NamespaceUID == "" || len(created.Aliases) == 0 { - t.Fatalf("create did not record namespace lifetime and aliases: %+v", created) - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, device, nil)); !response.Allowed { - t.Fatalf("Device delete in a terminating namespace was denied, so the namespace cannot finish terminating: %s", response.Result.Message) - } - tombstone := retainedFence(t, handler, device.UID) - if !tombstone.Deleted || tombstone.NamespaceUID != created.NamespaceUID || tombstone.Version != "" || !preservesReservations(Ledger{DeviceFences: []DeviceFence{created}}, Ledger{DeviceFences: []DeviceFence{tombstone}}) { - t.Fatalf("tombstone lost retained lifetime: before %+v after %+v", created, tombstone) - } - recreated := device.DeepCopyObject().(*inventory.Device) - recreated.Namespace, recreated.UID = "default", "recreated" - if handler.Handle(ctx, deviceRequest(t, admissionv1.Create, nil, recreated)).Allowed { - t.Fatal("deleted hardware aliases were released by the terminating namespace path") - } -} - -func TestDeviceDeleteAfterNamespaceRemovalUsesRecordedLifetime(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - project, device := terminatingDevice(t, handler, "removed", "33333333-3333-3333-3333-333333333333") - created := retainedFence(t, handler, device.UID) - namespace := &corev1.Namespace{} - if err := project.Client.Get(ctx, client.ObjectKey{Name: device.Namespace}, namespace); err != nil { - t.Fatal(err) - } - namespace.Finalizers = nil - if err := project.Client.Update(ctx, namespace); err != nil { - t.Fatal(err) - } - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(namespace), namespace); err == nil { - t.Fatal("namespace was not removed") - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, device, nil)); !response.Allowed { - t.Fatalf("Device delete after namespace removal was denied: %s", response.Result.Message) - } - tombstone := retainedFence(t, handler, device.UID) - if !tombstone.Deleted || tombstone.NamespaceUID != created.NamespaceUID || !preservesReservations(Ledger{DeviceFences: []DeviceFence{created}}, Ledger{DeviceFences: []DeviceFence{tombstone}}) { - t.Fatalf("tombstone did not keep the recorded namespace lifetime: before %+v after %+v", created, tombstone) - } -} - -func TestDeviceFinalizerRemovalInTerminatingNamespaceRetainsTombstone(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - project, device := terminatingDevice(t, handler, "finalized", "44444444-4444-4444-4444-444444444444") - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - device.Finalizers = []string{"synthetic.example/drain"} - if err := project.Client.Update(ctx, device); err != nil { - t.Fatal(err) - } - if err := project.Client.Delete(ctx, device); err != nil { - t.Fatal(err) - } - deleting := &inventory.Device{} - if err := project.Client.Get(ctx, client.ObjectKeyFromObject(device), deleting); err != nil || deleting.DeletionTimestamp.IsZero() { - t.Fatalf("Device is not deleting: %v", err) - } - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Delete, deleting, nil)); !response.Allowed { - t.Fatalf("Device delete in a terminating namespace was denied: %s", response.Result.Message) - } - released := deleting.DeepCopyObject().(*inventory.Device) - released.Finalizers = nil - if response := handler.Handle(ctx, deviceRequest(t, admissionv1.Update, deleting, released)); !response.Allowed { - t.Fatalf("finalizer removal in a terminating namespace was denied: %s", response.Result.Message) - } - tombstone := retainedFence(t, handler, device.UID) - if !tombstone.Deleted || tombstone.NamespaceUID == "" || len(tombstone.Aliases) == 0 { - t.Fatalf("finalizer removal lost the tombstone: %+v", tombstone) - } - edited := deleting.DeepCopyObject().(*inventory.Device) - edited.Finalizers, edited.Labels = nil, map[string]string{"edited": "true"} - if handler.Handle(ctx, deviceRequest(t, admissionv1.Update, deleting, edited)).Allowed { - t.Fatal("a non-finalizer edit was admitted without a live namespace") - } -} diff --git a/internal/registration/runtime.go b/internal/registration/runtime.go index 26ce2bff..f92434bf 100644 --- a/internal/registration/runtime.go +++ b/internal/registration/runtime.go @@ -2,28 +2,24 @@ package registration import ( "context" - "encoding/json" "errors" "fmt" - "reflect" - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - metal "go.datum.net/fleet/internal/api/v1alpha1" "go.datum.net/fleet/internal/manager" "go.datum.net/fleet/internal/projectdiscovery" authenticationv1 "k8s.io/api/authentication/v1" authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/rest" "sigs.k8s.io/controller-runtime/pkg/client" ) -func NewHandler(store Store, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { - store.AllowInactiveForTests = false - return &Handler{Store: store, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, root, store.Projects) }, Resolve: func(ctx context.Context, name string) (Project, error) { - identity, err := manager.ResolveProjectIdentity(ctx, root, store.Authority, name) +// NewHandler wires the handler to Milo. The root client resolves Project +// lifetimes; the template is re-addressed to each provider project's control +// plane for uncached Device and capacity reads and SubjectAccessReviews. +func NewHandler(authority string, projects []string, root client.Client, template *rest.Config, scheme *runtime.Scheme) *Handler { + return &Handler{Projects: projects, Resolve: func(ctx context.Context, name string) (Project, error) { + identity, err := manager.ResolveProjectIdentity(ctx, root, authority, name) if err != nil { return Project{}, err } @@ -33,11 +29,12 @@ func NewHandler(store Store, root client.Client, template *rest.Config, scheme * } api, err := client.New(config, client.Options{Scheme: scheme}) return Project{Identity: identity, Client: api}, err - }, Authorize: Authorize, FenceDigest: func(ctx context.Context) (string, error) { - return VerifiedFenceDigest(ctx, root, store.Projects) - }} + }, Authorize: Authorize} } +// Authorize evaluates the caller's own permission with a SubjectAccessReview +// carrying the caller's username, UID, groups and extras. The service's +// credentials evaluate the review; they never stand in for the caller. func Authorize(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { verb := "get" if resource == "machinecapacities" { @@ -47,7 +44,7 @@ func Authorize(ctx context.Context, project Project, actor authenticationv1.User for key, values := range actor.Extra { extra[key] = authorizationv1.ExtraValue(append([]string(nil), values...)) } - review := &authorizationv1.SubjectAccessReview{Spec: authorizationv1.SubjectAccessReviewSpec{User: actor.Username, UID: actor.UID, Groups: append([]string(nil), actor.Groups...), Extra: extra, ResourceAttributes: &authorizationv1.ResourceAttributes{Group: group, Resource: resource, Version: "v1alpha1", Namespace: "default", Verb: verb, Name: name}}} + review := &authorizationv1.SubjectAccessReview{Spec: authorizationv1.SubjectAccessReviewSpec{User: actor.Username, UID: actor.UID, Groups: append([]string(nil), actor.Groups...), Extra: extra, ResourceAttributes: &authorizationv1.ResourceAttributes{Group: group, Resource: resource, Version: "v1alpha1", Namespace: InventoryNamespace, Verb: verb, Name: name}}} if err := project.Client.Create(ctx, review); err != nil { return errors.New("current registration authorization is unavailable") } @@ -56,62 +53,3 @@ func Authorize(ctx context.Context, project Project, actor authenticationv1.User } return nil } - -func (handler *Handler) Recover(ctx context.Context) error { - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - return err - } - changed := false - var failures error - for index := range ledger.Entries { - entry := &ledger.Entries[index] - outcome, err := handler.observe(ctx, *entry) - failures = errors.Join(failures, err) - if entry.Outcome != outcome { - entry.Outcome = outcome - changed = true - } - } - if changed { - failures = errors.Join(failures, handler.Store.Write(ctx, secret, ledger)) - } - return failures -} - -func (handler *Handler) observe(ctx context.Context, entry Entry) (string, error) { - project, err := handler.Resolve(ctx, entry.Project) - if err != nil { - return "Unknown", err - } - if project.Identity.UID != entry.ProjectUID { - return "LifetimeLost", nil - } - var namespace corev1.Namespace - if err := project.Client.Get(ctx, client.ObjectKey{Name: "default"}, &namespace); err != nil && !apierrors.IsNotFound(err) { - return "Unknown", err - } - var device inventory.Device - if err := project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: entry.DeviceName}, &device); err != nil && !apierrors.IsNotFound(err) { - return "Unknown", err - } - if namespace.UID != entry.NamespaceUID || !namespace.DeletionTimestamp.IsZero() || device.UID != entry.DeviceUID || !device.DeletionTimestamp.IsZero() || !reflect.DeepEqual(aliases(&device), entry.Aliases) { - return "LifetimeLost", nil - } - var current metal.MachineCapacity - err = project.Client.Get(ctx, client.ObjectKey{Namespace: "default", Name: entry.Name}, ¤t) - if apierrors.IsNotFound(err) { - return "Unknown", nil - } - if err != nil { - return "Unknown", err - } - var input metal.MachineCapacity - if err := json.Unmarshal(entry.Input, &input); err != nil { - return "Unknown", err - } - if current.UID != entry.CapacityUID || !reflect.DeepEqual(current.Spec, input.Spec) || !reflect.DeepEqual(current.Annotations, input.Annotations) || !reflect.DeepEqual(current.Labels, input.Labels) || !current.DeletionTimestamp.IsZero() { - return "IncarnationConflict", nil - } - return "Recorded", nil -} diff --git a/internal/registration/segments.go b/internal/registration/segments.go deleted file mode 100644 index 710c85fe..00000000 --- a/internal/registration/segments.go +++ /dev/null @@ -1,269 +0,0 @@ -package registration - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "reflect" - "slices" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/controller-runtime/pkg/client" -) - -const ( - TailBudget = 650000 - SegmentBudget = 750000 - MaxSegments = 16 - RootBudget = 850000 - SegmentPrefix = "fleet-registration-segment-" -) - -var ErrGrowthStopped = errors.New("registration growth stopped; signed lossless expansion required, reservations remain retained") - -// ErrSegmentsExhausted is the terminal growth stop: every sealed segment is in -// use, so expansion itself is refused. It still matches ErrGrowthStopped for -// callers that only distinguish stopped growth. -var ErrSegmentsExhausted error = segmentsExhausted{} - -type segmentsExhausted struct{} - -func (segmentsExhausted) Error() string { - return fmt.Sprintf("registration segments exhausted (%d of %d sealed); expansion is refused and a reviewed storage migration is required, see docs/development/registration-storage-rollout.md; reservations remain retained, do not raise caps or delete records", MaxSegments, MaxSegments) -} - -func (segmentsExhausted) Is(target error) bool { return target == ErrGrowthStopped } - -type Segment struct { - Name string `json:"name"` - UID types.UID `json:"uid"` - Digest string `json:"digest"` -} - -type Routing struct { - Version int `json:"version"` - Epoch uint64 `json:"epoch"` - RootUID types.UID `json:"rootUID"` - Segments []Segment `json:"segments"` - Pending *SignedControl `json:"pending,omitempty"` - Activation *SignedControl `json:"activation,omitempty"` - ActivationHistory []SignedControl `json:"activationHistory,omitempty"` -} - -func digest(data []byte) string { - value := sha256.Sum256(data) - return hex.EncodeToString(value[:]) -} - -func decodeRouting(secret *corev1.Secret) (Routing, error) { - var route Routing - if err := json.Unmarshal(secret.Data["routing.json"], &route); err != nil { - return route, err - } - if route.Version != 2 || route.RootUID != secret.UID || route.Epoch != uint64(len(route.Segments)) || len(route.Segments) > MaxSegments || len(route.ActivationHistory) > 7 { - return route, errors.New("invalid registration routing identity or epoch") - } - return route, nil -} - -func (store Store) readSnapshot(ctx context.Context, secret *corev1.Secret) (Ledger, Ledger, error) { - base := Ledger{Authority: store.Authority, Projects: store.Projects} - key := "ledger.json" - if _, exists := secret.Data["routing.json"]; exists { - route, err := decodeRouting(secret) - if err != nil { - return Ledger{}, Ledger{}, err - } - key = "tail.json" - for index, reference := range route.Segments { - if reference.Name != segmentName(secret.UID, uint64(index)) || reference.UID == "" { - return Ledger{}, Ledger{}, errors.New("invalid segment identity") - } - segment := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: reference.Name}, segment); err != nil { - return Ledger{}, Ledger{}, err - } - if segment.UID != reference.UID || segment.Immutable == nil || !*segment.Immutable || !segment.DeletionTimestamp.IsZero() || digest(segment.Data["ledger.json"]) != reference.Digest { - return Ledger{}, Ledger{}, errors.New("segment lifetime or integrity unavailable") - } - var delta Ledger - if err := json.Unmarshal(segment.Data["ledger.json"], &delta); err != nil { - return Ledger{}, Ledger{}, err - } - if delta.Authority != store.Authority || !reflect.DeepEqual(delta.Projects, store.Projects) { - return Ledger{}, Ledger{}, errors.New("segment scope mismatch") - } - base = overlay(base, delta) - } - } - var tail Ledger - if err := json.Unmarshal(secret.Data[key], &tail); err != nil { - return Ledger{}, Ledger{}, err - } - if tail.Authority != store.Authority || !reflect.DeepEqual(tail.Projects, store.Projects) { - return Ledger{}, Ledger{}, errors.New("ledger scope mismatch") - } - return overlay(base, tail), base, nil -} - -func fenceKey(fence DeviceFence) string { - encoded, _ := json.Marshal([]string{fence.Project, string(fence.UID)}) - return string(encoded) -} - -func overlay(base, tail Ledger) Ledger { - result := Ledger{Authority: base.Authority, Projects: base.Projects} - entries := map[types.UID]bool{} - fences := map[string]bool{} - for _, entry := range tail.Entries { - entries[entry.Operation] = true - } - for _, fence := range tail.DeviceFences { - fences[fenceKey(fence)] = true - } - for _, entry := range base.Entries { - if !entries[entry.Operation] { - result.Entries = append(result.Entries, entry) - } - } - for _, fence := range base.DeviceFences { - if !fences[fenceKey(fence)] { - result.DeviceFences = append(result.DeviceFences, fence) - } - } - result.Entries = append(result.Entries, tail.Entries...) - result.DeviceFences = append(result.DeviceFences, tail.DeviceFences...) - return result -} - -func deltaFrom(base, current Ledger) Ledger { - delta := Ledger{Authority: current.Authority, Projects: current.Projects} - baseEntries := map[types.UID][]Entry{} - currentEntries := map[types.UID][]Entry{} - baseFences := map[string][]DeviceFence{} - currentFences := map[string][]DeviceFence{} - for _, entry := range base.Entries { - baseEntries[entry.Operation] = append(baseEntries[entry.Operation], entry) - } - for _, entry := range current.Entries { - currentEntries[entry.Operation] = append(currentEntries[entry.Operation], entry) - } - for _, fence := range base.DeviceFences { - baseFences[fenceKey(fence)] = append(baseFences[fenceKey(fence)], fence) - } - for _, fence := range current.DeviceFences { - currentFences[fenceKey(fence)] = append(currentFences[fenceKey(fence)], fence) - } - for _, entry := range current.Entries { - if !reflect.DeepEqual(baseEntries[entry.Operation], currentEntries[entry.Operation]) { - delta.Entries = append(delta.Entries, entry) - } - } - for _, fence := range current.DeviceFences { - if !reflect.DeepEqual(baseFences[fenceKey(fence)], currentFences[fenceKey(fence)]) { - delta.DeviceFences = append(delta.DeviceFences, fence) - } - } - return delta -} - -func preservesReservations(before, after Ledger) bool { - if before.Authority != after.Authority || !reflect.DeepEqual(before.Projects, after.Projects) { - return false - } - entries := map[types.UID][]Entry{} - fences := map[string][]DeviceFence{} - for _, entry := range after.Entries { - entries[entry.Operation] = append(entries[entry.Operation], entry) - } - for _, fence := range after.DeviceFences { - fences[fenceKey(fence)] = append(fences[fenceKey(fence)], fence) - } - for _, previous := range before.Entries { - found := false - for _, next := range entries[previous.Operation] { - next.Outcome = previous.Outcome - if reflect.DeepEqual(previous, next) { - found = true - break - } - } - if !found { - return false - } - } - for _, previous := range before.DeviceFences { - found := false - for _, next := range fences[fenceKey(previous)] { - if fenceKey(previous) != fenceKey(next) || (previous.Deleted && !next.Deleted) { - continue - } - if previous.ProjectUID != "" && previous.ProjectUID != next.ProjectUID { - continue - } - if previous.NamespaceUID != "" && previous.NamespaceUID != next.NamespaceUID { - continue - } - if previous.Name != "" && (previous.Name != next.Name || previous.Namespace != next.Namespace) { - continue - } - if slices.ContainsFunc(previous.Aliases, func(alias string) bool { return !slices.Contains(next.Aliases, alias) }) { - continue - } - found = true - } - if !found { - return false - } - } - return true -} - -func (store Store) writeSnapshot(ctx context.Context, secret *corev1.Secret, current Ledger) error { - route, err := decodeRouting(secret) - if err != nil { - return err - } - if route.Pending != nil { - return errors.New("registration expansion is fenced") - } - previous, base, err := store.readSnapshot(ctx, secret) - if err != nil { - return err - } - if !preservesReservations(previous, current) { - return errors.New("registration write would discard retained authority") - } - encoded, err := json.Marshal(deltaFrom(base, current)) - if err != nil { - return err - } - if len(encoded) > TailBudget { - if len(route.Segments) >= MaxSegments { - return ErrSegmentsExhausted - } - return ErrGrowthStopped - } - updated := secret.DeepCopy() - updated.Data["tail.json"] = encoded - return store.updateRoot(ctx, updated) -} - -func (store Store) updateRoot(ctx context.Context, secret *corev1.Secret) error { - size := 0 - for key, value := range secret.Data { - size += len(key) + len(value) - } - if size > RootBudget { - return ErrGrowthStopped - } - return store.Client.Update(ctx, secret) -} - -func segmentName(uid types.UID, epoch uint64) string { - return fmt.Sprintf("%s%s-%02d", SegmentPrefix, digest([]byte(uid))[:24], epoch) -} diff --git a/internal/registration/segments_envtest_test.go b/internal/registration/segments_envtest_test.go deleted file mode 100644 index a5eb8168..00000000 --- a/internal/registration/segments_envtest_test.go +++ /dev/null @@ -1,382 +0,0 @@ -package registration - -import ( - "context" - "crypto/ed25519" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" - "fmt" - "os" - "os/exec" - "path/filepath" - "reflect" - "strings" - "sync" - "testing" - - corev1 "k8s.io/api/core/v1" - rbacv1 "k8s.io/api/rbac/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" - "k8s.io/client-go/tools/clientcmd" - clientcmdapi "k8s.io/client-go/tools/clientcmd/api" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" -) - -type faultClient struct { - client.Client - createAfter bool - createBefore bool - updateAt int - updates int - updateAfter bool - crash bool -} - -func (fault *faultClient) fail() error { - if fault.crash { - os.Exit(23) - } - return context.DeadlineExceeded -} - -func (fault *faultClient) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { - if fault.createBefore { - return fault.fail() - } - if err := fault.Client.Create(ctx, object, options...); err != nil { - return err - } - if fault.createAfter { - return fault.fail() - } - return nil -} - -func (fault *faultClient) Update(ctx context.Context, object client.Object, options ...client.UpdateOption) error { - fault.updates++ - if fault.updates == fault.updateAt && !fault.updateAfter { - return fault.fail() - } - if err := fault.Client.Update(ctx, object, options...); err != nil { - return err - } - if fault.updates == fault.updateAt && fault.updateAfter { - return fault.fail() - } - return nil -} - -func TestRegistrationExpansionWorker(t *testing.T) { - configPath := os.Getenv("FLEET_TEST_CONFIG") - if configPath == "" { - return - } - config, err := clientcmd.BuildConfigFromFlags("", configPath) - if err != nil { - t.Fatal(err) - } - scheme := runtime.NewScheme() - _ = corev1.AddToScheme(scheme) - _ = rbacv1.AddToScheme(scheme) - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - encoded, err := os.ReadFile(os.Getenv("FLEET_TEST_PUBLIC")) - if err != nil { - t.Fatal(err) - } - public, err := ParseControlKey(encoded) - if err != nil { - t.Fatal(err) - } - store := Store{Client: api, Namespace: os.Getenv("FLEET_TEST_NAMESPACE"), Authority: "milo", Projects: []string{"provider"}, ControlKey: public} - fault := &faultClient{Client: api, crash: true} - switch os.Getenv("FLEET_TEST_CRASH") { - case "freeze": - fault.updateAt, fault.updateAfter = 1, true - case "segment-before": - fault.createBefore = true - case "segment-after": - fault.createAfter = true - case "switch-before": - fault.updateAt = 2 - case "switch-after": - fault.updateAt, fault.updateAfter = 2, true - default: - if err := store.ResumeExpansion(context.Background()); err != nil { - t.Fatal(err) - } - return - } - store.Client = fault - encoded, err = os.ReadFile(os.Getenv("FLEET_TEST_REQUEST")) - if err != nil { - t.Fatal(err) - } - control, err := ParseControl(encoded) - if err != nil { - t.Fatal(err) - } - handler := &Handler{Store: store} - if err := handler.ApplyControl(context.Background(), control); err != nil { - t.Fatal(err) - } - t.Fatal("fault boundary was not reached") -} - -func TestRealLosslessExpansionAndProcessRecovery(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - environment := &envtest.Environment{} - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - _ = corev1.AddToScheme(scheme) - _ = rbacv1.AddToScheme(scheme) - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - ctx := context.Background() - newHandler := func(t *testing.T, namespace string) (*Handler, ed25519.PrivateKey) { - handler, _ := fixture(t) - secret, ledger, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - ledger.Entries = []Entry{{Operation: "admitted-not-persisted", Project: "provider", ProjectUID: "project-1", NamespaceUID: "namespace-1", CapacityUID: "public-uid", DeviceUID: "device-1", DeviceVersion: "v1", Aliases: []string{"uuid:reserved"}, Input: json.RawMessage(`{"spec":{"allocationPolicy":"Disabled","reclaimPolicy":"Retain"}}`), Outcome: "Unknown"}} - ledger.DeviceFences = []DeviceFence{{Project: "provider", UID: "legacy", Version: "old", Aliases: []string{"legacy-alias"}}, {Project: "provider", UID: "legacy", Version: "pending"}, {Project: "provider", UID: "deleted", Deleted: true, Aliases: []string{"never-release"}}} - secret.Data["ledger.json"], _ = json.Marshal(ledger) - secret.Namespace, secret.UID, secret.ResourceVersion = namespace, "", "" - if err := api.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: namespace}}); err != nil { - t.Fatal(err) - } - if err := api.Create(ctx, secret); err != nil { - t.Fatal(err) - } - handler.Store.Client, handler.Store.Namespace = api, namespace - return handler, controlFixture(t, handler) - } - kubeconfig := clientcmdapi.Config{Clusters: map[string]*clientcmdapi.Cluster{"test": {Server: config.Host, CertificateAuthorityData: config.CAData}}, AuthInfos: map[string]*clientcmdapi.AuthInfo{"test": {ClientCertificateData: config.CertData, ClientKeyData: config.KeyData}}, Contexts: map[string]*clientcmdapi.Context{"test": {Cluster: "test", AuthInfo: "test"}}, CurrentContext: "test"} - kubeBytes, err := clientcmd.Write(kubeconfig) - if err != nil { - t.Fatal(err) - } - kubePath := filepath.Join(t.TempDir(), "config") - if err := os.WriteFile(kubePath, kubeBytes, 0600); err != nil { - t.Fatal(err) - } - for _, boundary := range []string{"freeze", "segment-before", "segment-after", "switch-before", "switch-after"} { - t.Run(boundary, func(t *testing.T) { - handler, key := newHandler(t, boundary) - stale, before, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - control := controlFor(t, handler, key, "expand") - encoded, _ := json.Marshal(control) - requestPath := filepath.Join(t.TempDir(), "request") - if err := os.WriteFile(requestPath, encoded, 0600); err != nil { - t.Fatal(err) - } - publicDER, _ := x509.MarshalPKIXPublicKey(handler.Store.ControlKey) - publicPath := filepath.Join(t.TempDir(), "public") - if err := os.WriteFile(publicPath, pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: publicDER}), 0600); err != nil { - t.Fatal(err) - } - runWorker := func(crash string) error { - command := exec.Command(os.Args[0], "-test.run=^TestRegistrationExpansionWorker$") - command.Env = append(os.Environ(), "FLEET_TEST_CONFIG="+kubePath, "FLEET_TEST_NAMESPACE="+handler.Store.Namespace, "FLEET_TEST_PUBLIC="+publicPath, "FLEET_TEST_REQUEST="+requestPath, "FLEET_TEST_CRASH="+crash) - output, err := command.CombinedOutput() - if err != nil && crash == "" { - t.Log(string(output)) - } - return err - } - var exit *exec.ExitError - if err := runWorker(boundary); !errors.As(err, &exit) || exit.ExitCode() != 23 { - t.Fatalf("expected injected process crash: %v", err) - } - if handler.Store.Write(ctx, stale, before) == nil { - t.Fatal("pre-freeze writer committed") - } - if err := runWorker(""); err != nil { - t.Fatal("restart", err) - } - _, after, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(before, after) { - t.Fatalf("restart lost reservations: %v\n%+v", err, after) - } - _, route, err := handler.Store.root(ctx) - if err != nil || route.Pending != nil || route.Epoch != 1 || len(route.Segments) != 1 { - t.Fatalf("unfinished expansion: %+v %v", route, err) - } - var segments corev1.SecretList - if err := api.List(ctx, &segments, client.InNamespace(handler.Store.Namespace)); err != nil || len(segments.Items) != 2 { - t.Fatalf("orphan segments: %d %v", len(segments.Items), err) - } - }) - } - t.Run("full-legacy-sealing", func(t *testing.T) { - handler, key := newHandler(t, "full-legacy") - secret, before, err := handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - before.DeviceFences = append(before.DeviceFences, DeviceFence{Project: "provider", UID: "large", Aliases: []string{""}}) - encoded, _ := json.Marshal(before) - before.DeviceFences[len(before.DeviceFences)-1].Aliases[0] = strings.Repeat("x", SegmentBudget-len(encoded)) - secret.Data["ledger.json"], _ = json.Marshal(before) - if err := api.Update(ctx, secret); err != nil { - t.Fatal(err) - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { - t.Fatal(err) - } - _, after, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(before, after) { - t.Fatal("full legacy data lost", err) - } - status, err := handler.Status(ctx) - if err != nil || status.HeadroomBytes < TailBudget-1000 || status.Epoch != 1 || status.ActivationVerified { - t.Fatalf("bad expanded bootstrap status: %+v %v", status, err) - } - }) - t.Run("multi-replica-and-growth", func(t *testing.T) { - handler, key := newHandler(t, "replicas") - _, before, _ := handler.Store.Read(ctx) - control := controlFor(t, handler, key, "expand") - var workers sync.WaitGroup - for range 8 { - workers.Add(1) - go func() { defer workers.Done(); replica := *handler; _ = replica.ApplyControl(ctx, control) }() - } - workers.Wait() - if err := handler.Store.ResumeExpansion(ctx); err != nil { - t.Fatal(err) - } - if err := handler.ApplyControl(ctx, control); err != nil { - t.Fatal("lost completion response cannot be reconciled", err) - } - secret, after, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(before, after) { - t.Fatal("concurrent migration lost history", err) - } - for attempt := 1; attempt < MaxSegments; attempt++ { - after.DeviceFences = append(after.DeviceFences, DeviceFence{Project: "provider", UID: types.UID(fmt.Sprint("new-", attempt)), Aliases: []string{strings.Repeat("a", TailBudget-1000)}}) - if err := handler.Store.Write(ctx, secret, after); err != nil { - t.Fatal(err) - } - secret, after, _ = handler.Store.Read(ctx) - tooLarge := after - tooLarge.DeviceFences = append(append([]DeviceFence(nil), after.DeviceFences...), DeviceFence{Project: "provider", UID: "oversize", Aliases: []string{strings.Repeat("b", 2000)}}) - if !errors.Is(handler.Store.Write(ctx, secret, tooLarge), ErrGrowthStopped) { - t.Fatal("tail headroom not enforced") - } - if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { - t.Fatal(err) - } - secret, after, err = handler.Store.Read(ctx) - if err != nil { - t.Fatal(err) - } - } - if !errors.Is(handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")), ErrGrowthStopped) { - t.Fatal("unbounded expansion") - } - if after.Entries[0].Outcome != "Unknown" || len(after.DeviceFences) != len(before.DeviceFences)+MaxSegments-1 { - t.Fatal("growth changed custody") - } - _, route, _ := handler.Store.root(ctx) - segment := &corev1.Secret{} - if err := api.Get(ctx, client.ObjectKey{Namespace: handler.Store.Namespace, Name: route.Segments[0].Name}, segment); err != nil { - t.Fatal(err) - } - segment.Data["ledger.json"] = []byte("{}") - if err := api.Update(ctx, segment); !apierrors.IsInvalid(err) { - t.Fatal("segment mutable", err) - } - if err := api.Delete(ctx, segment); err != nil { - t.Fatal(err) - } - if _, _, err := handler.Store.Read(ctx); err == nil { - t.Fatal("missing segment treated as free") - } - segment.UID, segment.ResourceVersion = "", "" - if err := api.Create(ctx, segment); err != nil { - t.Fatal(err) - } - if _, _, err := handler.Store.Read(ctx); err == nil { - t.Fatal("replacement segment adopted") - } - }) - t.Run("uncertain-write-and-read-only", func(t *testing.T) { - handler, key := newHandler(t, "uncertain") - if err := handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")); err != nil { - t.Fatal(err) - } - secret, ledger, _ := handler.Store.Read(ctx) - ledger.DeviceFences = append(ledger.DeviceFences, DeviceFence{Project: "provider", UID: "uncertain", Aliases: []string{"retained"}}) - store := handler.Store - store.Client = &faultClient{Client: api, updateAt: 1, updateAfter: true} - if !errors.Is(store.Write(ctx, secret, ledger), context.DeadlineExceeded) { - t.Fatal("write should be uncertain") - } - secret, observed, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(ledger, observed) { - t.Fatal("persist timeout released state", err) - } - store.Client = &faultClient{Client: api, updateAt: 1} - observed.DeviceFences = append(observed.DeviceFences, DeviceFence{Project: "provider", UID: "denied"}) - if store.Write(ctx, secret, observed) == nil { - t.Fatal("read-only storage admitted") - } - _, retained, err := handler.Store.Read(ctx) - if err != nil || !reflect.DeepEqual(ledger, retained) { - t.Fatal("read-only failure changed history", err) - } - retained.DeviceFences = nil - if handler.Store.Write(ctx, secret, retained) == nil { - t.Fatal("alias removal accepted") - } - role := &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Name: "reader", Namespace: handler.Store.Namespace}, Rules: []rbacv1.PolicyRule{{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"get"}}}} - if err := api.Create(ctx, role); err != nil { - t.Fatal(err) - } - binding := &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Name: "reader", Namespace: handler.Store.Namespace}, Subjects: []rbacv1.Subject{{Kind: "User", Name: "ledger-reader"}}, RoleRef: rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "Role", Name: "reader"}} - if err := api.Create(ctx, binding); err != nil { - t.Fatal(err) - } - readOnlyConfig := rest.CopyConfig(config) - readOnlyConfig.Impersonate = rest.ImpersonationConfig{UserName: "ledger-reader", Groups: []string{"system:authenticated"}} - readOnly, err := client.New(readOnlyConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - store.Client = readOnly - secret, observed, err = store.Read(ctx) - if err != nil { - t.Fatal("read-only observation should work", err) - } - observed.DeviceFences = append(observed.DeviceFences, DeviceFence{Project: "provider", UID: "forbidden"}) - if err := store.Write(ctx, secret, observed); !apierrors.IsForbidden(err) { - t.Fatal("read-only storage wrote", err) - } - }) -} diff --git a/internal/registration/terminal_errors_test.go b/internal/registration/terminal_errors_test.go deleted file mode 100644 index 7d6d9932..00000000 --- a/internal/registration/terminal_errors_test.go +++ /dev/null @@ -1,121 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "strings" - "testing" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/client/fake" -) - -const runbook = "docs/development/registration-storage-rollout.md" - -// sealedRoot converts the fixture root to v2 routing with the given number of -// sealed segments, each a valid immutable overlay of the configured scope. -func sealedRoot(t *testing.T, handler *Handler, sealed int) { - t.Helper() - ctx := context.Background() - store := handler.Store - secret := &corev1.Secret{} - if err := store.Client.Get(ctx, client.ObjectKey{Namespace: store.Namespace, Name: LedgerName}, secret); err != nil { - t.Fatal(err) - } - empty, _ := json.Marshal(Ledger{Authority: store.Authority, Projects: store.Projects}) - route := Routing{Version: 2, RootUID: secret.UID, Epoch: uint64(sealed)} - immutable := true - for epoch := 0; epoch < sealed; epoch++ { - segment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: store.Namespace, Name: segmentName(secret.UID, uint64(epoch)), UID: types.UID(fmt.Sprint("segment-", epoch))}, Immutable: &immutable, Data: map[string][]byte{"ledger.json": empty}} - if err := store.Client.Create(ctx, segment); err != nil { - t.Fatal(err) - } - if segment.UID == "" { - t.Fatal("segment UID not retained") - } - route.Segments = append(route.Segments, Segment{Name: segment.Name, UID: segment.UID, Digest: digest(empty)}) - } - encoded, _ := json.Marshal(route) - secret.Data = map[string][]byte{"ledger.json": []byte(`{"authority":"v2-routing-required","projects":[]}`), "tail.json": empty, "routing.json": encoded} - if err := store.Client.Update(ctx, secret); err != nil { - t.Fatal(err) - } -} - -func oversizedWrite(t *testing.T, handler *Handler) error { - t.Helper() - secret, ledger, err := handler.Store.Read(context.Background()) - if err != nil { - t.Fatal(err) - } - ledger.DeviceFences = append(ledger.DeviceFences, DeviceFence{Project: "provider", UID: "oversize", Aliases: []string{strings.Repeat("x", TailBudget)}}) - return handler.Store.Write(context.Background(), secret, ledger) -} - -func TestSegmentExhaustionIsDistinctAndActionable(t *testing.T) { - ctx := context.Background() - handler, _ := fixture(t) - key := controlFixture(t, handler) - sealedRoot(t, handler, MaxSegments) - for name, err := range map[string]error{ - "expand": handler.ApplyControl(ctx, controlFor(t, handler, key, "expand")), - "write": oversizedWrite(t, handler), - } { - if !errors.Is(err, ErrSegmentsExhausted) || !errors.Is(err, ErrGrowthStopped) { - t.Fatalf("%s: terminal growth stop not distinct: %v", name, err) - } - message := err.Error() - if strings.Contains(message, "expansion required") || !strings.Contains(message, "segments exhausted") || !strings.Contains(message, "reviewed storage migration") || !strings.Contains(message, runbook) { - t.Fatalf("%s: terminal error is not operator-actionable: %s", name, message) - } - } - _, route, err := handler.Store.root(ctx) - if err != nil || route.Pending != nil || len(route.Segments) != MaxSegments { - t.Fatalf("refused expansion changed routing: %+v %v", route, err) - } -} - -func TestGrowthStopBelowSegmentCapStillAsksForExpansion(t *testing.T) { - handler, _ := fixture(t) - controlFixture(t, handler) - sealedRoot(t, handler, MaxSegments-1) - err := oversizedWrite(t, handler) - if !errors.Is(err, ErrGrowthStopped) || errors.Is(err, ErrSegmentsExhausted) { - t.Fatalf("expandable root reported terminal exhaustion: %v", err) - } -} - -func TestFullLegacyLedgerNamesExpandRequest(t *testing.T) { - handler, _ := fixture(t) - err := oversizedWrite(t, handler) - if err == nil || !strings.Contains(err.Error(), "sign an expand") || !strings.Contains(err.Error(), runbook) { - t.Fatalf("full v1 ledger does not say how to proceed: %v", err) - } -} - -func TestActivationGateIsDefaultAndProductionForcesIt(t *testing.T) { - ctx := context.Background() - handler, device := fixture(t) - handler.Store.AllowInactiveForTests = false - if handler.Handle(ctx, registrationRequest(t, device, "zero-value")).Allowed { - t.Fatal("zero-value store admitted without signed activation") - } - if _, ledger, err := handler.Store.Read(ctx); err != nil || len(ledger.Entries) != 0 { - t.Fatalf("gated admission retained a reservation: %+v %v", ledger, err) - } - scheme := runtime.NewScheme() - if err := corev1.AddToScheme(scheme); err != nil { - t.Fatal(err) - } - production := NewHandler(Store{Client: handler.Store.Client, Namespace: "private", Authority: "milo", Projects: []string{"provider"}, AllowInactiveForTests: true}, fake.NewClientBuilder().WithScheme(scheme).Build(), &rest.Config{Host: "https://synthetic.invalid"}, scheme) - if production.Store.AllowInactiveForTests { - t.Fatal("production wiring kept the test-only activation opt-out") - } -} diff --git a/internal/registration/testdata/review_adversarial_test.go.txt b/internal/registration/testdata/review_adversarial_test.go.txt deleted file mode 100644 index fefd78ba..00000000 --- a/internal/registration/testdata/review_adversarial_test.go.txt +++ /dev/null @@ -1,172 +0,0 @@ -package registration - -import ( - "context" - "encoding/json" - "net/http/httptest" - "os" - "path/filepath" - "testing" - "time" - - inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" - metal "go.datum.net/fleet/internal/api/v1alpha1" - "go.datum.net/fleet/internal/controller" - iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" - admissionregistrationv1 "k8s.io/api/admissionregistration/v1" - authorizationv1 "k8s.io/api/authorization/v1" - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/client-go/rest" - "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" - "sigs.k8s.io/controller-runtime/pkg/webhook/admission" - "sigs.k8s.io/yaml" -) - -func TestReviewRealNoopAndOutage(t *testing.T) { - if os.Getenv("KUBEBUILDER_ASSETS") == "" { - t.Skip("KUBEBUILDER_ASSETS required") - } - ctx := context.Background() - environment := &envtest.Environment{CRDDirectoryPaths: []string{filepath.Join("..", "..", "config", "base", "crd"), filepath.Join("..", "..", "config", "components", "inventory", "crds")}, ErrorIfCRDPathMissing: true} - config, err := environment.Start() - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { - if err := environment.Stop(); err != nil { - t.Error(err) - } - }) - scheme := runtime.NewScheme() - for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, inventory.AddToScheme, metal.AddToScheme, admissionregistrationv1.AddToScheme, authorizationv1.AddToScheme} { - if err := add(scheme); err != nil { - t.Fatal(err) - } - } - api, err := client.New(config, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - device := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "noop-hardware", Namespace: "default"}, Spec: inventory.DeviceSpec{ClaimRef: inventory.LocalReference{Name: "installation"}, Identity: inventory.DeviceIdentity{Model: "test", Serial: "noop-serial", SystemUUID: "11111111-1111-1111-1111-111111111111"}}} - if err := api.Create(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - encoded, _ := json.Marshal(Ledger{Authority: "milo", Projects: []string{"provider"}}) - if err := api.Create(ctx, &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: LedgerName, Namespace: "default"}, Data: map[string][]byte{"ledger.json": encoded}}); err != nil { - t.Fatal(err) - } - handler := &Handler{Store: Store{Client: api, Namespace: "default", Authority: "milo", Projects: []string{"provider"}}, VerifyFence: func(ctx context.Context) error { return VerifyFence(ctx, api) }, Resolve: func(context.Context, string) (Project, error) { - return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "provider", UID: "project-1"}, Client: api}, nil - }, Authorize: Authorize} - server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) - t.Cleanup(server.Close) - data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") - if err != nil { - t.Fatal(err) - } - var webhooks admissionregistrationv1.ValidatingWebhookConfiguration - if err := yaml.UnmarshalStrict(data, &webhooks); err != nil { - t.Fatal(err) - } - url := server.URL - webhooks.Webhooks[0].ClientConfig = admissionregistrationv1.WebhookClientConfig{URL: &url, CABundle: pemCertificate(server.Certificate().Raw)} - if err := api.Create(ctx, &webhooks); err != nil { - t.Fatal(err) - } - actorConfig := rest.CopyConfig(config) - actorConfig.Impersonate = rest.ImpersonationConfig{UserName: "review-operator", UID: "actor-1", Groups: []string{"system:masters"}, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"provider"}}} - actor, err := client.New(actorConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - deadline := time.Now().Add(10 * time.Second) - for { - if err := actor.Update(ctx, device.DeepCopyObject().(*inventory.Device), client.DryRunAll); err != nil { - break - } - if time.Now().After(deadline) { - t.Fatal("webhook did not engage") - } - time.Sleep(30 * time.Millisecond) - } - t.Run("successful-noop-must-not-poison-current-device", func(t *testing.T) { - unchanged := false - for attempt := 0; attempt < 3; attempt++ { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - before := device.ResourceVersion - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if before == device.ResourceVersion { - unchanged = true - break - } - } - if !unchanged { - t.Fatal("could not reproduce a no-op update") - } - request := registrationRequest(t, device, "after-noop") - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { - t.Fatal(err) - } - capacity.UID = "" - if err := actor.Create(ctx, &capacity); err != nil { - t.Errorf("completed no-op left current RV %s ineligible: %v", device.ResourceVersion, err) - } - }) - t.Run("explicit-real-edit-control-restores-registration", func(t *testing.T) { - if err := actor.Get(ctx, client.ObjectKeyFromObject(device), device); err != nil { - t.Fatal(err) - } - before := device.ResourceVersion - device.Labels = map[string]string{"review-control": "real-change"} - if err := actor.Update(ctx, device, client.FieldOwner("review")); err != nil { - t.Fatal(err) - } - if device.ResourceVersion == before { - t.Fatal("control edit did not change RV") - } - request := registrationRequest(t, device, "after-real-edit") - var capacity metal.MachineCapacity - if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { - t.Fatal(err) - } - capacity.UID = "" - if err := actor.Create(ctx, &capacity); err != nil { - t.Fatalf("explicitly reselected changed Device should register: %v", err) - } - if err := handler.Recover(ctx); err != nil { - t.Fatal(err) - } - _, ledger, err := handler.Store.Read(ctx) - if err != nil || len(ledger.Entries) != 1 || ledger.Entries[0].Outcome != "Recorded" { - t.Fatalf("control failed: %+v %v", ledger, err) - } - }) - t.Run("out-of-scope-inventory-outage-blast-radius", func(t *testing.T) { - outsideConfig := rest.CopyConfig(actorConfig) - outsideConfig.Impersonate.Extra = map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"unrelated-consumer"}} - outside, err := client.New(outsideConfig, client.Options{Scheme: scheme}) - if err != nil { - t.Fatal(err) - } - other := device.DeepCopyObject().(*inventory.Device) - other.Name, other.UID, other.ResourceVersion, other.ManagedFields = "outside-before-outage", "", "", nil - if err := outside.Create(ctx, other); err != nil { - t.Fatal(err) - } - server.Close() - other.Name, other.UID, other.ResourceVersion, other.ManagedFields = "outside-after-outage", "", "", nil - if err := outside.Create(ctx, other); err == nil { - t.Fatal("expected packaged fail-closed webhook to block unrelated inventory too") - } else { - t.Logf("confirmed unrelated project inventory outage: %v", err) - } - }) -} diff --git a/internal/registration/transport.go b/internal/registration/transport.go index 1113fe89..da35f813 100644 --- a/internal/registration/transport.go +++ b/internal/registration/transport.go @@ -1,104 +1,18 @@ package registration import ( - "context" - "crypto/ed25519" - "crypto/x509" - "encoding/json" - "encoding/pem" - "errors" "net/http" - "time" - - "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" ) -func ParseControlKey(encoded []byte) (ed25519.PublicKey, error) { - block, rest := pem.Decode(encoded) - if block == nil || len(rest) != 0 { - return nil, errors.New("expected one PKIX public key") - } - parsed, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return nil, err - } - key, ok := parsed.(ed25519.PublicKey) - if !ok { - return nil, errors.New("control key must be Ed25519") - } - return key, nil -} - -func ParseControl(encoded []byte) (SignedControl, error) { - var control SignedControl - if len(encoded) > 16384 { - return control, errors.New("control request exceeds budget") - } - err := json.Unmarshal(encoded, &control) - return control, err -} - +// Transport serves the validating webhook and a transport probe. Both sit +// behind the same mutually authenticated TLS listener. func (handler *Handler) Transport() http.Handler { mux := http.NewServeMux() mux.Handle("/validate-registration", &admission.Webhook{Handler: handler}) - mux.HandleFunc("/transportz", func(writer http.ResponseWriter, request *http.Request) { - writer.WriteHeader(http.StatusNoContent) - }) - mux.HandleFunc("/activationz", func(writer http.ResponseWriter, request *http.Request) { - ctx, cancel := context.WithTimeout(request.Context(), 5*time.Second) - defer cancel() - if err := handler.Ready(ctx); err != nil { - http.Error(writer, "registration non-admitting or dependencies unavailable", http.StatusServiceUnavailable) - return - } + mux.HandleFunc("/transportz", func(writer http.ResponseWriter, _ *http.Request) { writer.WriteHeader(http.StatusNoContent) }) - mux.HandleFunc("/status", func(writer http.ResponseWriter, request *http.Request) { - ctx, cancel := context.WithTimeout(request.Context(), 5*time.Second) - defer cancel() - status, err := handler.Status(ctx) - if err != nil { - http.Error(writer, "registration ledger unavailable", http.StatusServiceUnavailable) - return - } - writer.Header().Set("Content-Type", "application/json") - _ = json.NewEncoder(writer).Encode(status) - }) return mux } - -type Status struct { - Authority string `json:"authority"` - Projects []string `json:"projects"` - RootUID types.UID `json:"rootUID"` - ResourceVersion string `json:"resourceVersion"` - Epoch uint64 `json:"epoch"` - TailBytes int `json:"tailBytes"` - HeadroomBytes int `json:"headroomBytes"` - RemainingSegments int `json:"remainingSegments"` - Pending bool `json:"pending"` - ActivationVerified bool `json:"activationVerified"` - FenceDigest string `json:"fenceDigest,omitempty"` -} - -func (handler *Handler) Status(ctx context.Context) (Status, error) { - secret, route, err := handler.Store.root(ctx) - if err != nil { - return Status{}, err - } - if _, _, err := handler.Store.readSnapshot(ctx, secret); err != nil { - return Status{}, err - } - tail := secret.Data["tail.json"] - if _, exists := secret.Data["routing.json"]; !exists { - tail = secret.Data["ledger.json"] - } - status := Status{Authority: handler.Store.Authority, Projects: handler.Store.Projects, RootUID: secret.UID, ResourceVersion: secret.ResourceVersion, Epoch: route.Epoch, TailBytes: len(tail), HeadroomBytes: max(0, TailBudget-len(tail)), RemainingSegments: MaxSegments - len(route.Segments), Pending: route.Pending != nil} - status.ActivationVerified = handler.readySnapshot(ctx, secret, route) == nil - if handler.FenceDigest != nil { - status.FenceDigest, _ = handler.FenceDigest(ctx) - } - return status, nil -} From ebf574557483a6a7a5bb1e862ed32e4e0eb6ae6d Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:46 -0600 Subject: [PATCH 02/16] feat(config): add Device deletion protection Add config/components/device-deletion-protection, a ValidatingAdmissionPolicy and binding that deny every Device DELETE with no exemptions. config/milo-production is config/milo plus the component. config/milo, config/milo-synthetic and every other root leave it out, so test and staging control planes can still delete Devices. The overlay isolation validator now fails when a production-style root lacks the component or any other root renders it. CI builds the new root. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 + .../kustomization.yaml | 7 ++ .../device-deletion-protection/policy.yaml | 34 +++++++ config/milo-production/kustomization.yaml | 9 ++ hack/overlay-isolation-validator.go | 98 +++++++++++++++++++ hack/test-overlay-isolation.sh | 38 +++++++ 6 files changed, 187 insertions(+) create mode 100644 config/components/device-deletion-protection/kustomization.yaml create mode 100644 config/components/device-deletion-protection/policy.yaml create mode 100644 config/milo-production/kustomization.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d537961b..0fbf0da4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,7 @@ jobs: - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null + - run: kustomize build config/milo-production >/dev/null - run: kustomize build config/milo-synthetic >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/config/components/device-deletion-protection/kustomization.yaml b/config/components/device-deletion-protection/kustomization.yaml new file mode 100644 index 00000000..03bc082f --- /dev/null +++ b/config/components/device-deletion-protection/kustomization.yaml @@ -0,0 +1,7 @@ +# Optional: install wherever Device objects are admitted (the Milo control +# plane) in environments that must never lose a Device. See +# docs/development/inventory-capacity-registration.md#device-deletion-protection. +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: + - policy.yaml diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml new file mode 100644 index 00000000..bc69125e --- /dev/null +++ b/config/components/device-deletion-protection/policy.yaml @@ -0,0 +1,34 @@ +# Devices are never deleted where this component is installed. Retire a +# machine through its capacity staying Disabled instead. The API server runs +# admission once per object for deletecollection, garbage collection and +# namespace or project cleanup, so every one of those paths is denied too. +# There are no exemptions: an environment that needs Device deletion does not +# install this component. +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicy +metadata: + name: fleet-device-deletion-protection +spec: + failurePolicy: Fail + matchConstraints: + matchPolicy: Equivalent + resourceRules: + - apiGroups: [fleet.datumapis.com] + apiVersions: ['*'] + operations: [DELETE] + resources: [devices] + validations: + - expression: 'false' + reason: Forbidden + message: >- + Devices cannot be deleted in this environment. Their identity must stay + visible to duplicate-hardware checks. Leave the Device in place and + keep its capacity Disabled. +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: ValidatingAdmissionPolicyBinding +metadata: + name: fleet-device-deletion-protection +spec: + policyName: fleet-device-deletion-protection + validationActions: [Deny] diff --git a/config/milo-production/kustomization.yaml b/config/milo-production/kustomization.yaml new file mode 100644 index 00000000..c3a66020 --- /dev/null +++ b/config/milo-production/kustomization.yaml @@ -0,0 +1,9 @@ +# Production-style Milo root: config/milo plus Device deletion protection. +# Environments that need Device deletions, such as test and staging control +# planes, consume config/milo instead. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../milo +components: + - ../components/device-deletion-protection diff --git a/hack/overlay-isolation-validator.go b/hack/overlay-isolation-validator.go index 8d1ea9f6..6ffe60eb 100644 --- a/hack/overlay-isolation-validator.go +++ b/hack/overlay-isolation-validator.go @@ -26,8 +26,15 @@ const ( marker = "fleet.datumapis.com/standalone-only" localProjectStandIn = "fleet.datumapis.com/local-project-stand-in" sharedNamespace = "fleet.datumapis.com/shared-with-standalone" + + // Device deletion protection is optional per environment. Only the + // production-style roots below may render it, and they must. + deletionProtection = "fleet-device-deletion-protection" + deletionProtectionComponent = "components/device-deletion-protection" ) +var deletionProtectedRoots = []string{"milo-production"} + type kustomization struct { Resources []string `json:"resources"` Components []string `json:"components"` @@ -78,6 +85,16 @@ func main() { } } v.indexStandalone(standaloneObjects) + if err := checkDeletionProtection("standalone", standaloneObjects, false); err != nil { + fatalf("render %s: %v", standaloneRoot, err) + } + if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(deletionProtectionComponent))); err == nil { + for _, root := range deletionProtectedRoots { + if _, err := os.Stat(filepath.Join(configRoot, root)); err != nil { + fatalf("production-style root %s must exist and install Device deletion protection: %v", root, err) + } + } + } entries, err := discover(configRoot) check(err) @@ -103,6 +120,16 @@ func main() { fatalf("render %s: %v", root, err) } } + relative, err := filepath.Rel(configRoot, root) + check(err) + relative = filepath.ToSlash(relative) + required := relative == deletionProtectionComponent + for _, protected := range deletionProtectedRoots { + required = required || relative == protected + } + if err := checkDeletionProtection(relative, objects, required); err != nil { + fatalf("render %s: %v", root, err) + } } if checked == 0 { fatalf("no non-standalone Kustomize entry point was validated") @@ -260,6 +287,77 @@ func (v *validator) checkObject(object *unstructured.Unstructured) error { return nil } +// checkDeletionProtection requires the exact deny-all Device DELETE policy and +// its binding in production-style roots, and forbids either object anywhere +// else, so test and synthetic roots keep Device deletion available. +func checkDeletionProtection(root string, objects []*unstructured.Unstructured, required bool) error { + var policy, binding *unstructured.Unstructured + for _, object := range objects { + if object.GetAPIVersion() != "admissionregistration.k8s.io/v1" { + continue + } + switch object.GetKind() { + case "ValidatingAdmissionPolicy": + if object.GetName() == deletionProtection || policyMatchesDeviceDelete(object) { + policy = object + } + case "ValidatingAdmissionPolicyBinding": + if name, _, _ := unstructured.NestedString(object.Object, "spec", "policyName"); object.GetName() == deletionProtection || name == deletionProtection { + binding = object + } + } + } + if !required { + if policy != nil || binding != nil { + return fmt.Errorf("%s renders Device deletion protection; only %v may install %s", root, deletionProtectedRoots, deletionProtectionComponent) + } + return nil + } + if policy == nil || binding == nil { + return fmt.Errorf("production-style root %s must install the Device deletion policy and its binding", root) + } + failurePolicy, _, _ := unstructured.NestedString(policy.Object, "spec", "failurePolicy") + validations, _, _ := unstructured.NestedSlice(policy.Object, "spec", "validations") + _, hasConditions := policy.Object["spec"].(map[string]any)["matchConditions"] + if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || hasConditions || len(validations) != 1 { + return fmt.Errorf("%s: Device deletion policy must fail closed, match DELETE on devices and have no exemptions", root) + } + if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); expression != "false" { + return fmt.Errorf("%s: Device deletion policy must deny every DELETE", root) + } + actions, _, _ := unstructured.NestedStringSlice(binding.Object, "spec", "validationActions") + _, hasMatch := binding.Object["spec"].(map[string]any)["matchResources"] + _, hasParams := binding.Object["spec"].(map[string]any)["paramRef"] + if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParams { + return fmt.Errorf("%s: Device deletion binding must Deny in every namespace", root) + } + return nil +} + +func policyMatchesDeviceDelete(policy *unstructured.Unstructured) bool { + rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") + for _, raw := range rules { + rule, ok := raw.(map[string]any) + if !ok { + continue + } + groups, resources, operations := stringsFrom(rule["apiGroups"]), stringsFrom(rule["resources"]), stringsFrom(rule["operations"]) + if (contains(groups, "fleet.datumapis.com") || contains(groups, "*")) && (contains(resources, "devices") || contains(resources, "*")) && (contains(operations, "DELETE") || contains(operations, "*")) { + return true + } + } + return false +} + +func contains(values []string, value string) bool { + for _, candidate := range values { + if candidate == value { + return true + } + } + return false +} + func isCoreNamespace(object *unstructured.Unstructured) bool { return object.GetAPIVersion() == "v1" && object.GetKind() == "Namespace" } diff --git a/hack/test-overlay-isolation.sh b/hack/test-overlay-isolation.sh index e8564d36..6d0ec68f 100755 --- a/hack/test-overlay-isolation.sh +++ b/hack/test-overlay-isolation.sh @@ -417,4 +417,42 @@ EOF expect_failure "intentional Kustomize build failure" "missing.yaml" rm -rf "$fixture_root/config/overlays/broken" +# Device deletion protection is per environment: only production-style roots +# may render it, and once the component exists they must. +mkdir -p "$fixture_root/config/components/device-deletion-protection" +cp "$repo_root/config/components/device-deletion-protection/kustomization.yaml" "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/" +expect_failure "deletion component without a production-style root" "production-style root milo-production must exist" +mkdir -p "$fixture_root/config/milo-production" +cat >"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../base/safe] +EOF +expect_failure "production-style root without deletion protection" "must install the Device deletion policy and its binding" +cat >>"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' +components: [../components/device-deletion-protection] +EOF +"$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" +mkdir -p "$fixture_root/config/overlays/synthetic-with-protection" +cat >"$fixture_root/config/overlays/synthetic-with-protection/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../../base/safe] +components: [../../components/device-deletion-protection] +EOF +expect_failure "test or synthetic root installing deletion protection" "renders Device deletion protection" +rm -rf "$fixture_root/config/overlays/synthetic-with-protection" +mkdir -p "$fixture_root/config/overlays/renamed-protection" +sed 's/name: fleet-device-deletion-protection/name: renamed-device-guard/; s/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/overlays/renamed-protection/policy.yaml" +cat >"$fixture_root/config/overlays/renamed-protection/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [policy.yaml] +EOF +expect_failure "renamed Device deletion policy outside production roots" "renders Device deletion protection" +rm -rf "$fixture_root/config/overlays/renamed-protection" +sed 's/validationActions: \[Deny\]/validationActions: [Audit]/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/components/device-deletion-protection/policy.yaml" +expect_failure "audit-only Device deletion binding" "must Deny in every namespace" +cp "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/policy.yaml" + "$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" From 00a33dc774678697e678e70bdfd46dcac6e81491 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:46 -0600 Subject: [PATCH 03/16] feat(ui): derive capacity name from the Device The registration form no longer asks for a capacity name. It shows device-, which is what admission now requires, and marks every Device that shares a normalized serial, system UUID or provider host reference with another Device as Conflicting. Co-Authored-By: Claude Opus 5.5 --- ui/provider/README.md | 10 +++--- .../src/components/create-capacity-dialog.tsx | 21 ++++++------ .../src/lib/capacity-registration.test.ts | 26 +++++++++++---- ui/provider/src/lib/capacity-registration.ts | 32 ++++++++++++++++--- .../src/pages/capacity-registration.test.tsx | 9 +++--- ui/shared/fleet-api.ts | 2 +- 6 files changed, 67 insertions(+), 33 deletions(-) diff --git a/ui/provider/README.md b/ui/provider/README.md index ef4567c8..f55063c8 100644 --- a/ui/provider/README.md +++ b/ui/provider/README.md @@ -8,13 +8,15 @@ Operations in the navigation. The page has four tabs: - **Capacity** (the mount root, where the nav item points) lists the provider's MachineCapacities in every namespace. A verified host session can - register an existing `default` Device under an independently authored name. + register an existing `default` Device as `device-` capacity. Selection retains the exact Device UID/resourceVersion; the named reference is immutable. Registration is Disabled/Retain with cleaning explicitly unconfigured, without class assignment, allocation, preparation or positive - readiness. The server enforces permissions, physical-alias reservations and - lifetime fences. Unknown completion blocks retries and never deletes capacity - to roll back. See the [registration contract](../../docs/development/inventory-capacity-registration.md). + readiness. The capacity name is derived from the Device UID, so a Device + backs at most one capacity. Devices sharing a hardware alias are marked + Conflicting. The server enforces permissions and checks live Devices for + duplicates. Unknown completion blocks retries in the form and never deletes + capacity to roll back. See the [registration contract](../../docs/development/inventory-capacity-registration.md). - **Profiles** (`profiles`) lists MachineProfiles and creates new ones. A profile can't be changed after it is created, so there is no edit. - **Classes** (`classes`) lists MachineClasses and creates new ones: the diff --git a/ui/provider/src/components/create-capacity-dialog.tsx b/ui/provider/src/components/create-capacity-dialog.tsx index df50a62b..12c6c18c 100644 --- a/ui/provider/src/components/create-capacity-dialog.tsx +++ b/ui/provider/src/components/create-capacity-dialog.tsx @@ -1,10 +1,9 @@ import { Button } from '@datum-cloud/datum-ui/button'; -import { Input } from '@datum-cloud/datum-ui/input'; import { Label } from '@datum-cloud/datum-ui/label'; import { useQuery } from '@tanstack/react-query'; import { useContext, useLayoutEffect, useRef, useState, type FormEvent } from 'react'; import type { Device } from '../../../shared/fleet-api'; -import { ineligibleReason, registerCapacity, registrationDevices, registrationPermission, RegistrationUnknown } from '../lib/capacity-registration'; +import { capacityNameFor, ineligibleReason, registerCapacity, registrationDevices, registrationPermission, RegistrationUnknown } from '../lib/capacity-registration'; import { InventoryOperationContext, InventoryOperationReadyContext, InventoryOperationScope, type InventoryOperation } from '../lib/inventory-operation'; import { useInventoryRead } from '../lib/inventory-read'; import { confirmInventoryDismissal, InventoryDraftGuard, InventoryForm, InventoryFormSurface } from './inventory-form-surface'; @@ -21,7 +20,6 @@ export function CapacityRegistrationForm({ onRegistered }: { onRegistered?: () = const operation = useRef(undefined); const operationID = useRef(''); const [open, setOpen] = useState(false); - const [name, setName] = useState(''); const [selected, setSelected] = useState(); const [pending, setPending] = useState(false); const [unknown, setUnknown] = useState(false); @@ -33,16 +31,16 @@ export function CapacityRegistrationForm({ onRegistered }: { onRegistered?: () = useLayoutEffect(() => { scope.startLifecycle(); return () => scope.invalidate(); }, [scope]); const available = ready && !!parent && permission.data === true; const dismiss = () => { - if (confirmInventoryDismissal(!!name || !!selected, pending, unknown)) { scope.invalidate(); setOpen(false); } + if (confirmInventoryDismissal(!!selected, pending, unknown)) { scope.invalidate(); setOpen(false); } }; async function submit(event: FormEvent) { event.preventDefault(); if (!available || pending || unknown || !selected || !operation.current) return; setPending(true); setMessage(''); try { - await registerCapacity(name, selected, operationID.current, operation.current); - setMessage(`Registered ${name} as Disabled/Retain. Cleaning is unconfigured; readiness and availability remain unknown.`); - setName(''); setSelected(undefined); setOpen(false); onRegistered?.(); + const result = await registerCapacity(selected, operationID.current, operation.current); + setMessage(`Registered ${result.metadata.name} as Disabled/Retain. Cleaning is unconfigured; readiness and availability remain unknown.`); + setSelected(undefined); setOpen(false); onRegistered?.(); } catch (error) { setUnknown(error instanceof RegistrationUnknown); setMessage(error instanceof Error ? error.message : 'Registration unavailable.'); @@ -50,23 +48,22 @@ export function CapacityRegistrationForm({ onRegistered }: { onRegistered?: () = } const status = <>{message &&

{message}

}{!available &&

{permission.isPending ? 'Checking registration permission…' : permission.error ? 'Registration unavailable: authorization could not be checked.' : 'Registration denied or unavailable for this session. Synthetic previews cannot register capacity.'}

}; return <> - + { scope.startLifecycle(); operation.current = scope.begin(parent); operationID.current = crypto.randomUUID(); - setName(''); setSelected(undefined); setUnknown(false); setMessage(''); setOpen(true); + setSelected(undefined); setUnknown(false); setMessage(''); setOpen(true); }}>Register capacity}> void submit(event)} message={message}>

Choose a Device in default. This creates an inert Disabled/Retain record, not usable capacity. Cleaning remains explicitly unconfigured. No hardware is prepared or changed.

- + }}>{devices.data?.map(device => )} {devices.isPending &&

Loading Devices…

} {devices.error &&

Devices are unavailable or access is denied. Registration is blocked.

} {devices.data?.length === 0 &&

No Devices are available in default.

} - {selected &&

The authored Device reference {selected.metadata.name} is immutable. This selection retains its exact incarnation and version; it is never silently refreshed.

} + {selected &&

Capacity name: {capacityNameFor(selected)}. It is derived from this Device, so the Device can back only one capacity. The Device reference {selected.metadata.name} is immutable. This selection retains its exact incarnation and version; it is never silently refreshed.

}
diff --git a/ui/provider/src/lib/capacity-registration.test.ts b/ui/provider/src/lib/capacity-registration.test.ts index a3713191..52ea1963 100644 --- a/ui/provider/src/lib/capacity-registration.test.ts +++ b/ui/provider/src/lib/capacity-registration.test.ts @@ -1,6 +1,6 @@ import { beforeEach, expect, it, vi } from 'vitest'; import type { Device } from '../../../shared/fleet-api'; -import { registerCapacity, ineligibleReason, REGISTRATION_DEVICE_UID, REGISTRATION_DEVICE_VERSION, RegistrationUnknown } from './capacity-registration'; +import { capacityNameFor, registerCapacity, ineligibleReason, REGISTRATION_DEVICE_UID, REGISTRATION_DEVICE_VERSION, RegistrationUnknown } from './capacity-registration'; import { InventoryOperationScope } from './inventory-operation'; const device: Device = { metadata: { name: 'chosen-hardware', namespace: 'default', uid: 'device-1', resourceVersion: '7' }, spec: { claimRef: { name: 'installation' }, identity: { model: 'test', serial: 'serial-1', systemUUID: '11111111-1111-1111-1111-111111111111' } } }; @@ -14,8 +14,9 @@ beforeEach(() => { }); }); -it('uses the exact selected Device, authored name, Disabled/Retain and no synthetic policy', async () => { - const result = await registerCapacity('authored-name', device, 'operation-1', new InventoryOperationScope().begin()); +it('uses the exact selected Device, the Device-derived name, Disabled/Retain and no synthetic policy', async () => { + const result = await registerCapacity(device, 'operation-1', new InventoryOperationScope().begin()); + expect(result.metadata.name).toBe('device-device-1'); expect(result.spec).toEqual({ deviceRef: { name: 'chosen-hardware' }, allocationPolicy: 'Disabled', reclaimPolicy: 'Retain', cleaningPolicyRef: { name: '' } }); expect(result.metadata.annotations).toMatchObject({ [REGISTRATION_DEVICE_UID]: 'device-1', [REGISTRATION_DEVICE_VERSION]: '7' }); expect(result.status).toBeUndefined(); @@ -26,20 +27,20 @@ it('uses the exact selected Device, authored name, Disabled/Retain and no synthe it.each(['uid', 'resourceVersion'] as const)('rejects stale selected %s without refreshing or dispatching', async field => { transport.mockImplementation(async input => String(input).includes('selfsubjectaccessreviews') ? Response.json({ data: { status: { allowed: true } } }) : Response.json({ data: { ...device, metadata: { ...device.metadata, [field]: 'changed' } } })); - await expect(registerCapacity('record', device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('selected Device changed'); + await expect(registerCapacity(device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('selected Device changed'); expect(transport.mock.calls.some(([url]) => String(url).includes('machinecapacities?'))).toBe(false); }); it('does not dispatch on permission revocation', async () => { transport.mockResolvedValue(Response.json({ data: { status: { allowed: false } } })); - await expect(registerCapacity('record', device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('permission is denied'); + await expect(registerCapacity(device, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('permission is denied'); expect(transport).toHaveBeenCalledTimes(1); }); it('fences a session change before dispatch', async () => { const scope = new InventoryOperationScope(); transport.mockImplementation(async () => { scope.invalidate(); return Response.json({ data: { status: { allowed: true } } }); }); - await expect(registerCapacity('record', device, 'operation', scope.begin())).rejects.toThrow('No write was dispatched'); + await expect(registerCapacity(device, 'operation', scope.begin())).rejects.toThrow('No write was dispatched'); expect(transport).toHaveBeenCalledTimes(1); }); @@ -53,10 +54,21 @@ it.each(['network', 'timeout', 'session', 'bad receipt'])('retains an unknown ou if (failure === 'session') scope.invalidate(); return Response.json({ data: { metadata: {} } }); }); - await expect(registerCapacity('record', device, 'operation', scope.begin())).rejects.toBeInstanceOf(RegistrationUnknown); + await expect(registerCapacity(device, 'operation', scope.begin())).rejects.toBeInstanceOf(RegistrationUnknown); expect(transport.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false); }); +it('marks every Device sharing a normalized hardware alias as conflicting', () => { + const twin: Device = { metadata: { name: 'twin', namespace: 'default', uid: 'device-2', resourceVersion: '1' }, spec: { claimRef: { name: 'installation' }, identity: { model: 'test', serial: ' SERIAL-1 ', systemUUID: '22222222-2222-2222-2222-222222222222' } } }; + const unrelated: Device = { ...twin, metadata: { ...twin.metadata, name: 'unrelated', uid: 'device-3' }, spec: { ...twin.spec, identity: { model: 'test', serial: 'serial-3', systemUUID: '33333333-3333-3333-3333-333333333333' } } }; + expect(ineligibleReason(device, [device, twin, unrelated])).toContain('Conflicting'); + expect(ineligibleReason(twin, [device, twin, unrelated])).toContain('Conflicting'); + expect(ineligibleReason(unrelated, [device, twin, unrelated])).toBeUndefined(); + const hosted = (uid: string, id: string): Device => ({ ...unrelated, metadata: { ...unrelated.metadata, uid }, spec: { ...unrelated.spec, identity: { model: 'test', serial: `serial-${uid}`, systemUUID: uid === 'a' ? '44444444-4444-4444-4444-444444444444' : '55555555-5555-5555-5555-555555555555' }, providerHostRef: { system: 'Provider', type: 'server', id } } }); + expect(ineligibleReason(hosted('a', 'host-1'), [hosted('a', 'host-1'), hosted('b', ' HOST-1')])).toContain('Conflicting'); + expect(capacityNameFor(device)).toBe('device-device-1'); +}); + it('rejects partial and unidentified identity and non-default inventory', () => { expect(ineligibleReason({ ...device, spec: { ...device.spec, identity: { model: 'test', serial: 'only-serial' } } })).toContain('ambiguous'); expect(ineligibleReason({ ...device, metadata: { ...device.metadata, namespace: 'other' } })).toContain('unavailable'); diff --git a/ui/provider/src/lib/capacity-registration.ts b/ui/provider/src/lib/capacity-registration.ts index 8fbcc619..cbe5aff1 100644 --- a/ui/provider/src/lib/capacity-registration.ts +++ b/ui/provider/src/lib/capacity-registration.ts @@ -8,10 +8,33 @@ export const REGISTRATION_OPERATION = 'fleet.datumapis.com/registration-operatio const devicesPath = '/apis/fleet.datumapis.com/v1alpha1/namespaces/default/devices'; const capacitiesPath = '/apis/metal.datumapis.com/v1alpha1/namespaces/default/machinecapacities'; -export function ineligibleReason(device: Device): string | undefined { +// capacityNameFor mirrors the admission contract: one capacity per Device, +// named from the Device UID, so the API server rejects a second one. +export function capacityNameFor(device: Device): string { + return `device-${device.metadata.uid ?? ''}`; +} + +// aliases mirrors the server's normalization of serial, system UUID and +// provider host reference. +function aliases(device: Device): string[] { + const normalize = (value?: string) => (value ?? '').trim().toLowerCase(); + const result: string[] = []; + if (normalize(device.spec.identity.serial)) result.push(`serial:${normalize(device.spec.identity.serial)}`); + if (normalize(device.spec.identity.systemUUID)) result.push(`uuid:${normalize(device.spec.identity.systemUUID)}`); + const host = device.spec.providerHostRef; + if (host) result.push(`provider:${JSON.stringify([normalize(host.system), normalize(host.type), normalize(host.id)])}`); + return result; +} + +// ineligibleReason explains why a Device cannot be registered. Passing the +// listed Devices also marks every Device that shares a hardware alias with +// another one as conflicting until a person resolves the duplicate. +export function ineligibleReason(device: Device, listed: Device[] = []): string | undefined { if (device.metadata.namespace !== 'default' || !device.metadata.uid || !device.metadata.resourceVersion || device.metadata.deletionTimestamp) return 'Device incarnation is unavailable or deleting'; if (device.spec.identity.unidentified || !device.spec.identity.serial?.trim() || !device.spec.identity.systemUUID) return 'Both serial and system UUID are required; partial identity is ambiguous'; if (['unknown', 'none', 'n/a', 'default string', 'to be filled by o.e.m.'].includes(device.spec.identity.serial.trim().toLowerCase()) || ['00000000-0000-0000-0000-000000000000', 'ffffffff-ffff-ffff-ffff-ffffffffffff'].includes(device.spec.identity.systemUUID)) return 'Placeholder identity is ineligible'; + const own = aliases(device); + if (listed.some(other => other.metadata.uid !== device.metadata.uid && aliases(other).some(alias => own.includes(alias)))) return 'Conflicting: another Device shares this hardware identity; resolve the duplicate first'; return undefined; } @@ -31,13 +54,14 @@ export async function registrationDevices(): Promise { export class RegistrationUnknown extends Error { constructor(name: string, readonly operationID: string, detail: string) { - super(`Registration of ${name} is not confirmed. ${detail} Reservations may be retained. Do not retry under another name or delete capacity to roll back; ask an operator to reconcile operation ${operationID}.`); + super(`Registration of ${name} is not confirmed. ${detail} Check whether capacity ${name} exists before registering again; its name is derived from the Device, so a repeat cannot create a second record. Do not delete capacity to roll back. Client operation ${operationID}.`); } } -export async function registerCapacity(name: string, selected: Device, operationID: string, operation: InventoryOperation): Promise { +export async function registerCapacity(selected: Device, operationID: string, operation: InventoryOperation): Promise { operation.assertCurrent(); - if (!/^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/.test(name) || name.length > 63 || !operationID) throw new Error('Enter a valid authored capacity name.'); + const name = capacityNameFor(selected); + if (!selected.metadata.uid || !operationID) throw new Error('The selected Device has no incarnation to register.'); if (ineligibleReason(selected)) throw new Error(ineligibleReason(selected)); if (!await registrationPermission()) throw new ApiError(403, 'Capacity registration permission is denied or unavailable.'); operation.assertCurrent(); diff --git a/ui/provider/src/pages/capacity-registration.test.tsx b/ui/provider/src/pages/capacity-registration.test.tsx index 10769010..589f5138 100644 --- a/ui/provider/src/pages/capacity-registration.test.tsx +++ b/ui/provider/src/pages/capacity-registration.test.tsx @@ -21,7 +21,6 @@ async function openForm() { const trigger = await screen.findByRole('button', { name: 'Register capacity' }); await waitFor(() => expect(trigger).toBeEnabled()); fireEvent.click(trigger); await screen.findByRole('option', { name: 'server-a' }); - fireEvent.change(screen.getByLabelText('Capacity name'), { target: { value: 'authored-record' } }); fireEvent.change(screen.getByLabelText('Device'), { target: { value: 'device-1' } }); return router; } @@ -29,7 +28,7 @@ async function openForm() { it('registers the selected incarnation through a real host session fence', async () => { await openForm(); fireEvent.click(screen.getByRole('button', { name: 'Register Disabled capacity' })); - expect(await screen.findByText(/Registered authored-record as Disabled\/Retain/)).toBeInTheDocument(); + expect(await screen.findByText(/Registered device-device-1 as Disabled\/Retain/)).toBeInTheDocument(); expect(fetcher.mock.calls.filter(([url, init]) => String(url).includes('machinecapacities?') && init?.method === 'POST')).toHaveLength(1); expect(screen.queryByRole('checkbox')).toBeNull(); }); @@ -38,7 +37,7 @@ it('visible blur/focus is a no-op for the selected baseline and draft', async () await openForm(); const before = fetcher.mock.calls.length; fireEvent(window, new Event('blur')); fireEvent(window, new Event('focus')); - expect(screen.getByLabelText('Capacity name')).toHaveValue('authored-record'); + expect(screen.getByText('device-device-1')).toBeInTheDocument(); expect(screen.getByLabelText('Device')).toHaveValue('device-1'); expect(fetcher.mock.calls).toHaveLength(before); }); @@ -51,8 +50,8 @@ it('keeps unknown completion in the form and prevents retry and rollback', async return Response.json({ data: device }); }); fireEvent.click(screen.getByRole('button', { name: 'Register Disabled capacity' })); - expect(await screen.findByText(/Reservations may be retained/)).toBeInTheDocument(); + expect(await screen.findByText(/Check whether capacity device-device-1 exists/)).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Register Disabled capacity' })).toBeDisabled(); - expect(screen.getByLabelText('Capacity name')).toHaveValue('authored-record'); + expect(screen.getByLabelText('Device')).toHaveValue('device-1'); expect(fetcher.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false); }); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 7baf6b96..3e4e65c9 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -143,7 +143,7 @@ export type AllocationPolicy = 'Enabled' | 'Disabled'; export interface MachineCapacity { metadata: ObjectMeta; spec: { - /** Immutable authored name. Registration retains incarnation evidence privately. */ + /** Immutable Device name. Registration records the Device UID and version in annotations. */ deviceRef: LocalReference; /** Defaults to Disabled. */ allocationPolicy: AllocationPolicy; From ef65a81109c7a2d9ab773648fa7062d902cbab52 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:22:46 -0600 Subject: [PATCH 04/16] docs(registration): record the no-ledger decision Rewrite the stage-1 contract around the decision to drop the ledger and signed activation: live-Device checks, Device-derived capacity names, the documented duplicate race, and optional Device deletion protection, including deletecollection, namespace and project cascades, remediation and retirement. Remove the storage rollout runbook, which only described the ledger. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 52 +- docs/architecture/design.md | 4 +- docs/development/README.md | 6 +- .../inventory-capacity-registration.md | 639 ++++++++---------- docs/operations/physical-inventory.md | 9 +- 5 files changed, 337 insertions(+), 373 deletions(-) diff --git a/config/README.md b/config/README.md index 8a36c5e2..55020bb5 100644 --- a/config/README.md +++ b/config/README.md @@ -9,42 +9,45 @@ entitlements, ServiceAvailability resources, and publication rules must referenc `metal`. See the [API architecture](../docs/architecture/README.md) for group separation and breaking alpha rename constraints. -The repository publishes two production manifest roots. They target different -API servers and must be reconciled independently. +The repository publishes Milo and management-cluster manifest roots. They +target different API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | -| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook | +| `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook. Devices can be deleted. | +| `config/milo-production` | Milo root control plane (production-style) | `config/milo` plus Device deletion protection | | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | -The synthetic staging overlay explicitly excludes the inert-registration -service and its retention policies. Pair it with `config/milo-synthetic` in a -**separate non-production Milo control plane**, not production `config/milo`. -That root preserves the pre-registration synthetic API contract. There is no -request field, actor exemption, or runtime switch that bypasses production -registration admission. Never point synthetic lifecycle handlers at the -production registration authority or its private ledger. +`config/components/device-deletion-protection` is an optional component: a +ValidatingAdmissionPolicy and binding that deny every Device `DELETE`, with no +exemptions. Each environment chooses whether to install it. Production-style +Milo control planes use `config/milo-production`; test, staging and synthetic +control planes that need Device deletions use `config/milo` or +`config/milo-synthetic`. `hack/validate-overlay-isolation.sh` rejects any other +root that renders the policy. Namespace and project deletions that reach a +protected Device stay stuck rather than deleting it; see +[Device deletion protection](../docs/development/inventory-capacity-registration.md#device-deletion-protection). + +The synthetic staging overlay excludes the inert-registration service. Pair it +with `config/milo-synthetic` in a **separate non-production Milo control +plane**, not production `config/milo`. That root preserves the +pre-registration synthetic API contract. There is no request field, actor +exemption, or runtime switch that bypasses production registration admission. The one `fleet-manager` Deployment serves every Milo project that consumes the `metal` service; see [project discovery](#project-discovery). -The [signed expansion and transport-first contract](../docs/development/registration-storage-rollout.md) -defines the required operator public-key ConfigMap, retained segments, activation -gate, byte budgets and ordered parent infrastructure work. Pod TCP readiness is -transport-only; it must not enable UI registration. - The separate `fleet-registration` Deployment serves inert inventory-backed -capacity admission only. Its TLS trust, read/SAR credentials, webhook serving CA -and one-time private ledger bootstrap are environment-owned. Read the +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 [registration rollout contract](../docs/development/inventory-capacity-registration.md#production-packaging-and-rollout) -before applying either root: an unavailable authority blocks capacity writes -globally, and fences Device writes and protected lifetime deletions in provider -or ambiguous inventory contexts. Admission-time trusted-context conditions keep -proven unrelated Project inventory independent of webhook availability. All four webhook -entries require the same serving CA and endpoint; their scope must match the -private ledger, which must never be reset by GitOps. This does not enable -production allocation or provisioning. +before applying either root: an unavailable service blocks capacity writes +globally, and nothing else. Pod TCP readiness is transport-only; it must not +enable UI registration. This does not enable production allocation or +provisioning. `config/components/service-catalog-staging` is a Kustomize component with staging's Bare Metal prices: committed servers and server setup, which @@ -122,6 +125,7 @@ Render both production roots before publishing the Kustomize bundle: ```sh kustomize build config/milo >/dev/null +kustomize build config/milo-production >/dev/null kustomize build config/milo-synthetic >/dev/null kustomize build config/overlays/management-plane >/dev/null kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/docs/architecture/design.md b/docs/architecture/design.md index f44765d7..7ee559f7 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -20,8 +20,8 @@ preserves provenance and outstanding review points; the original discussions rem The implemented [stage-1 registration decision](../development/inventory-capacity-registration.md) allows explicitly unconfigured cleaning only for inert Disabled/Retain records. -It uses a separate private CAS ledger and project-plane admission, not allocation -custody or provider enrollment. Enabling and preparation remain forbidden until +It uses stateless project-plane admission against live Devices, plus optional +Device deletion protection, not allocation custody or provider enrollment. Enabling and preparation remain forbidden until their policy resolution and authorization contracts are implemented. ## Problem and intended outcome diff --git a/docs/development/README.md b/docs/development/README.md index e486d2bb..d4ccb76d 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -20,9 +20,9 @@ event-driven Machine allocation, contention, cleanup, and reuse through the public project API. Production caller-preserving allocation admission, replayable Milo event adapters, and production provider integration are not implemented. Inert [inventory-backed capacity registration](inventory-capacity-registration.md) -now has a caller-preserving admission service, a separate CAS registration -ledger, exact-incarnation recovery, and a session-fenced default-namespace Device -picker. It admits only Disabled/Retain records with cleaning explicitly +now has a stateless caller-preserving admission service that checks live +Devices, one capacity per Device through a Device-derived name, optional Device +deletion protection, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly unconfigured; deployment trust inputs and live Milo acceptance remain required. An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 976716fd..5278d81c 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -9,18 +9,48 @@ name-derived Device reference, invented cleaning default, allocation checkbox, and unrestricted frontend create helper remain removed. Existing capacity listing and legacy values remain visible; no existing object is migrated. -## Public contract and authority +## Decision: no registration ledger + +An earlier revision kept a private ledger in host-cluster Secrets. Its job was +to remember Device identities after a Device was deleted, and it grew into +tombstones, incarnation fences, permanent alias retention, `Unknown` outcomes, +a mutable tail with sealed segments, signed expansion and activation, epochs +and growth limits. The user decided this was overengineering and replaced it +with the following: + +1. **Devices are not deleted.** An optional ValidatingAdmissionPolicy denies + every Device `DELETE`. An environment decides whether to install it; see + [Device deletion protection](#device-deletion-protection). +2. **No signed activation.** The bootstrap/activation gate, `/activationz`, + `/status`, the operator control key and ConfigMap, + `cmd/fleet-registration-control` and signed controls are gone. The + registration webhook is an ordinary fail-closed webhook (`failurePolicy: + Fail`) with mutual TLS, scoped credentials and least privilege. +3. **Registration checks live objects.** The webhook keeps no state. It + checks the live Device and capacities through the API server on every + request. + +Rationale: when Devices are never deleted, the live Device list already holds +every identity the ledger used to remember, so a second store adds failure +modes without adding information. Environments that need to delete Devices, +such as test and synthetic environments, do not hold real machines and do not +need permanent identity retention. -The staff form selects an existing `Device` in `default`, retains its UID and -resourceVersion as an immutable selection baseline, and authors an independent -capacity name. It POSTs to the existing provider project's `MachineCapacity` -API using the staff portal's caller-preserving proxy. `spec.deviceRef` remains -a name-only reference. It must not be a generated capacity name masquerading as -a Device name. +## Public contract and authority -The only admitted new capacity contract is: +The staff form selects an existing `Device` in `default` and keeps its UID and +resourceVersion as an immutable selection baseline. It POSTs to the provider +project's `MachineCapacity` API through the staff portal's caller-preserving +proxy. The admitted create is: ```yaml +metadata: + name: device- + namespace: default + annotations: + fleet.datumapis.com/registration-device-uid: + fleet.datumapis.com/registration-device-version: + fleet.datumapis.com/registration-operation: spec: deviceRef: {name: selected-device} allocationPolicy: Disabled @@ -28,348 +58,273 @@ spec: cleaningPolicyRef: {name: ""} ``` +`spec.deviceRef` remains a name-only reference. The capacity name is no longer +authored: it is `device-` followed by the Device UID (43 characters). This +changes the earlier contract, where staff typed an independent name. All other +fields and the three annotations are unchanged. The annotations are request +preconditions and traceability, not authentication or ownership proofs. The +operation ID is no longer used for deduplication. + An empty cleaning-policy name explicitly means **unconfigured**, not a policy -named `default`, synthetic cleaning, or authorization to prepare. The CRD permits -it only while Disabled. The production admission handler rejects *all* capacity -updates, status updates and deletes, including setting a nonempty policy and -enabling in the same request. Real policy resolution and policy-use authorization +named `default`, synthetic cleaning, or authorization to prepare. The CRD +permits it only while Disabled. The webhook rejects *all* capacity updates, +status updates and deletes. Real policy resolution and policy-use authorization are future prerequisites for a separately designed transition; there is no -stage-1 preparation endpoint. Legacy nonempty cleaning references remain valid -in the schema and synthetic lifecycle environments remain separate. - -Three protected request-precondition annotations carry the selected UID, -selected resourceVersion and stable client operation ID: -`fleet.datumapis.com/registration-device-uid`, -`fleet.datumapis.com/registration-device-version`, and -`fleet.datumapis.com/registration-operation`. They are not authentication or -ownership proofs. A create with copied annotations still goes through the full -admission protocol; updates and deletion cannot remove or replace them. The -private ledger, not these public annotations, binds the exact capacity UID. - -`cmd/fleet-registration` serves a validating admission webhook. Its production -implementation uses Milo's authenticated `iam.miloapis.com/parent-*` extras, -requires a single Project context and an actor UID, and resolves the current -Project UID through the root Milo client. It does not use a project, actor or -permission bypass from request annotations. Separate SubjectAccessReviews pass -through the caller's username, UID, groups and extras for current -`machinecapacities.create` and named `devices.get` in `default`. Permission errors, -denials, missing identity and incomplete evaluations fail closed. Both checks -are repeated before reservation, alongside uncached Device and namespace -lifetime/version reads. Controller credentials supply reads and SAR evaluation, -not the caller's registration authority. +stage-1 preparation endpoint. + +`cmd/fleet-registration` serves the validating webhook. For each create it: + +1. requires Milo's authenticated `iam.miloapis.com/parent-*` extras naming a + single Project in the configured provider scope, and an actor UID; +2. requires the `default` namespace, the exact shape above, and a name equal + to `device-`; +3. resolves the current Project lifetime through the root Milo client; +4. runs SubjectAccessReviews with the caller's username, UID, groups and + extras for `machinecapacities.create` and named `devices.get` in + `default`. Denials, errors and incomplete evaluations fail closed. This + happens before the Device is read, so an unauthorized caller cannot learn + whether a Device exists; +5. reads the Device uncached. A missing Device is denied. Its UID and + resourceVersion must equal the annotations, and it must not be deleting; +6. requires both a non-placeholder serial and a canonical system UUID, and a + complete provider host reference when one is present; +7. lists Devices and capacities in **all namespaces of every configured + provider project** and denies when: + - another Device shares a normalized alias (below); + - any capacity already references this Device by name or by its UID + annotation; + - any capacity has unresolved physical identity, so non-conflict cannot be + established; or + - any capacity is backed by a Device that shares an alias. + +The webhook writes nothing. Dry-run requests are evaluated like real ones +(`sideEffects: None`). Controller credentials supply reads and SAR evaluation, +not the caller's registration authority. Errors about records in another +provider project do not name them. The webhook accepts only mutually authenticated TLS from a dedicated API-server client CA. Do not use a broad tenant/client CA: an AdmissionReview received from -an untrusted client is not evidence of an authenticated actor. The server also -checks the installed root webhook configuration at signed activation and before admission: -the exact write rules, explicit serving CA, Fail policy, common authority -endpoint, and the restricted match conditions described below. Label selectors, -missing fences, expanded rules, and conditions differing from the configured -provider scope are rejected. Scope changes require an operator-coordinated -manifest and ledger migration, not caller-selected labels or annotations. - -## Physical identity and bounded deduplication - -The complete operator-configured provider-project list and Milo authority are -fixed in one private ledger. All replicas, names and projects in that scope use -the same resourceVersion CAS. Configuration must match the retained scope -exactly; changing the list requires an explicit ledger migration, not a restart -with a smaller list. The packaged UI and deployment use `datum-cloud`. - -Eligible Devices must have **both** a recorded non-placeholder serial and a -canonical non-placeholder system UUID. The canonical asset key is the digest of -`uuid:` plus that UUID. Known reservation aliases include the digests of the -normalized serial, UUID, and, when present, provider host system/type/ID tuple. -Normalization trims and lowercases values; conservative false-positive -collisions require operator investigation rather than choosing a winner. -MAC addresses, BMC endpoints, installation claims, rack placement and asset tags -are not canonical chassis identifiers in this stage. - -Every known alias is claimed in the same CAS transaction. A second Device with -any shared alias, including inconsistent serial/UUID pairs or a shared provider -host reference, is ambiguous and is rejected rather than merged or adopted. -Before reservation the handler reads Devices and capacities in **all namespaces -of every configured provider project**. Existing unresolved legacy capacity -blocks new registration because non-conflict cannot be established. Existing -capacity bound to a conflicting asset blocks it regardless of allocation -policy or reported readiness. None of these records or allocations is changed. +an untrusted client is not evidence of an authenticated actor. + +## Physical identity and duplicates + +Aliases are the digests of the normalized serial, system UUID and, when +present, provider host system/type/ID tuple. Normalization trims and lowercases +values. A shared alias between two Devices, including inconsistent +serial/UUID pairs, is ambiguous: registration is denied for both until a person +resolves the duplicate. Neither is merged or adopted. MAC addresses, BMC +endpoints, installation claims, rack placement and asset tags are not chassis +identifiers in this stage. This is **not universal physical deduplication** or proof of real hardware -identity. Serial-only and UUID-only records cannot prove the same hardware in -the absence of shared evidence; neither can be selected for registration. -Different fabricated or incomplete identifiers, assets outside the configured -provider scope, and physical equipment absent from inventory cannot be compared -reliably. Recording identity does not establish physical verification or -ownership. Production allocation remains disabled independently. - -## Serialization and recovery - -`fleet-capacity-registration-v1` is a separate host-cluster Secret in -`fleet-system-private`; it is **not** allocation custody. The service updates only -that root and can create/read immutable retained segments under the host policy. -The [storage and bootstrap protocol](registration-storage-rollout.md) adds signed -lossless expansion and deny-only transport startup. Its JSON retains the actor, exact -API-normalized create object, admission request UID, client operation ID, -Project/namespace lifetimes, Device UID/resourceVersion, aliases, canonical key, -and API-assigned capacity UID **before allowing the public create**. Kubernetes -assigns that UID before validating admission; envtest verifies a caller-supplied -UID is replaced and the retained UID matches the actual result. - -CAS conflicts repeat authorization and observation before another reservation -attempt. No public object, allocation, status, provider, networking, or cleaning -write is performed by the registration service. Capacity persistence is the -original caller's API-server operation. All new entries start `Unknown` because -another admission plugin, API storage failure, timeout or crash can still prevent -the create. A failed CAS response may itself have committed: it is not released. - -Device creation also reserves its known aliases before admission completes. -Device deletion retains a permanent UID tombstone before admission completes. -Both use the same ledger CAS, closing the registration-versus-pending-create or -delete race. Potentially changing Device updates retain their old resourceVersion -before admission completes. Registration rejects a selected version with such an update fence; -only an explicitly selected newer persisted version can pass it. This serializes -pending metadata/spec updates with registration without silently refreshing the -selection. The sole exception is a provably unchanged update: the complete old -and new admission JSON objects are equal, including metadata, managed fields, -status and any fields unknown to Fleet's typed Device. JSON key order and -whitespace are immaterial; numbers are compared without floating-point rounding. -An unchanged Kubernetes update can keep its existing resourceVersion, and must -not permanently fence that still-current version. This exception adds no new -reservation and **never removes an existing pending-update fence**. It does not -infer success from a later read, refresh a selected version, or relax identity -and registered-spec checks. Any differing field still takes the conservative -fencing path. An uncertain potentially changing update can therefore leave its -old version ineligible even if storage ultimately made no change. Failed Device -creates can likewise retain an alias reservation. -Update fences are coalesced to one record per provider Project and Device UID, -not one per observation. Before replacing a retained version, admission reads -the Device directly through the uncached project client and requires the current -UID and resourceVersion to equal both incoming update incarnations/baselines. -It rejects stale admissions rather than replacing a newer pending fence. The -ledger snapshot precedes that authoritative read; a competing ledger write -forces a full CAS retry and another Device read. All concurrent updates at the -same baseline share its fence. Once the API server has persisted a newer version, -optimistic concurrency prevents an older-baseline write from subsequently -committing; an API-server storage retry must re-enter admission at its new -baseline. Thus superseded fences can be compacted without allowing an unfinished -current-baseline update to race registration. ResourceVersions are compared only -for equality, never ordered numerically. - -Coalescing unions creation aliases and never clears a deletion tombstone. -A deletion replaces update history with a permanent all-version tombstone; -later changing updates for that UID are rejected. Older-build multiple-version -records are compacted only when this same authoritative update check succeeds, -or when deletion installs a stronger permanent tombstone. Unrelated incarnations -are untouched. An unknown/rejected write at the still-current version stays -fenced, including after restart and no-op updates. Recovery still requires a -genuine persisted change and explicit new selection, not automatic ledger cleanup. -The selected Device's own successful creation reservation is not a conflict. -Identity/provider-alias changes are forbidden; registered Device specs are -frozen, and its deletion and same-name replacement are forbidden. The default -provider namespace and configured provider Project deletions are denied. - -Recovery observes the exact retained capacity UID, namespace and Project -lifetimes, Device incarnation, aliases and authored input. An exact observed -object becomes `Recorded`, which means only that the inert record exists. -Absence remains `Unknown`; replacement or lifetime loss is a conflict/tombstone, -never adoption. Recovery never creates, deletes, retries under a different name, -or publishes positive readiness. It runs every 30 seconds and after restart; -CAS conflicts leave evidence retained for a later observation. Repeating POST -is not the recovery mechanism: inspect the original name and retained operation. - -Reservations and tombstones have no automatic expiry or release path in stage 1. -This deliberately includes create attempts that never persisted and deleted -Devices that were never registered: their known hardware aliases remain reserved, -and recreating that hardware under a new UID fails closed. Stage 1 has no safe -operator release command. Future reconciliation must prove the original outcome, -all competing operations and lifetime ownership before designing a fenced release; -neither manual Secret editing nor speculative expiry is an accepted workaround. - -Routine updates to an incarnation use one record with at most one pending -resourceVersion, retained aliases and a deletion bit. This bounds growth by -distinct incarnations/aliases and registration operations, **not** by elapsed -collector observations. It is not an unlimited-inventory or universal deduplication -guarantee: retained incarnations and reservations can still fill the pilot ledger. -The mutable tail refuses growth past 650,000 encoded bytes (the boundary fits), -leaving sealing headroom. Signed expansion seals up to sixteen immutable segments; -existing v1 tails up to 750,000 bytes can migrate losslessly. This is bounded growth, -not unlimited capacity, alias expiry, or permission to increase caps. -Admission makes at most six CAS attempts with complete reevaluation after conflicts; -exhaustion emits a structured error with project, operation identity and attempt -count, without actor credentials or ledger contents. Lost or corrupt -ledger state, scope changes, uncertain operations and full ledgers require -operator-led reconciliation/migration; deleting or recreating the ledger is not -a repair. Ledger update protection and private-namespace deletion protection -are installed in the host cluster. Cluster administrators who can remove those -fences or restore arbitrary storage remain outside the guarantee. +identity. Hardware outside the provider scope or absent from inventory cannot +be compared. Recording identity does not establish physical verification or +ownership. + +### One capacity per Device + +Two creates for the same Device carry the same derived name, so the API server +rejects the second with `AlreadyExists` even when both pass admission +concurrently. The webhook also refuses a Device that a legacy capacity already +references under another name. A replacement Device created under a deleted +Device's name is refused too, because the old capacity still references that +name. + +### The documented duplicate race + +The duplicate check is a point-in-time list. It does not close this race: + +- Device A is being registered while Device B, which shares A's serial, is + being created. If B is not yet visible when A's registration lists Devices, + A's capacity is admitted. + +No reservation store closes this, by decision. The consequences are bounded: + +- B can never be registered, because A now exists and shares its alias. +- A's capacity is `Disabled`, and the webhook denies every capacity update, so + it can never become available in stage 1. +- The staff registration form lists every Device and marks each one that + shares an alias with another as **Conflicting**, so both A and B show the + conflict until a person resolves it. +- Any future transition that enables capacity must recheck duplicates against + live Devices at that time. + +Two registrations racing for two already-existing Devices that share an alias +both fail, because each sees the other Device. Device status has no writer +today, so there is no server-side eligibility condition to set; reporting +conflicts through Device status is a follow-up. + +## Device deletion protection + +`config/components/device-deletion-protection` is a Kustomize component with a +ValidatingAdmissionPolicy and binding named `fleet-device-deletion-protection`. +It denies every `DELETE` on `devices.fleet.datumapis.com` (all versions, all +namespaces) with `failurePolicy: Fail` and reason `Forbidden`. + +- **Where it is installed.** Devices are stored and admitted by the Milo + control plane: `config/components/inventory` registers the CRD there, and + records live in provider projects. The component therefore belongs with the + Milo root, not the management-cluster host overlays, which have no Device + CRD. Like the registration webhook, it is installed at the Milo root and + relies on Milo running its root admission policies for project-routed + requests (pinned Milo `v0.36.9` enables the `ValidatingAdmissionPolicy` + plugin). Confirm this on the deployed Milo before relying on it. +- **Which roots include it.** `config/milo-production` is `config/milo` plus + the component, and is the production-style root. `config/milo` (consumed by + staging and test control planes that need Device deletion), + `config/milo-synthetic`, `config/inventory`, `config/standalone` and every + host overlay leave it out. `hack/validate-overlay-isolation.sh` fails if a + production-style root lacks it, or if any other root renders it. +- **No exemptions.** No user, group or service account is exempt, including + cluster administrators. The escape hatch is an environment not installing + the component. Anyone able to delete the binding is outside the guarantee. +- **deletecollection.** The API server admits each object of a collection + delete individually as a `DELETE`, so a collection delete that includes a + Device fails and leaves Devices in place. Other objects in the same call may + already be gone. +- **Garbage collection and finalizers.** Owner-reference cascades issue the + same `DELETE` and are denied. Because the `DELETE` is denied, a Device never + gets a deletion timestamp, so finalizers never run. +- **Namespace and project deletion (fail-closed: stays stuck).** A policy + cannot see what a namespace contains, so it does not block the namespace + `DELETE`. The namespace becomes `Terminating`, the namespace controller + deletes the other contents, and its Device deletions are denied. The + namespace stays `Terminating` with its Devices intact and readable; it + accepts no new objects. Milo keeps `default` undeletable, and Milo's project + purge drains `default` in place and reports remaining Devices as blockers on + the Project. So deleting a provider project stops with its Devices in place. + Other inventory in that namespace or project (for example DeviceClaims) is + still deleted before the cascade stops. Capacity is not, because the + registration webhook denies capacity deletes. Do not delete namespaces or + projects that hold Devices. +- **Remediation for a stuck namespace or project.** Kubernetes cannot cancel + a namespace deletion. Either leave it `Terminating`, which keeps every + Device, or have the environment owner deliberately decide to give up those + identities: remove the binding, let the cascade finish, and reinstall the + component. The second option loses the Device records and their duplicate + protection, so it is an explicit ownership decision, not routine repair. +- **Retirement.** A machine leaving service keeps its Device. Its capacity is + already `Disabled` and cannot be changed, which is the only retirement state + stage 1 has. Devices have no lifecycle or retirement field (see + [Planning and registering physical devices](../operations/physical-inventory.md)). + A Device retirement state is a follow-up. + +### Deleting a Device where deletion is allowed + +Without the component, deleting a Device that backs capacity leaves the +capacity in place, still `Disabled`. The webhook denies every update and +delete of it, so it cannot become available. No owner reference links the two: +the webhook rejects owner references on registration, and garbage collection +would be denied anyway because capacity deletes are fenced. The orphaned +capacity keeps its Device UID annotation and name, which also prevents a +replacement Device with the same name from registering. Clean it up only in +environments where capacity writes are not fenced, such as synthetic ones. ## Production packaging and rollout -- `config/milo` includes the mandatory Fail-closed registration webhook on the - **actual project resource path**, not just a manager-side helper. Four separate - admission entries use the same endpoint. Capacity create/update/delete/status - remains globally fenced. Device create/update/delete/status excludes only - proven unrelated Project contexts (in **all namespaces**, because alias scans - cover all of them). Namespace deletion matches only `default` in protected or - ambiguous contexts. Project deletion matches only exact configured provider Project - names, including root requests without parent extras. Unnamed collection - deletion cannot prove exclusion of protected lifetimes and is explicitly - denied (including when transport is healthy); delete unrelated lifetimes by - exact name instead. No object-label opt-in or opt-out exists. -- `config/overlays/management-plane` includes a separate two-replica registration - Deployment, TLS Service, narrowly scoped host RBAC, and private retention - policies. It does not enable production lifecycle handlers. -- The webhook consumes parent context from Milo's standard admission extras. - The API server evaluates the inventory/lifetime CEL match conditions **before - webhook transport**. An unreachable service or incomplete certificate rollout - therefore cannot block unrelated consumers' Device writes, other namespaces, - or unrelated Project deletions through these entries. In-scope writes remain - Fail-closed during transport failure; capacity writes remain globally blocked. - Handler-side exemptions alone are not an outage-isolation boundary. -- These conditions rely on **server-established routing context**, not arbitrary - identity-provider claims. In pinned Milo `v0.36.9`, - `ProjectRouterWithRequestInfo` establishes the project from the routed path; - `ProjectContextAuthorizationDecorator` overwrites all three parent extras - after authentication/impersonation and before authorization/admission - (`cmd/milo/apiserver/config.go`). The pinned filter regression verifies that - conflicting caller extras are overwritten while actor identity is preserved. - Only a singleton `Project` / `resourcemanager.miloapis.com` / nonempty name - outside the protected list proves that inventory is unrelated and skips the - webhook. Missing, malformed, root, Organization and User inventory contexts - remain fail-closed. This conservative fallback matters: pinned Milo's later - Organization/User decorators can obscure the Project extras for nested paths; - a non-Project context must not be mistaken for proof of unrelated storage. - Regression tests exercise those actual pinned decorators and the resulting - admission matching. Root Project deletion still uses only exact protected - names; other namespace names remain outside the namespace fence. - This scope is **not safe on a server that lets caller-supplied extras replace - its actual routing context**, or exposes an alternate provider-storage path - appearing as a different valid Project. Confirm these properties on the - deployed Milo path before enabling use. Unscoped/root Device writes are not - supported by this pilot; that is an explicit fail-closed limit, not universal - outage isolation for every possible inventory route. -- Legacy capacity writes in configured production scope fail closed; legacy - records remain readable and unchanged. Outside configured provider scope, - ordinary inventory writes are unaffected, but new capacity writes are denied. - The synthetic/standalone test APIs do not install this production webhook. - Pair the synthetic staging overlay with `config/milo-synthetic` on a separate - non-production API server; that overlay excludes registration workloads and - retention policies. Never use these synthetic roots in production or share - the registration authority's ledger. This is deployment isolation, not a - caller-selected bypass. - -Environment-owned inputs are required, just as for the existing manager. No -real credentials or certificates are supplied by this repository: - -1. Preserve the existing `fleet-manager-config` authority and discovery paths. - Supply separate `fleet-registration-milo-kubeconfig` and - `fleet-registration-project-kubeconfig` Secrets at the mounted paths. The root - credential needs Project reads and registration webhook-configuration reads; - the project credential needs Device and capacity get/list across the complete - scope, namespace get, and SubjectAccessReview create. It needs **no public - capacity or Device writes**, allocation permissions or provider credentials. -2. Supply `fleet-registration-tls` with `tls.crt`, `tls.key`, and a dedicated - `client-ca.crt`. Configure Milo's admission webhook client kubeconfig with an - API-server client certificate signed by that CA. Patch the webhook URL for - actual cross-cluster reachability and set every entry's - `clientConfig.caBundle` to the serving CA. All four entries must have the same - client configuration. No empty or guessed trust defaults are accepted. -3. Install the host retention policies. Bootstrap the ledger **once**, using - create, never apply/upsert, with environment-matching authority and sorted - projects. Its initial JSON has `authority`, `projects`, `entries: []` and - `deviceFences: []`. It is intentionally absent from GitOps resources so a - later reconcile cannot overwrite accumulated reservations. Do not label it - as legacy allocation custody (`fleet.datumapis.com/private-record`). -4. Quiesce provider inventory/capacity writes while installing the root webhook - and service. Validate the complete provider scope and legacy inventory before - reopening writes. Unavailable TLS, credentials, ledger or service leave - in-scope writes blocked. The API server must support webhook CEL match - conditions; preserve the packaged conditions, including the exact sorted - provider-name lists matching `--provider-projects` and the private ledger. - Do not replace them with namespace/object label selectors. A missing or - mismatched fence also prevents registration startup/admission; this does not - authorize unquiesced partial installation or deletion of admission policy. - Readiness is process reachability, not asset eligibility. +- `config/milo` includes the mandatory fail-closed registration webhook + (`config/components/registration-admission`). Its one entry matches + capacity create/update/delete and status in every namespace, with no + selectors or match conditions. An unreachable service blocks capacity + writes globally and nothing else: Device, namespace and Project writes do + not pass through the registration webhook. +- `config/milo-production` adds Device deletion protection. +- `config/overlays/management-plane` includes a separate two-replica + registration Deployment and TLS Service. The pod does not mount a service + account token and has no host RBAC. It does not enable production lifecycle + handlers. +- The synthetic staging overlay excludes the registration workload; pair it + with `config/milo-synthetic`, which installs neither the webhook nor the + deletion policy. Never use synthetic roots in production. +- The handler trusts parent context from Milo's admission extras. In pinned + Milo `v0.36.9`, `ProjectRouterWithRequestInfo` establishes the project from + the routed path and `ProjectContextAuthorizationDecorator` overwrites the + parent extras before authorization and admission. The pinned filter + regression verifies that conflicting caller extras are overwritten while + actor identity is preserved, and that nested Organization/User contexts do + not present as a Project. Only a singleton + `Project`/`resourcemanager.miloapis.com` context is accepted. +- Legacy capacity writes fail closed; legacy records remain readable and + unchanged. + +Environment-owned inputs, none of which this repository supplies: + +1. Keep the existing `fleet-manager-config` authority and discovery paths. + Supply `fleet-registration-milo-kubeconfig` (Project reads) and + `fleet-registration-project-kubeconfig` (Device and capacity get/list + across the complete provider scope, and SubjectAccessReview create). It + needs no public writes, allocation permissions or provider credentials. +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. +4. Choose the Milo root: `config/milo-production` to forbid Device deletion, + or `config/milo` to allow it. 5. Before rolling out the UI, verify caller-preserving project routing, named - Device read denial, registration denial, direct write/status/delete fences, - TLS rejection, and duplicate concurrency in the target environment. This - change performs **no live writes or deployment**, so it does not claim those - environment-specific checks have been performed. - -## UI and verification - -The Datum dialog uses the existing real host-session boundary and isolated read -cache. Missing host authority, denied registration, unavailable Devices and -partial identity have explicit explanations. Selecting a Device snapshots its -baseline; neither refetch nor visible browser-chrome blur/focus changes it. A -named current read immediately precedes dispatch. Session changes fence pending -work. After dispatch, uncertain results retain the authored name and disable -retry; the existing unfenced legacy deletion helper is never used for rollback. - -Tests cover concurrent CAS, serial/UUID/provider aliases and provider projects, -stale UID/RV, Device deletion fences, namespace/Project recreation, permission -revocation, unknown commit and restart, copied-annotation incarnation conflicts, -real API-assigned UID binding, direct mutation fences and no public effects. -Regression coverage also includes real successful unchanged updates retaining -their RV followed by `Recorded` registration, genuine-edit/stale-selection -controls, preservation of pending real-update fences, and transport-outage -isolation for Device writes and namespace/Project deletion. The original reviewer -reproduction is retained byte-for-byte in -`internal/registration/testdata/review_adversarial_test.go.txt`; it is evidence, -not an executable regression because it asserts the former outage failure and -assumes the no-op registration failed before its same-asset control. Derived -regressions use separate assets and assert the corrected behavior. -Envtest exercises the production authorization function against real SARs, -the packaged validating webhook, and the host retention policies against a -disposable API server. The outage regression uses a minimal Project CRD solely -to exercise root deletion admission and disables envtest's built-in -NamespaceLifecycle plugin so its independent ban on deleting `default` cannot -mask the webhook test. It uses dry-run deletion for shared `default`, and actual -deletion for unrelated namespaces/Projects. This does not alter production -admission plugins. The trust-boundary test imports the pinned Milo routing -filters (their test-build transitive dependencies are now recorded in `go.mod`). -TLS tests reject unauthenticated webhook transport. It is not a live Milo -deployment or independent security review. Frontend tests use real session -components and mocked transport. Run the existing Go/envtest, race, vet, -provider/consumer test/typecheck/build, manifest-isolation and documentation -checks described in the [development guide](README.md#build-test-and-run). - -Boundedness regressions perform 120 successive persisted collector observations -and 120 metadata updates through the packaged webhook, assert one incarnation -fence and stable ledger size, then register the current selection and recover it -to `Recorded`. The disposable Device CRD adds a test-only integer status observation -because the current production `DeviceStatus` is empty; this exercises real -`/status` storage and admission without inventing a production collector API. -Deterministic interleavings retain a newer pending fence while stale admission -retries, and keep unknown/rejected baselines fenced across restart/no-op requests. -An envtest race pauses two admitted updates at successive resourceVersions: after -coalescing, the older in-flight update conflicts at actual API-server storage, -the newer pending version remains unregistrable, and only its persisted successor -can be explicitly selected and recorded. -Real API-server Secret conflicts exercise success after five conflicts and six-conflict -exhaustion/logging. Separate tests assert the exact size boundary and effect-free -dry-run denial. - -The publishing workflow applies the server build tag to `config/base/registration`, -as it does to the manager. A regression reads the workflow's image transforms, -applies them to a temporary config tree, and renders the management-plane bundle -to assert that `/fleet-registration` uses the published server image tag rather -than `latest`. It also verifies registration remains absent from synthetic staging. -Raw source manifests still contain template `latest` references: direct deployment -must supply equivalent immutable build-tag or digest transforms, plus the required -trust/credential configuration. No published bundle or live deployment was tested. - -### Review-fix validation, November 22, 2026 - -- Full `go test -race ./...` with Kubernetes 1.37.0 envtest assets, `go vet ./...`, - and `go build ./cmd/...` pass locally. -- Provider tests: 693 pass; consumer tests: 44 pass. Both typechecks and builds - pass. One initial provider timing failure under concurrent validation load - passed on a full rerun without modifying UI code or reviewer tests. -- Production and synthetic manifest renders, overlay isolation tests, - standalone/synthetic render checks, documentation links and whitespace pass. -- The bounded-fencing rework adds real delayed-update and Secret-contention races, - exact-size/dry-run guards, repeated status-write bounds, and rendered publishing - image-transform checks. The original reviewer reproduction remains byte-identical. -- These are local checks, not live Milo acceptance or independent re-review. - No deployment, merge, live resource mutation, or ledger migration was performed. + Device read denial, registration denial, capacity mutation denial, TLS + rejection, Device deletion denial where installed, and duplicate handling + in the target environment. This change performs **no live writes or + deployment**, so it does not claim those checks. + +Removing the ledger deletes nothing live. An environment that bootstrapped the +old `fleet-capacity-registration-v1` Secret, its segments, the +`fleet-registration-control` ConfigMap, or the old retention policies keeps +those objects until its owner removes them; the new service ignores them. + +## UI + +The Datum dialog uses the existing host-session boundary and isolated read +cache. It shows the derived capacity name instead of a name field. Missing +host authority, denied registration, unavailable Devices, partial identity and +conflicting identities have explicit explanations. Selecting a Device +snapshots its baseline; neither refetch nor browser blur/focus changes it. A +named current read immediately precedes dispatch. Session changes fence +pending work. After dispatch, an uncertain result keeps the selection, disables +retry in that form, and asks the operator to check whether the derived capacity +exists. A repeat cannot create a second record. The unfenced legacy deletion +helper is never used for rollback. + +## Verification + +Run with Kubernetes 1.37.0 envtest assets: + +```sh +KUBEBUILDER_ASSETS="$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" go test -race -count=1 ./... +./hack/validate-overlay-isolation.sh Date: Sun, 22 Nov 2026 16:49:08 -0600 Subject: [PATCH 05/16] feat(api): add a Device lifecycle field Add spec.lifecycle to Device with Active (the CRD default), Decommissioning and Retired. CRD transition rules on spec allow Active and Decommissioning to move between each other and Decommissioning to move to Retired. Active to Retired is rejected and nothing leaves Retired, including by removing the field, which defaults back to Active. Creation in any lifecycle is allowed. The CRD is hand-maintained YAML; this repository has no CRD generator, so the schema and its offline tests change together. Co-Authored-By: Claude Opus 5.5 --- .../inventory/crds/fleet.datumapis.com.yaml | 13 ++++ .../api/inventory/v1alpha1/lifecycle_test.go | 78 +++++++++++++++++++ internal/api/inventory/v1alpha1/types.go | 23 ++++++ 3 files changed, 114 insertions(+) create mode 100644 internal/api/inventory/v1alpha1/lifecycle_test.go diff --git a/config/components/inventory/crds/fleet.datumapis.com.yaml b/config/components/inventory/crds/fleet.datumapis.com.yaml index d020afd6..f4e942ee 100644 --- a/config/components/inventory/crds/fleet.datumapis.com.yaml +++ b/config/components/inventory/crds/fleet.datumapis.com.yaml @@ -219,6 +219,9 @@ spec: - name: Serial type: string jsonPath: .spec.identity.serial + - name: Lifecycle + type: string + jsonPath: .spec.lifecycle - name: System UUID type: string priority: 1 @@ -289,7 +292,17 @@ spec: - rule: '!has(self.serviceAssociations) || (has(self.components) && self.serviceAssociations.all(a, self.components.exists(c, c.id == a.componentID)))' message: service associations must reference present components + - rule: '!has(oldSelf.lifecycle) || oldSelf.lifecycle != ''Retired'' || (has(self.lifecycle) && self.lifecycle + == ''Retired'')' + message: Retired is terminal; a Retired Device cannot change lifecycle + - rule: '!has(self.lifecycle) || self.lifecycle != ''Retired'' || (has(oldSelf.lifecycle) && oldSelf.lifecycle + in [''Decommissioning'', ''Retired''])' + message: move an Active Device to Decommissioning before Retired properties: + lifecycle: + type: string + enum: [Active, Decommissioning, Retired] + default: Active deviceTypeRef: type: object required: diff --git a/internal/api/inventory/v1alpha1/lifecycle_test.go b/internal/api/inventory/v1alpha1/lifecycle_test.go new file mode 100644 index 00000000..c6413816 --- /dev/null +++ b/internal/api/inventory/v1alpha1/lifecycle_test.go @@ -0,0 +1,78 @@ +package v1alpha1 + +import "testing" + +func lifecycleDevice(t *testing.T, lifecycle DeviceLifecycle) map[string]any { + t.Helper() + device := syntheticDevice() + device.Spec.Lifecycle = lifecycle + return object(t, device) +} + +func TestDeviceLifecycleDefaultsToActive(t *testing.T) { + device := lifecycleDevice(t, "") + if errs := admit(t, "Device", device, nil); len(errs) > 0 { + t.Fatal(errs) + } + if got := device["spec"].(map[string]any)["lifecycle"]; got != string(DeviceActive) { + t.Fatalf("unset lifecycle defaulted to %v, want Active", got) + } + if got := LifecycleOf(&Device{}); got != DeviceActive { + t.Fatalf("LifecycleOf(unset) = %q, want Active", got) + } + if errs := admit(t, "Device", lifecycleDevice(t, "Unknown"), nil); len(errs) == 0 { + t.Fatal("an unknown lifecycle value was accepted") + } +} + +func TestDeviceLifecycleTransitions(t *testing.T) { + for _, test := range []struct { + from, to DeviceLifecycle + allowed bool + }{ + {DeviceActive, DeviceActive, true}, + {DeviceActive, DeviceDecommissioning, true}, + {DeviceDecommissioning, DeviceActive, true}, + {DeviceDecommissioning, DeviceDecommissioning, true}, + {DeviceDecommissioning, DeviceRetired, true}, + {DeviceRetired, DeviceRetired, true}, + // An unset value is Active, before and after. + {"", DeviceDecommissioning, true}, + {DeviceDecommissioning, "", true}, + {DeviceActive, DeviceRetired, false}, + {"", DeviceRetired, false}, + {DeviceRetired, DeviceActive, false}, + {DeviceRetired, DeviceDecommissioning, false}, + // Removing the field defaults it to Active, so it is not a way out. + {DeviceRetired, "", false}, + } { + errs := admit(t, "Device", lifecycleDevice(t, test.to), lifecycleDevice(t, test.from)) + if allowed := len(errs) == 0; allowed != test.allowed { + t.Errorf("%q -> %q: allowed = %v, want %v (%v)", test.from, test.to, allowed, test.allowed, errs) + } + } +} + +// TestRetiredDeviceStillAcceptsOtherEdits pins that the terminal rule only +// freezes lifecycle, so a Retired record can still be corrected. +func TestRetiredDeviceStillAcceptsOtherEdits(t *testing.T) { + old := syntheticDevice() + old.Spec.Lifecycle = DeviceRetired + edited := syntheticDevice() + edited.Spec.Lifecycle = DeviceRetired + edited.Spec.AssetTag = "asset-0001" + if errs := admit(t, "Device", object(t, edited), object(t, old)); len(errs) > 0 { + t.Fatalf("edit of a Retired Device rejected: %v", errs) + } +} + +// TestDeviceMayBeCreatedInAnyLifecycle pins that transition rules apply to +// updates only: a record of hardware already out of service may be created +// as such. +func TestDeviceMayBeCreatedInAnyLifecycle(t *testing.T) { + for _, lifecycle := range []DeviceLifecycle{DeviceActive, DeviceDecommissioning, DeviceRetired} { + if errs := admit(t, "Device", lifecycleDevice(t, lifecycle), nil); len(errs) > 0 { + t.Errorf("create as %s rejected: %v", lifecycle, errs) + } + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go index 4b34b5bb..651ae98e 100644 --- a/internal/api/inventory/v1alpha1/types.go +++ b/internal/api/inventory/v1alpha1/types.go @@ -102,6 +102,29 @@ type DeviceSpec struct { // UnmappedMACAddresses are MACs detected on the asset that the registrar // could not attribute to a named interface. UnmappedMACAddresses []string `json:"unmappedMACAddresses,omitempty"` + // Lifecycle is the asset's service state. The CRD defaults it to Active and + // allows Active and Decommissioning to move between each other and + // Decommissioning to move to Retired, which is terminal. Only an Active + // Device can back new capacity. + Lifecycle DeviceLifecycle `json:"lifecycle,omitempty"` +} + +// DeviceLifecycle is the service state of a Device. +type DeviceLifecycle string + +const ( + DeviceActive DeviceLifecycle = "Active" + DeviceDecommissioning DeviceLifecycle = "Decommissioning" + DeviceRetired DeviceLifecycle = "Retired" +) + +// LifecycleOf returns the Device's lifecycle, treating an unset value as +// Active, which is the CRD default. +func LifecycleOf(device *Device) DeviceLifecycle { + if device.Spec.Lifecycle == "" { + return DeviceActive + } + return device.Spec.Lifecycle } type ReportedPlacement struct { From 671ddb170c9beed2278fd0cec6ecf9186cfada9f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:14 -0600 Subject: [PATCH 06/16] feat(registration): require an Active Device Registration admits new capacity only for an Active Device. A capacity update that would leave Disabled while its Device is Decommissioning or Retired is denied for that reason, after checking that the caller can read the Device; every other update keeps the stage-1 denial. Retired Devices still take part in the duplicate-identity scan while they exist. Co-Authored-By: Claude Opus 5.5 --- internal/registration/admission.go | 47 +++++++++- internal/registration/envtest_test.go | 104 ++++++++++++---------- internal/registration/lifecycle_test.go | 113 ++++++++++++++++++++++++ 3 files changed, 213 insertions(+), 51 deletions(-) create mode 100644 internal/registration/lifecycle_test.go diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 0982a8b8..526cdf25 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -111,8 +111,8 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a if request.Resource.Group != metal.GroupVersion.Group || request.Resource.Resource != "machinecapacities" { return admission.Denied("unsupported registration admission resource") } - if request.Operation != admissionv1.Create || request.SubResource != "" { - return admission.Denied("capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation") + if request.SubResource != "" || (request.Operation != admissionv1.Create && request.Operation != admissionv1.Update) { + return admission.Denied(mutationDisabled) } name, err := projectName(request.UserInfo) if err != nil { @@ -121,12 +121,52 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a if !slices.Contains(handler.Projects, name) { return admission.Denied("project is outside the configured provider registration scope") } + if request.Operation == admissionv1.Update { + return admission.Denied(handler.evaluateUpdate(ctx, name, request).Error()) + } if err := handler.evaluate(ctx, name, request); err != nil { return admission.Denied(err.Error()) } return admission.Allowed("inert inventory registration only; no availability or preparation authority") } +const mutationDisabled = "capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation" + +// evaluateUpdate explains why a capacity update is denied. Stage 1 denies +// every update. An update that would move capacity out of Disabled for a +// Device that is not Active is denied for that reason first, so the rule +// already holds when a future stage allows enabling capacity. It always +// returns an error. +func (handler *Handler) evaluateUpdate(ctx context.Context, name string, request admission.Request) error { + var capacity metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &capacity); err != nil { + return err + } + if capacity.Spec.AllocationPolicy == "Disabled" { + return errors.New(mutationDisabled) + } + project, err := handler.Resolve(ctx, name) + if err != nil || !project.Identity.Valid() || project.Identity.RouteName != name { + return errors.New("provider project lifetime is unavailable") + } + // The API server has authorized the capacity update itself. Reading the + // backing Device additionally requires the caller to be able to read it. + if err := handler.Authorize(ctx, project, request.UserInfo, inventory.GroupVersion.Group, "devices", capacity.Spec.DeviceRef.Name); err != nil { + return err + } + device := &inventory.Device{} + if err := project.Client.Get(ctx, client.ObjectKey{Namespace: request.Namespace, Name: capacity.Spec.DeviceRef.Name}, device); err != nil { + if apierrors.IsNotFound(err) { + return errors.New("capacity cannot leave Disabled: its Device does not exist") + } + return errors.New("capacity cannot leave Disabled: its Device is unavailable") + } + if lifecycle := inventory.LifecycleOf(device); lifecycle != inventory.DeviceActive { + return fmt.Errorf("capacity cannot leave Disabled: its Device is %s; only an Active Device can back available capacity", lifecycle) + } + return errors.New(mutationDisabled) +} + func (handler *Handler) evaluate(ctx context.Context, name string, request admission.Request) error { if request.Namespace != InventoryNamespace { return errors.New("registration requires the default inventory namespace") @@ -176,6 +216,9 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis if device.UID != types.UID(annotations[DeviceUIDAnnotation]) || device.ResourceVersion != annotations[DeviceVersionAnnotation] || !device.DeletionTimestamp.IsZero() { return errors.New("selected Device incarnation or version changed; do not silently refresh the selection") } + if lifecycle := inventory.LifecycleOf(device); lifecycle != inventory.DeviceActive { + return fmt.Errorf("selected Device is %s; only an Active Device can be registered as capacity", lifecycle) + } if !eligible(device) { return errors.New("registration requires non-placeholder serial, canonical system UUID, and complete provider aliases; incomplete identity is ambiguous") } diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index 7332f72b..734161ed 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -91,6 +91,29 @@ func (api *liveAPI) device(name, namespace, serial, uuid string) *inventory.Devi return device } +func (api *liveAPI) updateLifecycle(device *inventory.Device, lifecycle inventory.DeviceLifecycle) error { + api.t.Helper() + if err := api.admin.Get(context.Background(), client.ObjectKeyFromObject(device), device); err != nil { + api.t.Fatal(err) + } + device.Spec.Lifecycle = lifecycle + return api.admin.Update(context.Background(), device) +} + +func (api *liveAPI) setLifecycle(device *inventory.Device, lifecycle inventory.DeviceLifecycle) { + api.t.Helper() + if err := api.updateLifecycle(device, lifecycle); err != nil { + api.t.Fatal(err) + } +} + +// retire takes a Device through the only allowed path to Retired. +func (api *liveAPI) retire(device *inventory.Device) { + api.t.Helper() + api.setLifecycle(device, inventory.DeviceDecommissioning) + api.setLifecycle(device, inventory.DeviceRetired) +} + // installWebhook serves the production handler behind the packaged webhook // configuration and returns the server so a test can take it away. func (api *liveAPI) installWebhook() *httptest.Server { @@ -301,7 +324,7 @@ func TestRegistrationAgainstLiveDevices(t *testing.T) { } registered.Spec.AllocationPolicy = "Enabled" registered.Spec.CleaningPolicyRef.Name = "invented-policy" - if err := operator.Update(ctx, registered); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "mutation and deletion are disabled") { + if err := operator.Update(ctx, registered); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "cannot leave Disabled: its Device does not exist") { t.Fatalf("orphaned capacity was enabled: %v", err) } if err := operator.Delete(ctx, registered); !apierrors.IsForbidden(err) { @@ -311,57 +334,40 @@ func TestRegistrationAgainstLiveDevices(t *testing.T) { requireDenied(t, operator.Create(ctx, api.registration(replacement)), "already backs capacity") }) - cascade := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "cascade"}} - if err := api.admin.Create(ctx, cascade); err != nil { - t.Fatal(err) - } - cascaded := api.device("cascaded", "cascade", "cascade-serial", "77777777-7777-7777-7777-777777777777") - sibling := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "sibling", Namespace: "cascade"}} - if err := api.admin.Create(ctx, sibling); err != nil { - t.Fatal(err) - } - api.installDeletionProtection(duplicateA) - - t.Run("installed component denies Device DELETE for every caller", func(t *testing.T) { - for _, caller := range []client.Client{api.admin, operator} { - if err := caller.Delete(ctx, duplicateA); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), "cannot be deleted") { - t.Fatalf("Device deletion: %v", err) - } - } - if !api.exists(duplicateA) { - t.Fatal("Device removed despite deletion protection") - } - }) - t.Run("deletecollection is denied per Device", func(t *testing.T) { - if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("default")); !apierrors.IsForbidden(err) { - t.Fatalf("deletecollection: %v", err) - } - for _, device := range []*inventory.Device{duplicateA, duplicateB, legacyBacked, limitedTarget} { - if !api.exists(device) { - t.Fatalf("deletecollection removed %s", device.Name) - } - } + t.Run("only an Active Device can be registered", func(t *testing.T) { + decommissioning := api.device("decommissioning", "default", "decommissioning-serial", "99999999-9999-9999-9999-999999999991") + api.setLifecycle(decommissioning, inventory.DeviceDecommissioning) + requireDenied(t, operator.Create(ctx, api.registration(decommissioning)), "selected Device is Decommissioning") + retired := api.device("retired", "default", "retired-serial", "99999999-9999-9999-9999-999999999992") + api.retire(retired) + requireDenied(t, operator.Create(ctx, api.registration(retired)), "selected Device is Retired") + // A Retired Device still holds its identity while it exists. + twin := api.device("retired-twin", "default", "RETIRED-SERIAL", "99999999-9999-9999-9999-999999999993") + requireDenied(t, operator.Create(ctx, api.registration(twin)), "shares recorded hardware identity") }) - t.Run("namespace deletion stays Terminating with its Devices", func(t *testing.T) { - if err := api.admin.Delete(ctx, cascade); err != nil { - t.Fatal(err) - } - // envtest runs no namespace controller. Issue the same content - // deletions the controller would: deletecollection, then per item. - if err := api.admin.DeleteAllOf(ctx, &corev1.ConfigMap{}, client.InNamespace("cascade")); err != nil { + t.Run("capacity of a Decommissioning or Retired Device cannot leave Disabled", func(t *testing.T) { + device := api.device("leaving-service", "default", "leaving-serial", "99999999-9999-9999-9999-999999999994") + registered := api.registration(device) + if err := operator.Create(ctx, registered); err != nil { t.Fatal(err) } - if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("cascade")); !apierrors.IsForbidden(err) { - t.Fatalf("namespace cascade deletecollection: %v", err) - } - if err := api.admin.Delete(ctx, cascaded); !apierrors.IsForbidden(err) { - t.Fatalf("namespace cascade item deletion: %v", err) - } - if !api.exists(cascaded) || api.exists(sibling) { - t.Fatal("cascade must stop at Devices while other content drains") - } - if !api.exists(cascade) || cascade.DeletionTimestamp.IsZero() { - t.Fatal("namespace must remain Terminating") + enable := func() error { + current := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), current); err != nil { + t.Fatal(err) + } + current.Spec.AllocationPolicy = "Enabled" + current.Spec.CleaningPolicyRef.Name = "invented-policy" + return operator.Update(ctx, current) + } + requireDenied(t, enable(), "mutation and deletion are disabled") + api.setLifecycle(device, inventory.DeviceDecommissioning) + requireDenied(t, enable(), "its Device is Decommissioning") + api.setLifecycle(device, inventory.DeviceRetired) + requireDenied(t, enable(), "its Device is Retired") + current := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), current); err != nil || current.Spec.AllocationPolicy != "Disabled" { + t.Fatalf("capacity left Disabled: %v %q", err, current.Spec.AllocationPolicy) } }) t.Run("webhook outage blocks only capacity writes", func(t *testing.T) { diff --git a/internal/registration/lifecycle_test.go b/internal/registration/lifecycle_test.go new file mode 100644 index 00000000..c4b1e6f8 --- /dev/null +++ b/internal/registration/lifecycle_test.go @@ -0,0 +1,113 @@ +package registration + +import ( + "context" + "errors" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" + authenticationv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +func setLifecycle(t *testing.T, handler *Handler, device *inventory.Device, lifecycle inventory.DeviceLifecycle) { + t.Helper() + device.Spec.Lifecycle = lifecycle + if err := providerClient(t, handler).Update(context.Background(), device); err != nil { + t.Fatal(err) + } +} + +func TestRegistrationRequiresAnActiveDevice(t *testing.T) { + for _, lifecycle := range []inventory.DeviceLifecycle{inventory.DeviceDecommissioning, inventory.DeviceRetired} { + t.Run(string(lifecycle), func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, lifecycle) + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "selected Device is "+string(lifecycle)) { + t.Fatalf("registration of a %s Device: %+v", lifecycle, response.Result) + } + }) + } + t.Run("explicit Active", func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, inventory.DeviceActive) + if response := handler.Handle(context.Background(), registrationRequest(t, device)); !response.Allowed { + t.Fatalf("registration of an Active Device denied: %s", response.Result.Message) + } + }) +} + +// TestRetiredDeviceStillBlocksDuplicates pins that a Retired Device keeps its +// identity in the duplicate check for as long as it exists. +func TestRetiredDeviceStillBlocksDuplicates(t *testing.T) { + handler, device := fixture(t) + retired := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "retired", Namespace: "default", UID: "device-2"}, Spec: inventory.DeviceSpec{Lifecycle: inventory.DeviceRetired, Identity: inventory.DeviceIdentity{Serial: " serial-1", SystemUUID: "22222222-2222-2222-2222-222222222222", Model: "test"}}} + if err := providerClient(t, handler).Create(context.Background(), retired); err != nil { + t.Fatal(err) + } + response := handler.Handle(context.Background(), registrationRequest(t, device)) + if response.Allowed || !strings.Contains(response.Result.Message, "shares recorded hardware identity") { + t.Fatalf("registration beside a Retired duplicate: %+v", response.Result) + } +} + +func capacityUpdate(t *testing.T, device *inventory.Device, policy string) admission.Request { + t.Helper() + request := registrationRequest(t, device) + old := request.Object + changeCapacity(&request, func(capacity *metal.MachineCapacity) { capacity.Spec.AllocationPolicy = policy }) + request.Operation = admissionv1.Update + request.OldObject = old + return request +} + +func TestCapacityCannotLeaveDisabledForInactiveDevice(t *testing.T) { + for _, lifecycle := range []inventory.DeviceLifecycle{inventory.DeviceDecommissioning, inventory.DeviceRetired} { + t.Run(string(lifecycle), func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, lifecycle) + response := handler.Handle(context.Background(), capacityUpdate(t, device, "Enabled")) + if response.Allowed || !strings.Contains(response.Result.Message, "its Device is "+string(lifecycle)) { + t.Fatalf("enabling capacity of a %s Device: %+v", lifecycle, response.Result) + } + }) + } + // Stage 1 still denies every update, so an Active Device, or an update that + // stays Disabled, gets the general denial. + for name, test := range map[string]struct { + lifecycle inventory.DeviceLifecycle + policy string + }{ + "Active enabled": {inventory.DeviceActive, "Enabled"}, + "Retired staying Disabled": {inventory.DeviceRetired, "Disabled"}, + "Decommissioning unchanged": {inventory.DeviceDecommissioning, "Disabled"}, + } { + t.Run(name, func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, test.lifecycle) + response := handler.Handle(context.Background(), capacityUpdate(t, device, test.policy)) + if response.Allowed || response.Result.Message != mutationDisabled { + t.Fatalf("capacity update: %+v", response.Result) + } + }) + } + t.Run("caller without Device read learns nothing", func(t *testing.T) { + handler, device := fixture(t) + setLifecycle(t, handler, device, inventory.DeviceRetired) + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + if resource == "devices" { + return errors.New("get permission on devices is required") + } + return nil + } + response := handler.Handle(context.Background(), capacityUpdate(t, device, "Enabled")) + if response.Allowed || strings.Contains(response.Result.Message, "Retired") { + t.Fatalf("capacity update without Device read: %+v", response.Result) + } + }) +} From a84a15c03aa48cd7dae35beb0f4baf26946f7eb2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:24 -0600 Subject: [PATCH 07/16] feat(config): opt-in delete policy for Retired Production-specific configuration belongs to the deploying repository, so remove the config/milo-production root. The device-deletion-protection component stays as a reusable component that no root here includes. The policy now admits a Device DELETE only when namespaceObject has a deletion timestamp (null-guarded, so a missing namespace denies) or the deleted Device is Retired. Everything else is denied with a message to move the Device to Decommissioning, then Retired. It keeps failurePolicy Fail, Deny only, and no subject checks or exemptions. The overlay isolation validator renders the component on its own and requires that exact policy and binding, fails if any root here renders the policy under any name, and fails if the inventory component exists without the deletion component. Fixtures cover a root including the component and the policy renamed, audit-only, warn-only, fail-open, scoped, exempted or given a weaker rule. envtest applies the component and checks Active and Decommissioning deletes are denied, Retired deletes pass, deletecollection over mixed Devices denies the non-retired ones, and Devices of a deleting namespace can be deleted. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 1 - .../kustomization.yaml | 5 +- .../device-deletion-protection/policy.yaml | 31 ++-- config/milo-production/kustomization.yaml | 9 - hack/overlay-isolation-validator.go | 99 ++++++++--- hack/test-overlay-isolation.sh | 63 +++++-- .../registration/deletion_envtest_test.go | 160 ++++++++++++++++++ 7 files changed, 307 insertions(+), 61 deletions(-) delete mode 100644 config/milo-production/kustomization.yaml create mode 100644 internal/registration/deletion_envtest_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0fbf0da4..d537961b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,6 @@ jobs: - run: go run ./test/acceptance/milo/cmd validate --root . - run: kustomize build config/base/crd >/dev/null - run: kustomize build config/milo >/dev/null - - run: kustomize build config/milo-production >/dev/null - run: kustomize build config/milo-synthetic >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/config/components/device-deletion-protection/kustomization.yaml b/config/components/device-deletion-protection/kustomization.yaml index 03bc082f..a0d79d9e 100644 --- a/config/components/device-deletion-protection/kustomization.yaml +++ b/config/components/device-deletion-protection/kustomization.yaml @@ -1,5 +1,6 @@ -# Optional: install wherever Device objects are admitted (the Milo control -# plane) in environments that must never lose a Device. See +# Reusable and opt-in: no root in this repository includes it. A deploying +# repository that must keep in-service Devices adds it to the root it applies +# to the Milo control plane, where Devices are admitted. See # docs/development/inventory-capacity-registration.md#device-deletion-protection. apiVersion: kustomize.config.k8s.io/v1alpha1 kind: Component diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml index bc69125e..0de29e95 100644 --- a/config/components/device-deletion-protection/policy.yaml +++ b/config/components/device-deletion-protection/policy.yaml @@ -1,9 +1,16 @@ -# Devices are never deleted where this component is installed. Retire a -# machine through its capacity staying Disabled instead. The API server runs -# admission once per object for deletecollection, garbage collection and -# namespace or project cleanup, so every one of those paths is denied too. -# There are no exemptions: an environment that needs Device deletion does not -# install this component. +# A Device is deleted only after it is Retired, so a Device in service stays +# visible to duplicate-hardware checks. Retire a Device by moving +# spec.lifecycle to Decommissioning and then Retired; the CRD rejects every +# other path to Retired, and Retired is terminal. +# +# The one other exception is a Device whose namespace is being deleted +# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace is +# the privileged escape hatch: it lets the namespace controller finish and +# takes its Devices with it. Nothing keys off who makes the request, and there +# are no exemptions. The API server runs admission once per object for +# deletecollection, garbage collection and namespace cleanup, so each of those +# paths is held to the same rule. A missing namespace object or an evaluation +# error denies the request (failurePolicy: Fail). apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: @@ -18,12 +25,16 @@ spec: operations: [DELETE] resources: [devices] validations: - - expression: 'false' + - expression: >- + (namespaceObject != null && has(namespaceObject.metadata) && + has(namespaceObject.metadata.deletionTimestamp)) || + (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && + oldObject.spec.lifecycle == 'Retired') reason: Forbidden message: >- - Devices cannot be deleted in this environment. Their identity must stay - visible to duplicate-hardware checks. Leave the Device in place and - keep its capacity Disabled. + Only a Retired Device can be deleted. Move the Device to Decommissioning, + then Retired, first; its identity must stay visible to duplicate-hardware + checks while it is in service. --- apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding diff --git a/config/milo-production/kustomization.yaml b/config/milo-production/kustomization.yaml deleted file mode 100644 index c3a66020..00000000 --- a/config/milo-production/kustomization.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# Production-style Milo root: config/milo plus Device deletion protection. -# Environments that need Device deletions, such as test and staging control -# planes, consume config/milo instead. -apiVersion: kustomize.config.k8s.io/v1beta1 -kind: Kustomization -resources: - - ../milo -components: - - ../components/device-deletion-protection diff --git a/hack/overlay-isolation-validator.go b/hack/overlay-isolation-validator.go index 6ffe60eb..e524df59 100644 --- a/hack/overlay-isolation-validator.go +++ b/hack/overlay-isolation-validator.go @@ -27,14 +27,24 @@ const ( localProjectStandIn = "fleet.datumapis.com/local-project-stand-in" sharedNamespace = "fleet.datumapis.com/shared-with-standalone" - // Device deletion protection is optional per environment. Only the - // production-style roots below may render it, and they must. + // Device deletion protection is a reusable component that deploying + // repositories opt into. No root in this repository may render it, and the + // component rendered alone must be the exact fail-closed policy. deletionProtection = "fleet-device-deletion-protection" deletionProtectionComponent = "components/device-deletion-protection" + // inventoryComponent defines the Device CRD. A config tree that has it + // must also ship the deletion protection component. + inventoryComponent = "components/inventory" + + // deletionProtectionExpression is the only admitted rule: a Device DELETE + // passes when its namespace is being deleted or it is Retired. It is + // compared with whitespace normalized. + deletionProtectionExpression = `(namespaceObject != null && has(namespaceObject.metadata) && +has(namespaceObject.metadata.deletionTimestamp)) || +(oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && +oldObject.spec.lifecycle == 'Retired')` ) -var deletionProtectedRoots = []string{"milo-production"} - type kustomization struct { Resources []string `json:"resources"` Components []string `json:"components"` @@ -88,12 +98,11 @@ func main() { if err := checkDeletionProtection("standalone", standaloneObjects, false); err != nil { fatalf("render %s: %v", standaloneRoot, err) } + componentPresent := false if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(deletionProtectionComponent))); err == nil { - for _, root := range deletionProtectedRoots { - if _, err := os.Stat(filepath.Join(configRoot, root)); err != nil { - fatalf("production-style root %s must exist and install Device deletion protection: %v", root, err) - } - } + componentPresent = true + } else if _, err := os.Stat(filepath.Join(configRoot, filepath.FromSlash(inventoryComponent))); err == nil { + fatalf("%s defines Devices, so %s must exist for deploying repositories to opt into", inventoryComponent, deletionProtectionComponent) } entries, err := discover(configRoot) @@ -101,7 +110,7 @@ func main() { if len(entries) == 0 { fatalf("no Kustomize entry points found below %s", configRoot) } - checked := 0 + checked, componentChecked := 0, false for _, entry := range entries { root := filepath.Dir(entry) if v.definitionRoot(root) { @@ -124,9 +133,7 @@ func main() { check(err) relative = filepath.ToSlash(relative) required := relative == deletionProtectionComponent - for _, protected := range deletionProtectedRoots { - required = required || relative == protected - } + componentChecked = componentChecked || required if err := checkDeletionProtection(relative, objects, required); err != nil { fatalf("render %s: %v", root, err) } @@ -134,6 +141,9 @@ func main() { if checked == 0 { fatalf("no non-standalone Kustomize entry point was validated") } + if componentPresent && !componentChecked { + fatalf("%s was not rendered on its own", deletionProtectionComponent) + } } func (v *validator) definitionRoot(path string) bool { @@ -287,9 +297,9 @@ func (v *validator) checkObject(object *unstructured.Unstructured) error { return nil } -// checkDeletionProtection requires the exact deny-all Device DELETE policy and -// its binding in production-style roots, and forbids either object anywhere -// else, so test and synthetic roots keep Device deletion available. +// checkDeletionProtection requires the exact Device DELETE policy and its +// binding when the component is rendered alone, and forbids either object in +// every other root: deploying repositories opt in, this repository does not. func checkDeletionProtection(root string, objects []*unstructured.Unstructured, required bool) error { var policy, binding *unstructured.Unstructured for _, object := range objects { @@ -309,26 +319,29 @@ func checkDeletionProtection(root string, objects []*unstructured.Unstructured, } if !required { if policy != nil || binding != nil { - return fmt.Errorf("%s renders Device deletion protection; only %v may install %s", root, deletionProtectedRoots, deletionProtectionComponent) + return fmt.Errorf("%s renders Device deletion protection; no root in this repository may include %s, deploying repositories opt in", root, deletionProtectionComponent) } return nil } if policy == nil || binding == nil { - return fmt.Errorf("production-style root %s must install the Device deletion policy and its binding", root) + return fmt.Errorf("%s must render the Device deletion policy and its binding", root) } failurePolicy, _, _ := unstructured.NestedString(policy.Object, "spec", "failurePolicy") validations, _, _ := unstructured.NestedSlice(policy.Object, "spec", "validations") - _, hasConditions := policy.Object["spec"].(map[string]any)["matchConditions"] - if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || hasConditions || len(validations) != 1 { + spec := policy.Object["spec"].(map[string]any) + _, hasConditions := spec["matchConditions"] + _, hasVariables := spec["variables"] + _, hasParams := spec["paramKind"] + if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || !unscopedConstraints(policy) || hasConditions || hasVariables || hasParams || len(validations) != 1 { return fmt.Errorf("%s: Device deletion policy must fail closed, match DELETE on devices and have no exemptions", root) } - if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); expression != "false" { - return fmt.Errorf("%s: Device deletion policy must deny every DELETE", root) + if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); strings.Join(strings.Fields(expression), " ") != strings.Join(strings.Fields(deletionProtectionExpression), " ") { + return fmt.Errorf("%s: Device deletion policy must allow DELETE only for a Retired Device or a deleting namespace", root) } actions, _, _ := unstructured.NestedStringSlice(binding.Object, "spec", "validationActions") _, hasMatch := binding.Object["spec"].(map[string]any)["matchResources"] - _, hasParams := binding.Object["spec"].(map[string]any)["paramRef"] - if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParams { + _, hasParamRef := binding.Object["spec"].(map[string]any)["paramRef"] + if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParamRef { return fmt.Errorf("%s: Device deletion binding must Deny in every namespace", root) } return nil @@ -349,6 +362,44 @@ func policyMatchesDeviceDelete(policy *unstructured.Unstructured) bool { return false } +// unscopedConstraints reports whether the policy's match constraints apply to +// every namespace and object, with no exclusions or name restrictions. +func unscopedConstraints(policy *unstructured.Unstructured) bool { + constraints, _, _ := unstructured.NestedMap(policy.Object, "spec", "matchConstraints") + for _, key := range []string{"namespaceSelector", "objectSelector", "excludeResourceRules"} { + if value, found := constraints[key]; found && !emptyValue(value) { + return false + } + } + rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") + for _, raw := range rules { + rule, ok := raw.(map[string]any) + if !ok { + return false + } + if names, found := rule["resourceNames"]; found && !emptyValue(names) { + return false + } + if scope, found := rule["scope"]; found && scope != "*" && scope != "Namespaced" { + return false + } + } + return true +} + +func emptyValue(value any) bool { + switch typed := value.(type) { + case nil: + return true + case map[string]any: + return len(typed) == 0 + case []any: + return len(typed) == 0 + default: + return false + } +} + func contains(values []string, value string) bool { for _, candidate := range values { if candidate == value { diff --git a/hack/test-overlay-isolation.sh b/hack/test-overlay-isolation.sh index 6d0ec68f..95211c24 100755 --- a/hack/test-overlay-isolation.sh +++ b/hack/test-overlay-isolation.sh @@ -417,22 +417,31 @@ EOF expect_failure "intentional Kustomize build failure" "missing.yaml" rm -rf "$fixture_root/config/overlays/broken" -# Device deletion protection is per environment: only production-style roots -# may render it, and once the component exists they must. -mkdir -p "$fixture_root/config/components/device-deletion-protection" -cp "$repo_root/config/components/device-deletion-protection/kustomization.yaml" "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/" -expect_failure "deletion component without a production-style root" "production-style root milo-production must exist" +# Device deletion protection is a reusable component that deploying +# repositories opt into. No root in this repository may render it, and the +# component rendered alone must be the exact fail-closed policy. +component="$fixture_root/config/components/device-deletion-protection" +policy="$repo_root/config/components/device-deletion-protection/policy.yaml" +mkdir -p "$fixture_root/config/components/inventory" +cat >"$fixture_root/config/components/inventory/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../../base/safe] +EOF +expect_failure "Device inventory without the deletion component" "must exist for deploying repositories to opt into" +mkdir -p "$component" +cp "$repo_root/config/components/device-deletion-protection/kustomization.yaml" "$policy" "$component/" +"$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" + mkdir -p "$fixture_root/config/milo-production" cat >"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: [../base/safe] -EOF -expect_failure "production-style root without deletion protection" "must install the Device deletion policy and its binding" -cat >>"$fixture_root/config/milo-production/kustomization.yaml" <<'EOF' components: [../components/device-deletion-protection] EOF -"$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" +expect_failure "fleet root including the deletion component" "milo-production renders Device deletion protection" +rm -rf "$fixture_root/config/milo-production" mkdir -p "$fixture_root/config/overlays/synthetic-with-protection" cat >"$fixture_root/config/overlays/synthetic-with-protection/kustomization.yaml" <<'EOF' apiVersion: kustomize.config.k8s.io/v1beta1 @@ -440,19 +449,43 @@ kind: Kustomization resources: [../../base/safe] components: [../../components/device-deletion-protection] EOF -expect_failure "test or synthetic root installing deletion protection" "renders Device deletion protection" +expect_failure "nested fleet root including the deletion component" "renders Device deletion protection" rm -rf "$fixture_root/config/overlays/synthetic-with-protection" mkdir -p "$fixture_root/config/overlays/renamed-protection" -sed 's/name: fleet-device-deletion-protection/name: renamed-device-guard/; s/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/overlays/renamed-protection/policy.yaml" +sed 's/name: fleet-device-deletion-protection/name: renamed-device-guard/; s/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' "$policy" >"$fixture_root/config/overlays/renamed-protection/policy.yaml" cat >"$fixture_root/config/overlays/renamed-protection/kustomization.yaml" <<'EOF' apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: [policy.yaml] EOF -expect_failure "renamed Device deletion policy outside production roots" "renders Device deletion protection" +expect_failure "renamed Device deletion policy copied into a fleet root" "renders Device deletion protection" rm -rf "$fixture_root/config/overlays/renamed-protection" -sed 's/validationActions: \[Deny\]/validationActions: [Audit]/' "$repo_root/config/components/device-deletion-protection/policy.yaml" >"$fixture_root/config/components/device-deletion-protection/policy.yaml" -expect_failure "audit-only Device deletion binding" "must Deny in every namespace" -cp "$repo_root/config/components/device-deletion-protection/policy.yaml" "$fixture_root/config/components/device-deletion-protection/policy.yaml" + +# Each weakening below is rendered through the component itself. +weakened() { + description=$1 + expected=$2 + shift 2 + sed "$@" "$policy" >"$component/policy.yaml" + if cmp -s "$policy" "$component/policy.yaml"; then + echo "$description fixture did not change the policy" >&2 + exit 1 + fi + expect_failure "$description" "$expected" + cp "$policy" "$component/policy.yaml" +} +weakened "renamed Device deletion policy" "components/device-deletion-protection: Device deletion policy must fail closed" -e '1,/kind: ValidatingAdmissionPolicyBinding/s/name: fleet-device-deletion-protection/name: renamed-device-guard/' +weakened "renamed Device deletion policy and binding" "components/device-deletion-protection must render the Device deletion policy and its binding" -e 's/name: fleet-device-deletion-protection/name: renamed-device-guard/' -e 's/policyName: fleet-device-deletion-protection/policyName: renamed-device-guard/' +weakened "audit-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Audit]/' +weakened "warn-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Warn]/' +weakened "fail-open Device deletion policy" "must fail closed" -e 's/failurePolicy: Fail/failurePolicy: Ignore/' +weakened "always-true Device deletion expression" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/oldObject.spec.lifecycle == 'Retired')/oldObject.spec.lifecycle == 'Retired') || true/" +weakened "Decommissioning Device deletion allowed" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/== 'Retired')/!= 'Active')/" +weakened "namespace-scoped Device deletion policy" "must fail closed" -e 's/ matchPolicy: Equivalent/ matchPolicy: Equivalent\ + namespaceSelector: {matchLabels: {protected: "true"}}/' +weakened "subject exemption in Device deletion policy" "must fail closed" -e 's/^ validations:/ matchConditions:\ + - name: not-admin\ + expression: "request.userInfo.username != '\''admin'\''"\ + validations:/' "$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" diff --git a/internal/registration/deletion_envtest_test.go b/internal/registration/deletion_envtest_test.go new file mode 100644 index 00000000..9a2dbbca --- /dev/null +++ b/internal/registration/deletion_envtest_test.go @@ -0,0 +1,160 @@ +package registration + +import ( + "context" + "fmt" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const deletionDenied = "Only a Retired Device can be deleted" + +func (api *liveAPI) namespace(name string) *corev1.Namespace { + api.t.Helper() + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}} + if err := api.admin.Create(context.Background(), namespace); err != nil { + api.t.Fatal(err) + } + return namespace +} + +// TestDeviceLifecycleTransitionsAgainstLiveAPI runs the CRD transition rules +// in a real API server. +func TestDeviceLifecycleTransitionsAgainstLiveAPI(t *testing.T) { + api := startAPI(t) + device := api.device("lifecycle", "default", "lifecycle-serial", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1") + if device.Spec.Lifecycle != inventory.DeviceActive { + t.Fatalf("created Device lifecycle = %q, want the Active default", device.Spec.Lifecycle) + } + rejected := func(to inventory.DeviceLifecycle, message string) { + t.Helper() + if err := api.updateLifecycle(device, to); !apierrors.IsInvalid(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("transition to %s: %v", to, err) + } + } + rejected(inventory.DeviceRetired, "move an Active Device to Decommissioning before Retired") + api.setLifecycle(device, inventory.DeviceDecommissioning) + api.setLifecycle(device, inventory.DeviceActive) + api.setLifecycle(device, inventory.DeviceDecommissioning) + api.setLifecycle(device, inventory.DeviceRetired) + rejected(inventory.DeviceActive, "Retired is terminal") + rejected(inventory.DeviceDecommissioning, "Retired is terminal") + rejected("", "Retired is terminal") + api.setLifecycle(device, inventory.DeviceRetired) +} + +// TestDeviceDeletionProtection applies the component's manifests as a +// deploying repository that opts in would, and checks every deletion path. +func TestDeviceDeletionProtection(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + active := api.device("active", "default", "active-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1") + decommissioning := api.device("decommissioning", "default", "decommissioning-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb2") + api.setLifecycle(decommissioning, inventory.DeviceDecommissioning) + retired := api.device("retired", "default", "retired-serial", "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb3") + api.retire(retired) + + api.namespace("mixed") + mixed := map[string]inventory.DeviceLifecycle{"mixed-active": inventory.DeviceActive, "mixed-decommissioning": inventory.DeviceDecommissioning, "mixed-retired-a": inventory.DeviceRetired, "mixed-retired-b": inventory.DeviceRetired} + mixedDevices := map[string]*inventory.Device{} + suffix := 0 + for name, lifecycle := range mixed { + suffix++ + device := api.device(name, "mixed", name+"-serial", fmt.Sprintf("cccccccc-cccc-4ccc-8ccc-%012d", suffix)) + switch lifecycle { + case inventory.DeviceDecommissioning: + api.setLifecycle(device, lifecycle) + case inventory.DeviceRetired: + api.retire(device) + } + mixedDevices[name] = device + } + + teardown := api.namespace("teardown") + teardownActive := api.device("teardown-active", "teardown", "teardown-active-serial", "dddddddd-dddd-4ddd-8ddd-ddddddddddd1") + teardownDecommissioning := api.device("teardown-decommissioning", "teardown", "teardown-decommissioning-serial", "dddddddd-dddd-4ddd-8ddd-ddddddddddd2") + api.setLifecycle(teardownDecommissioning, inventory.DeviceDecommissioning) + + api.installDeletionProtection(active) + operator := api.actor("operator", "system:masters") + + t.Run("Active and Decommissioning Devices cannot be deleted by any caller", func(t *testing.T) { + for _, device := range []*inventory.Device{active, decommissioning} { + for _, caller := range []client.Client{api.admin, operator} { + if err := caller.Delete(ctx, device); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) || !strings.Contains(err.Error(), "Decommissioning, then Retired") { + t.Fatalf("deleting %s: %v", device.Name, err) + } + } + if !api.exists(device) { + t.Fatalf("%s removed despite deletion protection", device.Name) + } + } + }) + t.Run("a Retired Device can be deleted", func(t *testing.T) { + if err := operator.Delete(ctx, retired); err != nil { + t.Fatalf("deleting a Retired Device: %v", err) + } + if api.exists(retired) { + t.Fatal("Retired Device survived deletion") + } + }) + t.Run("deletecollection denies the Devices that are not Retired", func(t *testing.T) { + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("mixed")); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("deletecollection over mixed Devices: %v", err) + } + // The API server stops a collection delete at its first denial, so + // each Retired Device is either already gone or deletable now. + for name, lifecycle := range mixed { + device := mixedDevices[name] + err := api.admin.Delete(ctx, device) + switch { + case lifecycle == inventory.DeviceRetired && err != nil && !apierrors.IsNotFound(err): + t.Fatalf("deleting Retired %s after deletecollection: %v", name, err) + case lifecycle != inventory.DeviceRetired && (!apierrors.IsForbidden(err) || !api.exists(device)): + t.Fatalf("%s (%s) is not protected after deletecollection: %v", name, lifecycle, err) + case lifecycle == inventory.DeviceRetired && api.exists(device): + t.Fatalf("Retired %s survived", name) + } + } + }) + t.Run("deleting the namespace lets its Devices be deleted", func(t *testing.T) { + if err := api.admin.Delete(ctx, teardownActive); !apierrors.IsForbidden(err) { + t.Fatalf("Device deletion before namespace deletion: %v", err) + } + if err := api.admin.Delete(ctx, teardown); err != nil { + t.Fatal(err) + } + if !api.exists(teardown) || teardown.DeletionTimestamp.IsZero() { + t.Fatal("namespace is not marked for deletion") + } + // The policy reads namespaceObject from the API server's namespace + // cache, which observes the deletion mark shortly after it is set. + api.eventually("namespace deletion mark", func() bool { + return api.admin.Delete(ctx, teardownActive, client.DryRunAll) == nil + }) + // envtest runs no namespace controller. Issue the content deletions + // the controller would: deletecollection, then per item. + if err := api.admin.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("teardown")); err != nil { + t.Fatalf("namespace cleanup deletecollection: %v", err) + } + for _, device := range []*inventory.Device{teardownActive, teardownDecommissioning} { + if err := api.admin.Delete(ctx, device); err != nil && !apierrors.IsNotFound(err) { + t.Fatalf("namespace cleanup of %s: %v", device.Name, err) + } + if api.exists(device) { + t.Fatalf("%s survived namespace cleanup", device.Name) + } + } + }) + t.Run("Devices in other namespaces stay protected", func(t *testing.T) { + if err := api.admin.Delete(ctx, active); !apierrors.IsForbidden(err) || !api.exists(active) { + t.Fatalf("Active Device outside the deleting namespace: %v", err) + } + }) +} From 0537866c1f0c00ef28925c316bcaaf8802b9be24 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:31 -0600 Subject: [PATCH 08/16] feat(ui): honor Device lifecycle in registration The registration picker refuses Devices that are Decommissioning or Retired with an explicit reason, and still marks an Active Device that shares identity with a Retired one as conflicting. The inventory detail panel shows the lifecycle, defaulting to Active. The UI does not edit lifecycle. Co-Authored-By: Claude Opus 5.5 --- ui/provider/src/components/physical-inventory.tsx | 1 + ui/provider/src/lib/capacity-registration.test.ts | 10 ++++++++++ ui/provider/src/lib/capacity-registration.ts | 9 ++++++--- ui/shared/fleet-api.ts | 5 +++++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/ui/provider/src/components/physical-inventory.tsx b/ui/provider/src/components/physical-inventory.tsx index 31a3d2fe..003d9452 100644 --- a/ui/provider/src/components/physical-inventory.tsx +++ b/ui/provider/src/components/physical-inventory.tsx @@ -345,6 +345,7 @@ export function PhysicalInventory({ inventory: source, onRetry, showNavigation = {modelLabel(device.spec.identity)} {catalog ? reference('DeviceType', namespace, catalog.model.metadata.name) : device.spec.deviceTypeRef ? 'Catalog unavailable · showing recorded observation' : 'Not assigned · showing recorded observation'} {catalog?.model.spec.modelShape?.heightUnits === undefined ? 'Unknown' : `${catalog.model.spec.modelShape.heightUnits}U · not measured or used for occupancy`} + {device.spec.lifecycle ?? 'Active'} {device.spec.identity.serial} {device.spec.assetTag} {device.spec.identity.systemUUID} diff --git a/ui/provider/src/lib/capacity-registration.test.ts b/ui/provider/src/lib/capacity-registration.test.ts index 52ea1963..8a218155 100644 --- a/ui/provider/src/lib/capacity-registration.test.ts +++ b/ui/provider/src/lib/capacity-registration.test.ts @@ -73,3 +73,13 @@ it('rejects partial and unidentified identity and non-default inventory', () => expect(ineligibleReason({ ...device, spec: { ...device.spec, identity: { model: 'test', serial: 'only-serial' } } })).toContain('ambiguous'); expect(ineligibleReason({ ...device, metadata: { ...device.metadata, namespace: 'other' } })).toContain('unavailable'); }); + +it('registers only Active Devices and still counts Retired ones as conflicts', async () => { + expect(ineligibleReason({ ...device, spec: { ...device.spec, lifecycle: 'Active' } })).toBeUndefined(); + expect(ineligibleReason({ ...device, spec: { ...device.spec, lifecycle: 'Decommissioning' } })).toBe('Device is Decommissioning; only an Active Device can be registered'); + expect(ineligibleReason({ ...device, spec: { ...device.spec, lifecycle: 'Retired' } })).toBe('Device is Retired; only an Active Device can be registered'); + const retiredTwin: Device = { metadata: { name: 'retired-twin', namespace: 'default', uid: 'device-9', resourceVersion: '1' }, spec: { claimRef: { name: 'installation' }, lifecycle: 'Retired', identity: { model: 'test', serial: 'SERIAL-1', systemUUID: '99999999-9999-9999-9999-999999999999' } } }; + expect(ineligibleReason(device, [device, retiredTwin])).toContain('Conflicting'); + await expect(registerCapacity({ ...device, spec: { ...device.spec, lifecycle: 'Decommissioning' } }, 'operation', new InventoryOperationScope().begin())).rejects.toThrow('only an Active Device'); + expect(transport).not.toHaveBeenCalled(); +}); diff --git a/ui/provider/src/lib/capacity-registration.ts b/ui/provider/src/lib/capacity-registration.ts index cbe5aff1..6139d6b5 100644 --- a/ui/provider/src/lib/capacity-registration.ts +++ b/ui/provider/src/lib/capacity-registration.ts @@ -26,11 +26,14 @@ function aliases(device: Device): string[] { return result; } -// ineligibleReason explains why a Device cannot be registered. Passing the -// listed Devices also marks every Device that shares a hardware alias with -// another one as conflicting until a person resolves the duplicate. +// ineligibleReason explains why a Device cannot be registered. Only an Active +// Device can be. Passing the listed Devices also marks every Device that +// shares a hardware alias with another one, including a Retired one, as +// conflicting until a person resolves the duplicate. export function ineligibleReason(device: Device, listed: Device[] = []): string | undefined { if (device.metadata.namespace !== 'default' || !device.metadata.uid || !device.metadata.resourceVersion || device.metadata.deletionTimestamp) return 'Device incarnation is unavailable or deleting'; + const lifecycle = device.spec.lifecycle ?? 'Active'; + if (lifecycle !== 'Active') return `Device is ${lifecycle}; only an Active Device can be registered`; if (device.spec.identity.unidentified || !device.spec.identity.serial?.trim() || !device.spec.identity.systemUUID) return 'Both serial and system UUID are required; partial identity is ambiguous'; if (['unknown', 'none', 'n/a', 'default string', 'to be filled by o.e.m.'].includes(device.spec.identity.serial.trim().toLowerCase()) || ['00000000-0000-0000-0000-000000000000', 'ffffffff-ffff-ffff-ffff-ffffffffffff'].includes(device.spec.identity.systemUUID)) return 'Placeholder identity is ineligible'; const own = aliases(device); diff --git a/ui/shared/fleet-api.ts b/ui/shared/fleet-api.ts index 3e4e65c9..7abb2f2d 100644 --- a/ui/shared/fleet-api.ts +++ b/ui/shared/fleet-api.ts @@ -278,9 +278,14 @@ export interface Device { bmc?: { endpoint: string }; interfaces?: { name: string; macAddress?: string; peer?: PortPeer }[]; unmappedMACAddresses?: string[]; + // lifecycle defaults to Active. Active and Decommissioning move between + // each other, Decommissioning moves to Retired, and Retired is terminal. + lifecycle?: DeviceLifecycle; }; } +export type DeviceLifecycle = 'Active' | 'Decommissioning' | 'Retired'; + export interface ReportedPlacement { revision: number; observedAt: string; From a561597629d17449c659d3a75c2c4c9aa51a54ad Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 16:49:32 -0600 Subject: [PATCH 09/16] docs: describe Device lifecycle and opt-in delete Document the lifecycle values and transitions, the registration rules, and the deletion policy's two exceptions. Deploying repositories opt into the component; this repository no longer has a production Milo root. Namespace deletion is the privileged escape hatch and now completes with its Devices. The earlier stays-Terminating remediation is removed. Record that pinned Milo project purge issues collection deletes in every namespace before marking any, and never deletes default, so a project that holds Devices that are not Retired does not finish purging while the component is installed. Co-Authored-By: Claude Opus 5.5 --- config/README.md | 19 +- docs/development/README.md | 6 +- .../inventory-capacity-registration.md | 249 ++++++++++++------ docs/operations/physical-inventory.md | 18 +- 4 files changed, 186 insertions(+), 106 deletions(-) diff --git a/config/README.md b/config/README.md index 55020bb5..3c6187d1 100644 --- a/config/README.md +++ b/config/README.md @@ -15,18 +15,16 @@ target different API servers and must be reconciled independently. | Root | Destination | Contents | | --- | --- | --- | | `config/milo` | Milo root control plane | Fleet CRDs (including the `fleet.datumapis.com` inventory kinds), IAM protected resources and roles, service/quota registration, and the mandatory capacity-registration webhook. Devices can be deleted. | -| `config/milo-production` | Milo root control plane (production-style) | `config/milo` plus Device deletion protection | | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, manager and inert-registration workloads and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | -`config/components/device-deletion-protection` is an optional component: a -ValidatingAdmissionPolicy and binding that deny every Device `DELETE`, with no -exemptions. Each environment chooses whether to install it. Production-style -Milo control planes use `config/milo-production`; test, staging and synthetic -control planes that need Device deletions use `config/milo` or -`config/milo-synthetic`. `hack/validate-overlay-isolation.sh` rejects any other -root that renders the policy. Namespace and project deletions that reach a -protected Device stay stuck rather than deleting it; see +`config/components/device-deletion-protection` is a reusable component: a +ValidatingAdmissionPolicy and binding that deny a Device `DELETE` unless the +Device is `Retired` or its namespace is being deleted, with no exemptions. +Production-specific configuration lives in the deploying repository, which +opts in by adding the component to the root it applies to Milo. No root in this +repository includes it, and `hack/validate-overlay-isolation.sh` fails if one +does or if the component's policy is weakened. See [Device deletion protection](../docs/development/inventory-capacity-registration.md#device-deletion-protection). The synthetic staging overlay excludes the inert-registration service. Pair it @@ -121,11 +119,10 @@ synthetic claim before treating persistent-state recovery as verified in staging Do not delete the PVC as a recovery shortcut. -Render both production roots before publishing the Kustomize bundle: +Render the Milo and management-cluster roots before publishing the Kustomize bundle: ```sh kustomize build config/milo >/dev/null -kustomize build config/milo-production >/dev/null kustomize build config/milo-synthetic >/dev/null kustomize build config/overlays/management-plane >/dev/null kustomize build config/overlays/synthetic-staging >/dev/null diff --git a/docs/development/README.md b/docs/development/README.md index d4ccb76d..364bf6c8 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -21,8 +21,10 @@ public project API. Production caller-preserving allocation admission, replayable Milo event adapters, and production provider integration are not implemented. Inert [inventory-backed capacity registration](inventory-capacity-registration.md) now has a stateless caller-preserving admission service that checks live -Devices, one capacity per Device through a Device-derived name, optional Device -deletion protection, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly +Devices, one capacity per Device through a Device-derived name, a Device +lifecycle (`Active`, `Decommissioning`, terminal `Retired`), an opt-in Device +deletion protection component that admits deletes only for Retired Devices or +a deleting namespace, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly unconfigured; deployment trust inputs and live Milo acceptance remain required. An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index 5278d81c..e7cfe5c0 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -18,8 +18,11 @@ a mutable tail with sealed segments, signed expansion and activation, epochs and growth limits. The user decided this was overengineering and replaced it with the following: -1. **Devices are not deleted.** An optional ValidatingAdmissionPolicy denies - every Device `DELETE`. An environment decides whether to install it; see +1. **In-service Devices are not deleted.** A reusable ValidatingAdmissionPolicy + component denies a Device `DELETE` unless the Device is `Retired` or its + namespace is being deleted. No root in this repository includes it; + deploying repositories opt in. See + [Device lifecycle](#device-lifecycle) and [Device deletion protection](#device-deletion-protection). 2. **No signed activation.** The bootstrap/activation gate, `/activationz`, `/status`, the operator control key and ConfigMap, @@ -30,11 +33,12 @@ with the following: checks the live Device and capacities through the API server on every request. -Rationale: when Devices are never deleted, the live Device list already holds -every identity the ledger used to remember, so a second store adds failure -modes without adding information. Environments that need to delete Devices, -such as test and synthetic environments, do not hold real machines and do not -need permanent identity retention. +Rationale: when in-service Devices are never deleted, the live Device list +already holds every identity the ledger used to remember, so a second store +adds failure modes without adding information. A Device leaves the list only +after someone has retired it on purpose, or deleted its namespace. Environments +that do not include the component, such as test and synthetic environments, do +not hold real machines and do not need identity retention. ## Public contract and authority @@ -68,7 +72,9 @@ operation ID is no longer used for deduplication. An empty cleaning-policy name explicitly means **unconfigured**, not a policy named `default`, synthetic cleaning, or authorization to prepare. The CRD permits it only while Disabled. The webhook rejects *all* capacity updates, -status updates and deletes. Real policy resolution and policy-use authorization +status updates and deletes. An update that would move capacity out of +`Disabled` while its Device is `Decommissioning` or `Retired` is denied for +that reason; the webhook first checks that the caller can read the Device. Real policy resolution and policy-use authorization are future prerequisites for a separately designed transition; there is no stage-1 preparation endpoint. @@ -85,7 +91,8 @@ stage-1 preparation endpoint. happens before the Device is read, so an unauthorized caller cannot learn whether a Device exists; 5. reads the Device uncached. A missing Device is denied. Its UID and - resourceVersion must equal the annotations, and it must not be deleting; + resourceVersion must equal the annotations, it must not be deleting, and + its [lifecycle](#device-lifecycle) must be `Active`; 6. requires both a non-placeholder serial and a canonical system UUID, and a complete provider host reference when one is present; 7. lists Devices and capacities in **all namespaces of every configured @@ -154,71 +161,119 @@ both fail, because each sees the other Device. Device status has no writer today, so there is no server-side eligibility condition to set; reporting conflicts through Device status is a follow-up. +## Device lifecycle + +`Device.spec.lifecycle` records whether the asset is in service. It is part of +spec, so the inventory editor role, which can update Devices, can set it; no +extra RBAC exists. + +| Value | Meaning | +| --- | --- | +| `Active` | In service. The CRD default when the field is unset. | +| `Decommissioning` | Leaving service. Can return to `Active`. | +| `Retired` | Out of service. Terminal. | + +The CRD enforces transitions with transition rules (`oldSelf`) on `spec`: + +- `Active` to `Decommissioning`, `Decommissioning` to `Active`, and + `Decommissioning` to `Retired` are allowed. Leaving the value unchanged is + always allowed. +- `Active` to `Retired` is rejected: move the Device to `Decommissioning` + first. +- Nothing leaves `Retired`. Removing the field defaults it to `Active`, so + that is rejected too. + +The rules apply to updates only; a Device may be created in any lifecycle, for +example to record hardware that is already out of service. Other spec edits to +a Retired Device are still subject only to the existing rules. + +Registration semantics, enforced by the registration webhook: + +- Only an `Active` Device can get new capacity. +- Capacity whose Device is `Decommissioning` or `Retired` cannot leave + `Disabled`. Stage 1 already denies every capacity update, so this states the + rule a future enabling transition must keep. +- A Retired Device still takes part in the duplicate-identity check for as + long as it exists. Deleting it removes its identity from that check. + +Lifecycle is a record, not an effect. Moving a Device changes no capacity, +allocation, provider or network state. + ## Device deletion protection -`config/components/device-deletion-protection` is a Kustomize component with a -ValidatingAdmissionPolicy and binding named `fleet-device-deletion-protection`. -It denies every `DELETE` on `devices.fleet.datumapis.com` (all versions, all -namespaces) with `failurePolicy: Fail` and reason `Forbidden`. - -- **Where it is installed.** Devices are stored and admitted by the Milo - control plane: `config/components/inventory` registers the CRD there, and - records live in provider projects. The component therefore belongs with the - Milo root, not the management-cluster host overlays, which have no Device - CRD. Like the registration webhook, it is installed at the Milo root and - relies on Milo running its root admission policies for project-routed - requests (pinned Milo `v0.36.9` enables the `ValidatingAdmissionPolicy` - plugin). Confirm this on the deployed Milo before relying on it. -- **Which roots include it.** `config/milo-production` is `config/milo` plus - the component, and is the production-style root. `config/milo` (consumed by - staging and test control planes that need Device deletion), - `config/milo-synthetic`, `config/inventory`, `config/standalone` and every - host overlay leave it out. `hack/validate-overlay-isolation.sh` fails if a - production-style root lacks it, or if any other root renders it. -- **No exemptions.** No user, group or service account is exempt, including - cluster administrators. The escape hatch is an environment not installing - the component. Anyone able to delete the binding is outside the guarantee. -- **deletecollection.** The API server admits each object of a collection - delete individually as a `DELETE`, so a collection delete that includes a - Device fails and leaves Devices in place. Other objects in the same call may - already be gone. -- **Garbage collection and finalizers.** Owner-reference cascades issue the - same `DELETE` and are denied. Because the `DELETE` is denied, a Device never - gets a deletion timestamp, so finalizers never run. -- **Namespace and project deletion (fail-closed: stays stuck).** A policy - cannot see what a namespace contains, so it does not block the namespace - `DELETE`. The namespace becomes `Terminating`, the namespace controller - deletes the other contents, and its Device deletions are denied. The - namespace stays `Terminating` with its Devices intact and readable; it - accepts no new objects. Milo keeps `default` undeletable, and Milo's project - purge drains `default` in place and reports remaining Devices as blockers on - the Project. So deleting a provider project stops with its Devices in place. - Other inventory in that namespace or project (for example DeviceClaims) is - still deleted before the cascade stops. Capacity is not, because the - registration webhook denies capacity deletes. Do not delete namespaces or - projects that hold Devices. -- **Remediation for a stuck namespace or project.** Kubernetes cannot cancel - a namespace deletion. Either leave it `Terminating`, which keeps every - Device, or have the environment owner deliberately decide to give up those - identities: remove the binding, let the cascade finish, and reinstall the - component. The second option loses the Device records and their duplicate - protection, so it is an explicit ownership decision, not routine repair. -- **Retirement.** A machine leaving service keeps its Device. Its capacity is - already `Disabled` and cannot be changed, which is the only retirement state - stage 1 has. Devices have no lifecycle or retirement field (see - [Planning and registering physical devices](../operations/physical-inventory.md)). - A Device retirement state is a follow-up. - -### Deleting a Device where deletion is allowed - -Without the component, deleting a Device that backs capacity leaves the -capacity in place, still `Disabled`. The webhook denies every update and -delete of it, so it cannot become available. No owner reference links the two: -the webhook rejects owner references on registration, and garbage collection -would be denied anyway because capacity deletes are fenced. The orphaned -capacity keeps its Device UID annotation and name, which also prevents a -replacement Device with the same name from registering. Clean it up only in -environments where capacity writes are not fenced, such as synthetic ones. +`config/components/device-deletion-protection` is a reusable Kustomize +component with a ValidatingAdmissionPolicy and binding named +`fleet-device-deletion-protection`. It matches every `DELETE` on +`devices.fleet.datumapis.com` (all versions, all namespaces) and admits it only +when: + +1. the Device's namespace is being deleted: the policy's `namespaceObject` + has `metadata.deletionTimestamp` set. A missing namespace object does not + match; or +2. the Device being deleted (`oldObject`) has `spec.lifecycle: Retired`. + +Every other `DELETE` is denied with reason `Forbidden` and a message to move +the Device to `Decommissioning`, then `Retired`, first. The policy uses +`failurePolicy: Fail` and the binding `validationActions: [Deny]`, so an +evaluation error also denies. + +- **Who includes it.** No root in this repository renders the policy. + Production-specific configuration lives in the deploying repository, which + adds the component to the root it applies to the Milo control plane. Devices + are stored and admitted there: `config/components/inventory` registers the + CRD in Milo, and records live in provider projects. Management-cluster host + overlays have no Device CRD. Like the registration webhook, the policy relies + on Milo running its root admission policies for project-routed requests + (pinned Milo `v0.36.9` enables the `ValidatingAdmissionPolicy` plugin). + Confirm this on the deployed Milo before relying on it. +- **Validation.** `hack/validate-overlay-isolation.sh` renders the component + on its own and fails unless it is exactly this policy: the same name, + expression, `failurePolicy: Fail`, `Deny` only, and no match conditions, + selectors, exclusions, variables or parameters. It also fails if any root in + this repository renders the policy, under its own name or another, and if + the inventory component exists without this component. +- **No exemptions.** The policy does not look at the request's user, group or + service account. Cluster administrators are held to the same rule. Anyone + able to delete the binding is outside the guarantee. +- **deletecollection, garbage collection and finalizers.** The API server + admits each object of a collection delete individually as a `DELETE`, so a + collection delete that reaches a Device that is not Retired is denied and + leaves that Device in place. Retired Devices and other objects it reached + first may already be gone; it may also stop before reaching every Retired + Device, so repeat the delete per Device. Owner-reference cascades issue + the same `DELETE`. A denied Device gets no deletion timestamp, so its + finalizers never run. +- **Namespace deletion is the escape hatch.** Deleting a namespace is a + privileged act. Once the namespace has a deletion timestamp, the namespace + controller's Device deletions are admitted, so the namespace finishes + terminating and takes its Devices with it, whatever their lifecycle. Their + identities leave the duplicate check. The policy reads the namespace from the + API server's namespace cache, which observes the deletion mark shortly after + it is set. +- **Project deletion.** In pinned Milo `v0.36.9`, project purge first issues a + collection delete for every namespaced resource in every namespace, and only + then deletes the namespaces. It never deletes `default`, which it drains in + place. In that first phase no namespace is marked yet, so a Device that is + not Retired stops the purge's collection delete. Registered Devices live in + `default`, which is never marked. A project that holds Devices that are not + Retired therefore does not finish purging while the component is installed: + retire its Devices first. This is from reading the pinned Milo source, not a + live test. +- **Capacity is not deleted with its Device.** The registration webhook denies + capacity deletes, so a namespace or project teardown that removes Devices + still stops at their capacity; see the next section. + +### Deleting a Device + +Deleting a Device that backs capacity, whether it is Retired, its namespace is +being deleted, or the component is not installed, leaves the capacity in +place, still `Disabled`. The webhook denies every update and delete of it, so +it cannot become available. No owner reference links the two: the webhook +rejects owner references on registration, and garbage collection would be +denied anyway because capacity deletes are fenced. The orphaned capacity keeps +its Device UID annotation and name, which also prevents a replacement Device +with the same name from registering. Clean it up only in environments where +capacity writes are not fenced, such as synthetic ones. ## Production packaging and rollout @@ -228,7 +283,9 @@ environments where capacity writes are not fenced, such as synthetic ones. selectors or match conditions. An unreachable service blocks capacity writes globally and nothing else: Device, namespace and Project writes do not pass through the registration webhook. -- `config/milo-production` adds Device deletion protection. +- 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. - `config/overlays/management-plane` includes a separate two-replica registration Deployment and TLS Service. The pod does not mount a service account token and has no host RBAC. It does not enable production lifecycle @@ -259,11 +316,13 @@ Environment-owned inputs, none of which this repository supplies: 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. -4. Choose the Milo root: `config/milo-production` to forbid Device deletion, - or `config/milo` to allow it. +4. Decide whether the Milo root you apply includes + `config/components/device-deletion-protection`. With it, only Retired + Devices and Devices in a deleting namespace can be deleted; without it, + any authorized caller can delete a Device. 5. Before rolling out the UI, verify caller-preserving project routing, named Device read denial, registration denial, capacity mutation denial, TLS - rejection, Device deletion denial where installed, and duplicate handling + rejection, Device deletion denial where installed, lifecycle transitions, and duplicate handling in the target environment. This change performs **no live writes or deployment**, so it does not claim those checks. @@ -276,8 +335,10 @@ those objects until its owner removes them; the new service ignores them. The Datum dialog uses the existing host-session boundary and isolated read cache. It shows the derived capacity name instead of a name field. Missing -host authority, denied registration, unavailable Devices, partial identity and -conflicting identities have explicit explanations. Selecting a Device +host authority, denied registration, unavailable Devices, Devices that are not +Active, partial identity and conflicting identities, including a conflict with +a Retired Device, have explicit explanations. The inventory detail panel shows +a Device's lifecycle; the UI does not edit it. Selecting a Device snapshots its baseline; neither refetch nor browser blur/focus changes it. A named current read immediately precedes dispatch. Session changes fence pending work. After dispatch, an uncertain result keeps the selection, disables @@ -309,19 +370,35 @@ packaged webhook against a real API server and checks that: - without the component, Device `DELETE` succeeds and the backing capacity stays `Disabled` and cannot be updated, deleted or re-registered by a same-name replacement; -- with the component applied from its manifest, Device `DELETE` is denied for - every caller, `deletecollection` is denied, and namespace deletion stays - `Terminating` with its Devices while other content drains. envtest has no - namespace controller, so the test issues the controller's content deletions - itself; +- a Decommissioning or Retired Device cannot be registered, a Retired Device + still blocks a duplicate, and capacity cannot leave `Disabled` once its + Device is Decommissioning or Retired; - a webhook outage blocks capacity writes but not Device writes. +`internal/registration/deletion_envtest_test.go` applies the component from +its manifest and checks that: + +- the CRD transition rules accept `Active`/`Decommissioning` moves and + `Decommissioning` to `Retired`, and reject `Active` to `Retired` and every + move out of `Retired`; +- deleting an Active or Decommissioning Device is denied for every caller, + and deleting a Retired Device is allowed; +- `deletecollection` over mixed Devices denies those that are not Retired; +- after the namespace is deleted, its Devices can be deleted. envtest has no + namespace controller, so the test issues the controller's deletions itself + and they are admitted because `namespaceObject` has a deletion timestamp; +- Devices in other namespaces stay protected. + Unit tests cover the remaining negative cases, normalization, cross-project duplicates, project lifetime and the packaged webhook shape. `cmd/fleet-registration` tests reject unauthenticated and untrusted webhook -transport. The overlay isolation tests cover where the deletion component may -and must appear. Frontend tests cover the derived name and conflict marking -with mocked transport. None of this is a live Milo deployment or an independent +transport. `internal/api/inventory/v1alpha1/lifecycle_test.go` runs the +lifecycle default and transition rules through the CRD schema offline. The +overlay isolation tests fail when a root includes the deletion component and +when the component's policy is renamed, made audit-only, fail-open, scoped, +exempted or given a weaker expression. Frontend tests cover the derived name, +conflict marking including Retired Devices, and refusal of Devices that are not +Active, with mocked transport. None of this is a live Milo deployment or an independent security review. The publishing workflow applies the server build tag to diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index d009eb89..79234491 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -143,6 +143,7 @@ in the provider project. The plugin never writes. | Port and interface names are unique; MACs are lowercase and colon-separated, appear at most once per Device, and are either mapped to an interface or listed in `unmappedMACAddresses`, not both | Both | Malformed or ambiguous facts are rejected. | | The system UUID is in lowercase canonical form | Device | One spelling per identity. | | `bmc.endpoint` is an `https` URL without credentials | Device | Credentials never live in inventory records. | +| `lifecycle` is `Active` (default), `Decommissioning` or `Retired`; `Active` and `Decommissioning` move between each other, only `Decommissioning` moves to `Retired`, and `Retired` is terminal | Device | Retirement is deliberate and one-way. Only an Active Device can be registered as capacity. See [Device lifecycle](../development/inventory-capacity-registration.md#device-lifecycle). | | `status` is a separate subresource that declares no fields | All six | Reserved for future collectors and verifiers to report drift and mismatch. Status never carries identity, and nothing writes it yet. | The CRDs cannot check that `claimRef` names an existing DeviceClaim, because @@ -328,10 +329,13 @@ spec: ``` To replace the hardware, create a new Device with its own name and identity -that names the same claim. Leave the old Device in place until its retirement -is settled. This package does not model retirement. Environments with +that names the same claim. Leave the old Device in place and move its +`spec.lifecycle` from `Active` to `Decommissioning`, then to `Retired`; see +[Device lifecycle](../development/inventory-capacity-registration.md#device-lifecycle). +Retired is terminal and still counts in the duplicate-identity check while the +Device exists. Environments with [Device deletion protection](../development/inventory-capacity-registration.md#device-deletion-protection) -never delete a Device. +delete a Device only once it is Retired, or with its namespace. ## Relationship to the inventory proposal @@ -354,8 +358,8 @@ Still deferred to #63: adjudication and duplicate detection; and the protected ledger. - Trust roots, qualification profiles, enrollment challenges, technician and collector attestation, and evidence freshness. -- Component incarnations and lineage, maintenance, moves, retirement, and - adopted custody. +- Component incarnations and lineage, maintenance, moves, a retirement + workflow beyond the recorded Device lifecycle, and adopted custody. - The `Accepted`, `Bound`, `IdentityVerified`, `PlacementVerified`, `NetworkPathVerified`, and `PowerPathVerified` predicates and any eligibility publication. @@ -416,8 +420,8 @@ Two kinds of stored record no longer validate once pruned: serial or system UUID. Because `identity` is immutable, delete it and create a new Device with a serial or system UUID. Where [Device deletion protection](../development/inventory-capacity-registration.md#device-deletion-protection) - is installed the record cannot be deleted; leave it in place and create the - new Device alongside it. + is installed, retire it (`Decommissioning`, then `Retired`) before deleting + it, or leave it in place and create the new Device alongside it. - A Device whose `reportedPlacement` lacks `reason` or `reference` must gain both the next time its report changes. From 3e41e9e23ead4cb1afa568ed8ef6b64a4d275ac8 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 17:14:13 -0600 Subject: [PATCH 10/16] feat(config): allow cleanup identity Device delete Milo project purge drains every namespace, default included, with DeleteCollection before it deletes any namespace, so the deleting-namespace exception never applies and a denied Device aborts the purge. Add a third exception: the request's username is listed exactly in the cleanupUsernames key of a ConfigMap parameter. The policy gains paramKind core/v1 ConfigMap. The shipped binding has no paramRef, so params is null and the exception is off; deploying repositories add the ConfigMap and a paramRef with parameterNotFoundAction Deny. Entries are trimmed, empty entries and an empty username never match, and groups, prefixes and wildcards are not consulted. failurePolicy Fail and validationActions Deny stay. The overlay validator requires the exact rendered policy, including paramKind, and rejects wildcard, prefix, group-based, null-params-allows-all, empty-username and always-true variants, a different or missing paramKind, and any paramRef in the component. Envtest on Kubernetes 1.37.0 covers the null-params binding, listed, unlisted, prefix and superset users, deletecollection, a Milo-style purge of default and another namespace, and fail-closed denial (422 Invalid) when the referenced ConfigMap is missing. An offline test runs the expression through the admission CEL compiler for an empty username. Co-Authored-By: Claude Opus 5.5 --- .../device-deletion-protection/policy.yaml | 47 +++- hack/overlay-isolation-validator.go | 37 ++- hack/test-overlay-isolation.sh | 27 +- .../registration/deletion_envtest_test.go | 230 +++++++++++++++++- internal/registration/deletion_policy_test.go | 139 +++++++++++ 5 files changed, 457 insertions(+), 23 deletions(-) create mode 100644 internal/registration/deletion_policy_test.go diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml index 0de29e95..870d7fa6 100644 --- a/config/components/device-deletion-protection/policy.yaml +++ b/config/components/device-deletion-protection/policy.yaml @@ -3,20 +3,36 @@ # spec.lifecycle to Decommissioning and then Retired; the CRD rejects every # other path to Retired, and Retired is terminal. # -# The one other exception is a Device whose namespace is being deleted -# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace is -# the privileged escape hatch: it lets the namespace controller finish and -# takes its Devices with it. Nothing keys off who makes the request, and there -# are no exemptions. The API server runs admission once per object for -# deletecollection, garbage collection and namespace cleanup, so each of those -# paths is held to the same rule. A missing namespace object or an evaluation -# error denies the request (failurePolicy: Fail). +# Three exceptions admit a DELETE: +# +# 1. The Device's namespace is being deleted +# (namespaceObject.metadata.deletionTimestamp is set). Deleting a namespace +# is the privileged escape hatch: it lets the namespace controller finish +# and takes its Devices with it. +# 2. The Device is Retired. +# 3. The request's username is listed, exactly, in the cleanupUsernames key of +# the binding's parameter ConfigMap. This lets a project cleanup controller +# drain Devices in place, which namespace deletion cannot do for `default`. +# Entries are separated by commas or newlines and trimmed; empty entries +# and an empty username never match. Groups, prefixes and wildcards are not +# consulted. +# +# The binding below has no paramRef, so params is null and exception 3 is off. +# A deploying repository turns it on by adding the ConfigMap and patching the +# binding with a paramRef that sets parameterNotFoundAction: Deny; a missing +# ConfigMap then denies every Device DELETE. The API server runs admission once +# per object for deletecollection, garbage collection and namespace cleanup, so +# each of those paths is held to the same rule. A missing namespace object or +# an evaluation error denies the request (failurePolicy: Fail). apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicy metadata: name: fleet-device-deletion-protection spec: failurePolicy: Fail + paramKind: + apiVersion: v1 + kind: ConfigMap matchConstraints: matchPolicy: Equivalent resourceRules: @@ -29,13 +45,20 @@ spec: (namespaceObject != null && has(namespaceObject.metadata) && has(namespaceObject.metadata.deletionTimestamp)) || (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && - oldObject.spec.lifecycle == 'Retired') + oldObject.spec.lifecycle == 'Retired') || + (params != null && has(params.data) && 'cleanupUsernames' in params.data && + request.userInfo.username != '' && + params.data.cleanupUsernames.replace('\n', ',').split(',').exists(entry, + entry.trim() != '' && entry.trim() == request.userInfo.username)) reason: Forbidden message: >- - Only a Retired Device can be deleted. Move the Device to Decommissioning, - then Retired, first; its identity must stay visible to duplicate-hardware - checks while it is in service. + A Device can be deleted only when it is Retired, when its namespace is + being deleted, or by a configured cleanup identity. Move the Device to + Decommissioning, then Retired, first; its identity must stay visible to + duplicate-hardware checks while it is in service. --- +# No paramRef: params is null and only the namespace and Retired exceptions +# apply. See docs/development/inventory-capacity-registration.md#cleanup-identity. apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingAdmissionPolicyBinding metadata: diff --git a/hack/overlay-isolation-validator.go b/hack/overlay-isolation-validator.go index e524df59..79e111f0 100644 --- a/hack/overlay-isolation-validator.go +++ b/hack/overlay-isolation-validator.go @@ -37,12 +37,18 @@ const ( inventoryComponent = "components/inventory" // deletionProtectionExpression is the only admitted rule: a Device DELETE - // passes when its namespace is being deleted or it is Retired. It is - // compared with whitespace normalized. + // passes when its namespace is being deleted, it is Retired, or the + // request's username is listed exactly in the parameter ConfigMap's + // cleanupUsernames. It is compared with whitespace normalized, so wildcard, + // prefix, group-based or null-params-allows-all variants are rejected. deletionProtectionExpression = `(namespaceObject != null && has(namespaceObject.metadata) && has(namespaceObject.metadata.deletionTimestamp)) || (oldObject != null && has(oldObject.spec) && has(oldObject.spec.lifecycle) && -oldObject.spec.lifecycle == 'Retired')` +oldObject.spec.lifecycle == 'Retired') || +(params != null && has(params.data) && 'cleanupUsernames' in params.data && +request.userInfo.username != '' && +params.data.cleanupUsernames.replace('\n', ',').split(',').exists(entry, +entry.trim() != '' && entry.trim() == request.userInfo.username))` ) type kustomization struct { @@ -331,22 +337,37 @@ func checkDeletionProtection(root string, objects []*unstructured.Unstructured, spec := policy.Object["spec"].(map[string]any) _, hasConditions := spec["matchConditions"] _, hasVariables := spec["variables"] - _, hasParams := spec["paramKind"] - if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || !unscopedConstraints(policy) || hasConditions || hasVariables || hasParams || len(validations) != 1 { + if policy.GetName() != deletionProtection || failurePolicy != "Fail" || !policyMatchesDeviceDelete(policy) || !unscopedConstraints(policy) || hasConditions || hasVariables || len(validations) != 1 { return fmt.Errorf("%s: Device deletion policy must fail closed, match DELETE on devices and have no exemptions", root) } + if !configMapParamKind(spec["paramKind"]) { + return fmt.Errorf("%s: Device deletion policy paramKind must be exactly core/v1 ConfigMap", root) + } if expression, _, _ := unstructured.NestedString(validations[0].(map[string]any), "expression"); strings.Join(strings.Fields(expression), " ") != strings.Join(strings.Fields(deletionProtectionExpression), " ") { - return fmt.Errorf("%s: Device deletion policy must allow DELETE only for a Retired Device or a deleting namespace", root) + return fmt.Errorf("%s: Device deletion policy must allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username", root) } actions, _, _ := unstructured.NestedStringSlice(binding.Object, "spec", "validationActions") _, hasMatch := binding.Object["spec"].(map[string]any)["matchResources"] - _, hasParamRef := binding.Object["spec"].(map[string]any)["paramRef"] - if len(actions) != 1 || actions[0] != "Deny" || hasMatch || hasParamRef { + if len(actions) != 1 || actions[0] != "Deny" || hasMatch { return fmt.Errorf("%s: Device deletion binding must Deny in every namespace", root) } + // The component ships the cleanup identity off. A deploying repository + // adds the paramRef, with parameterNotFoundAction: Deny, alongside its own + // ConfigMap; a paramRef here, and above all one that Allows a missing + // parameter (which skips the policy), is rejected. + if _, hasParamRef := binding.Object["spec"].(map[string]any)["paramRef"]; hasParamRef { + return fmt.Errorf("%s: Device deletion binding must not set paramRef; deploying repositories enable the cleanup identity", root) + } return nil } +// configMapParamKind reports whether a policy paramKind is exactly core/v1 +// ConfigMap, the only parameter the cleanup identity reads. +func configMapParamKind(value any) bool { + paramKind, ok := value.(map[string]any) + return ok && len(paramKind) == 2 && paramKind["apiVersion"] == "v1" && paramKind["kind"] == "ConfigMap" +} + func policyMatchesDeviceDelete(policy *unstructured.Unstructured) bool { rules, _, _ := unstructured.NestedSlice(policy.Object, "spec", "matchConstraints", "resourceRules") for _, raw := range rules { diff --git a/hack/test-overlay-isolation.sh b/hack/test-overlay-isolation.sh index 95211c24..ee163d01 100755 --- a/hack/test-overlay-isolation.sh +++ b/hack/test-overlay-isolation.sh @@ -479,8 +479,8 @@ weakened "renamed Device deletion policy and binding" "components/device-deletio weakened "audit-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Audit]/' weakened "warn-only Device deletion binding" "must Deny in every namespace" -e 's/validationActions: \[Deny\]/validationActions: [Warn]/' weakened "fail-open Device deletion policy" "must fail closed" -e 's/failurePolicy: Fail/failurePolicy: Ignore/' -weakened "always-true Device deletion expression" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/oldObject.spec.lifecycle == 'Retired')/oldObject.spec.lifecycle == 'Retired') || true/" -weakened "Decommissioning Device deletion allowed" "allow DELETE only for a Retired Device or a deleting namespace" -e "s/== 'Retired')/!= 'Active')/" +weakened "always-true Device deletion expression" "allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" -e "s/oldObject.spec.lifecycle == 'Retired')/oldObject.spec.lifecycle == 'Retired') || true/" +weakened "Decommissioning Device deletion allowed" "allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" -e "s/== 'Retired')/!= 'Active')/" weakened "namespace-scoped Device deletion policy" "must fail closed" -e 's/ matchPolicy: Equivalent/ matchPolicy: Equivalent\ namespaceSelector: {matchLabels: {protected: "true"}}/' weakened "subject exemption in Device deletion policy" "must fail closed" -e 's/^ validations:/ matchConditions:\ @@ -488,4 +488,27 @@ weakened "subject exemption in Device deletion policy" "must fail closed" -e 's/ expression: "request.userInfo.username != '\''admin'\''"\ validations:/' +# The cleanup identity clause admits only an exactly listed, non-empty +# username from a ConfigMap parameter, and the component ships it off. +allowed="allow DELETE only for a Retired Device, a deleting namespace or an exactly listed cleanup username" +weakened "always-true cleanup identity clause" "$allowed" -e "s/entry.trim() != '' && entry.trim() == request.userInfo.username/true/" +weakened "wildcard cleanup username" "$allowed" -e "s/entry.trim() == request.userInfo.username/(entry.trim() == '*' || entry.trim() == request.userInfo.username)/" +weakened "prefix cleanup username" "$allowed" -e "s/entry.trim() == request.userInfo.username/request.userInfo.username.startsWith(entry.trim())/" +weakened "group-based cleanup exemption" "$allowed" -e "s/entry.trim() == request.userInfo.username))/entry.trim() == request.userInfo.username)) ||\\ + (params != null \&\& request.userInfo.groups.exists(group, group in params.data.cleanupUsernames.split(',')))/" +weakened "absent params allowing every Device deletion" "$allowed" -e "s/(params != null && has(params.data)/(params == null || has(params.data)/" +weakened "empty username matching an empty entry" "$allowed" -e "s/entry.trim() != '' && entry.trim() == request.userInfo.username/entry.trim() == request.userInfo.username/" -e "/request.userInfo.username != '' &&\$/d" +weakened "Secret paramKind" "paramKind must be exactly core/v1 ConfigMap" -e 's/^ kind: ConfigMap$/ kind: Secret/' +weakened "missing paramKind" "paramKind must be exactly core/v1 ConfigMap" -e '/^ paramKind:$/d' -e '/^ apiVersion: v1$/d' -e '/^ kind: ConfigMap$/d' +weakened "Allow parameterNotFoundAction in the component" "must not set paramRef" -e 's/^ validationActions: \[Deny\]/ validationActions: [Deny]\ + paramRef:\ + name: synthetic-device-cleanup\ + namespace: synthetic-device-cleanup\ + parameterNotFoundAction: Allow/' +weakened "cleanup identity enabled in the component" "must not set paramRef" -e 's/^ validationActions: \[Deny\]/ validationActions: [Deny]\ + paramRef:\ + name: synthetic-device-cleanup\ + namespace: synthetic-device-cleanup\ + parameterNotFoundAction: Deny/' + "$repo_root/hack/validate-overlay-isolation.sh" "$fixture_root/config" "$fixture_root/config/standalone" diff --git a/internal/registration/deletion_envtest_test.go b/internal/registration/deletion_envtest_test.go index 9a2dbbca..1e3693cf 100644 --- a/internal/registration/deletion_envtest_test.go +++ b/internal/registration/deletion_envtest_test.go @@ -7,13 +7,22 @@ import ( "testing" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" ) -const deletionDenied = "Only a Retired Device can be deleted" +const ( + deletionDenied = "A Device can be deleted only when it is Retired, when its namespace is being deleted, or by a configured cleanup identity" + // Synthetic identities. The policy compares usernames only, so each actor + // also holds system:masters to pass RBAC and prove groups do not matter. + syntheticCleanupUser = "synthetic-cleanup" + syntheticPurgeUser = "system:synthetic-purger" + cleanupConfig = "synthetic-device-cleanup" + missingParamsDenied = "no params found for policy binding with `Deny` parameterNotFoundAction" +) func (api *liveAPI) namespace(name string) *corev1.Namespace { api.t.Helper() @@ -96,6 +105,18 @@ func TestDeviceDeletionProtection(t *testing.T) { } } }) + t.Run("without a paramRef the cleanup username is not exempt", func(t *testing.T) { + // The shipped binding has no paramRef, so params is null. A null + // params must evaluate, not error: the denial carries the policy's + // own message, and the Retired subtest below is admitted. + cleanup := api.actor(syntheticCleanupUser, "system:masters") + if err := cleanup.Delete(ctx, active); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("cleanup username deleting an Active Device without a paramRef: %v", err) + } + if !api.exists(active) { + t.Fatal("Active Device removed without a paramRef") + } + }) t.Run("a Retired Device can be deleted", func(t *testing.T) { if err := operator.Delete(ctx, retired); err != nil { t.Fatalf("deleting a Retired Device: %v", err) @@ -158,3 +179,210 @@ func TestDeviceDeletionProtection(t *testing.T) { } }) } + +// setParamRef does what a deploying repository does to turn on the cleanup +// identity: it points the binding at a ConfigMap in a fixed namespace with +// parameterNotFoundAction: Deny. The ConfigMap is created separately, so a +// test can also point the binding at one that does not exist. +func (api *liveAPI) setParamRef(name string) { + api.t.Helper() + ctx := context.Background() + binding := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{} + if err := api.admin.Get(ctx, client.ObjectKey{Name: "fleet-device-deletion-protection"}, binding); err != nil { + api.t.Fatal(err) + } + deny := admissionregistrationv1.DenyAction + binding.Spec.ParamRef = &admissionregistrationv1.ParamRef{Name: name, Namespace: cleanupConfig, ParameterNotFoundAction: &deny} + if err := api.admin.Update(ctx, binding); err != nil { + api.t.Fatal(err) + } +} + +// missingParams reports whether err is the API server's denial for a binding +// whose parameter is missing under parameterNotFoundAction: Deny. +func missingParams(err error) bool { + return apierrors.IsInvalid(err) && strings.Contains(err.Error(), missingParamsDenied) +} + +func requireDeletionDenied(t *testing.T, err error, message string) { + t.Helper() + if !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), message) { + t.Fatalf("expected a Device deletion denial containing %q, got %v", message, err) + } +} + +// TestDeviceDeletionCleanupIdentity enables the cleanup identity as a +// deploying repository would and checks who it admits, that the other two +// exceptions still hold, that it lets a Milo-style purge drain `default`, and +// that a missing ConfigMap fails closed. +func TestDeviceDeletionCleanupIdentity(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + suffix := 0 + lifecycled := func(name, namespace string, lifecycle inventory.DeviceLifecycle) *inventory.Device { + suffix++ + device := api.device(name, namespace, fmt.Sprintf("%s-serial-%d", name, suffix), fmt.Sprintf("eeeeeeee-eeee-4eee-8eee-%012d", suffix)) + switch lifecycle { + case inventory.DeviceDecommissioning: + api.setLifecycle(device, lifecycle) + case inventory.DeviceRetired: + api.retire(device) + } + return device + } + active := lifecycled("cleanup-active", "default", inventory.DeviceActive) + decommissioning := lifecycled("cleanup-decommissioning", "default", inventory.DeviceDecommissioning) + guarded := lifecycled("guarded-active", "default", inventory.DeviceActive) + retired := lifecycled("cleanup-retired", "default", inventory.DeviceRetired) + api.namespace("collection") + collection := []*inventory.Device{ + lifecycled("collection-active", "collection", inventory.DeviceActive), + lifecycled("collection-decommissioning", "collection", inventory.DeviceDecommissioning), + lifecycled("collection-retired", "collection", inventory.DeviceRetired), + } + api.namespace("workloads") + purged := []*inventory.Device{ + lifecycled("purge-default-active", "default", inventory.DeviceActive), + lifecycled("purge-default-decommissioning", "default", inventory.DeviceDecommissioning), + lifecycled("purge-default-retired", "default", inventory.DeviceRetired), + lifecycled("purge-workloads-active", "workloads", inventory.DeviceActive), + lifecycled("purge-workloads-decommissioning", "workloads", inventory.DeviceDecommissioning), + lifecycled("purge-workloads-retired", "workloads", inventory.DeviceRetired), + } + teardown := api.namespace("teardown") + teardownFirst := lifecycled("teardown-first", "teardown", inventory.DeviceActive) + teardownSecond := lifecycled("teardown-second", "teardown", inventory.DeviceActive) + + api.installDeletionProtection(guarded) + cleanup := api.actor(syntheticCleanupUser, "system:masters") + purger := api.actor(syntheticPurgeUser, "system:masters") + operator := api.actor("synthetic-operator", "system:masters") + + t.Run("without a paramRef the cleanup username is denied", func(t *testing.T) { + requireDeletionDenied(t, cleanup.Delete(ctx, active), deletionDenied) + if !api.exists(active) { + t.Fatal("Active Device removed without a paramRef") + } + }) + + // Entries are padded and separated by commas, newlines and CRLF, with + // blank entries in between. Only exact, trimmed names match. + api.namespace(cleanupConfig) + config := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: cleanupConfig, Namespace: cleanupConfig}, Data: map[string]string{"cleanupUsernames": " " + syntheticCleanupUser + " ,\n\n , \r\n" + syntheticPurgeUser + "\r\n,"}} + if err := api.admin.Create(ctx, config); err != nil { + t.Fatal(err) + } + api.setParamRef(cleanupConfig) + api.eventually("cleanup identity", func() bool { + return cleanup.Delete(ctx, guarded, client.DryRunAll) == nil + }) + + t.Run("the listed username deletes Active and Decommissioning Devices", func(t *testing.T) { + for _, device := range []*inventory.Device{active, decommissioning} { + if err := cleanup.Delete(ctx, device); err != nil { + t.Fatalf("cleanup identity deleting %s: %v", device.Name, err) + } + if api.exists(device) { + t.Fatalf("%s survived the cleanup identity's delete", device.Name) + } + } + }) + t.Run("the listed username deletes a mixed collection", func(t *testing.T) { + if err := cleanup.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("collection")); err != nil { + t.Fatalf("cleanup identity deletecollection: %v", err) + } + for _, device := range collection { + if api.exists(device) { + t.Fatalf("%s survived the cleanup identity's deletecollection", device.Name) + } + } + }) + t.Run("other usernames stay denied", func(t *testing.T) { + callers := map[string]client.Client{ + "admin": api.admin, + "unlisted": operator, + "prefix": api.actor("synthetic-clean", "system:masters"), + "superset": api.actor(syntheticCleanupUser+"-extra", "system:masters"), + "embedded": api.actor("x"+syntheticCleanupUser, "system:masters"), + "case": api.actor("Synthetic-Cleanup", "system:masters"), + "listed name as a group": api.actor("synthetic-grouped", "system:masters", syntheticCleanupUser), + "suffix of a listed name": api.actor("synthetic-purger", "system:masters"), + } + for name, caller := range callers { + if err := caller.Delete(ctx, guarded); !apierrors.IsForbidden(err) || !strings.Contains(err.Error(), deletionDenied) { + t.Fatalf("%s deleting an Active Device: %v", name, err) + } + } + if !api.exists(guarded) { + t.Fatal("Active Device removed by an unlisted caller") + } + }) + t.Run("the Retired exception still holds", func(t *testing.T) { + if err := operator.Delete(ctx, retired); err != nil { + t.Fatalf("unlisted caller deleting a Retired Device: %v", err) + } + }) + t.Run("the deleting-namespace exception still holds", func(t *testing.T) { + requireDeletionDenied(t, operator.Delete(ctx, teardownFirst), deletionDenied) + if err := api.admin.Delete(ctx, teardown); err != nil { + t.Fatal(err) + } + api.eventually("namespace deletion mark", func() bool { + return operator.Delete(ctx, teardownFirst, client.DryRunAll) == nil + }) + if err := operator.Delete(ctx, teardownFirst); err != nil { + t.Fatalf("unlisted caller deleting a Device in a deleting namespace: %v", err) + } + // teardownSecond stays behind for the fail-closed check below. + }) + t.Run("a Milo-style purge drains default and other namespaces", func(t *testing.T) { + // Milo v0.36.9 project purge issues DeleteCollection per namespace, + // `default` included, before any namespace is marked for deletion. + for _, namespace := range []string{"default", "workloads"} { + if err := purger.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace(namespace)); err != nil { + t.Fatalf("purge deletecollection in %s: %v", namespace, err) + } + } + for _, device := range append(purged, guarded) { + if api.exists(device) { + t.Fatalf("%s survived the purge", device.Name) + } + } + }) + + // Fail closed: a paramRef to a ConfigMap that does not exist, under + // parameterNotFoundAction: Deny, denies every Device DELETE, including a + // Retired Device, the listed username and a deleting namespace. The API + // server reports this binding configuration error as 422 Invalid, not as + // the policy's 403 Forbidden. + failClosedRetired := lifecycled("fail-closed-retired", "default", inventory.DeviceRetired) + failClosedActive := lifecycled("fail-closed-active", "default", inventory.DeviceActive) + api.setParamRef("absent-" + cleanupConfig) + api.eventually("missing parameter denial", func() bool { + return missingParams(operator.Delete(ctx, failClosedRetired, client.DryRunAll)) + }) + t.Run("a missing ConfigMap denies every delete", func(t *testing.T) { + attempts := []struct { + name string + attempt func() error + }{ + {"Retired by an unlisted caller", func() error { return operator.Delete(ctx, failClosedRetired) }}, + {"Retired by the cleanup user", func() error { return cleanup.Delete(ctx, failClosedRetired) }}, + {"Active by the cleanup user", func() error { return cleanup.Delete(ctx, failClosedActive) }}, + {"Device in a deleting namespace", func() error { return api.admin.Delete(ctx, teardownSecond) }}, + {"purge deletecollection", func() error { + return purger.DeleteAllOf(ctx, &inventory.Device{}, client.InNamespace("default")) + }}, + } + for _, test := range attempts { + if err := test.attempt(); !missingParams(err) { + t.Fatalf("%s: %v", test.name, err) + } + } + for _, device := range []*inventory.Device{failClosedRetired, failClosedActive, teardownSecond} { + if !api.exists(device) { + t.Fatalf("%s removed while the parameter is missing", device.Name) + } + } + }) +} diff --git a/internal/registration/deletion_policy_test.go b/internal/registration/deletion_policy_test.go new file mode 100644 index 00000000..40d84390 --- /dev/null +++ b/internal/registration/deletion_policy_test.go @@ -0,0 +1,139 @@ +package registration + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "testing" + + admissionv1 "k8s.io/api/admission/v1" + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + authenticationv1 "k8s.io/api/authentication/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/apiserver/pkg/admission" + plugincel "k8s.io/apiserver/pkg/admission/plugin/cel" + "k8s.io/apiserver/pkg/admission/plugin/policy/validating" + celconfig "k8s.io/apiserver/pkg/apis/cel" + "k8s.io/apiserver/pkg/authentication/user" + "k8s.io/apiserver/pkg/cel/environment" +) + +// deletionPolicy reads the component's ValidatingAdmissionPolicy. +func deletionPolicy(t *testing.T) *admissionregistrationv1.ValidatingAdmissionPolicy { + t.Helper() + data, err := os.ReadFile("../../config/components/device-deletion-protection/policy.yaml") + if err != nil { + t.Fatal(err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var policy admissionregistrationv1.ValidatingAdmissionPolicy + err := decoder.Decode(&policy) + if errors.Is(err, io.EOF) { + t.Fatal("component has no ValidatingAdmissionPolicy") + } + if err != nil { + t.Fatal(err) + } + if policy.Kind == "ValidatingAdmissionPolicy" { + return &policy + } + } +} + +type deletionInput struct { + username string + groups []string + lifecycle string + namespaceDeleted bool + params *corev1.ConfigMap +} + +// TestDeletionPolicyCleanupIdentityOffline evaluates the policy's expression +// with the API server's admission CEL compiler, for inputs envtest cannot +// produce, such as an empty username. +func TestDeletionPolicyCleanupIdentityOffline(t *testing.T) { + policy := deletionPolicy(t) + if policy.Spec.ParamKind == nil || policy.Spec.ParamKind.APIVersion != "v1" || policy.Spec.ParamKind.Kind != "ConfigMap" { + t.Fatalf("paramKind = %+v, want core/v1 ConfigMap", policy.Spec.ParamKind) + } + if len(policy.Spec.Validations) != 1 { + t.Fatalf("validations = %d, want 1", len(policy.Spec.Validations)) + } + compiler := plugincel.NewConditionCompiler(environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion())) + evaluator := compiler.CompileCondition([]plugincel.ExpressionAccessor{&validating.ValidationCondition{Expression: policy.Spec.Validations[0].Expression}}, plugincel.OptionalVariableDeclarations{HasParams: true}, environment.StoredExpressions) + + listed := func(value string) *corev1.ConfigMap { + return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-device-cleanup", Namespace: "synthetic-device-cleanup"}, Data: map[string]string{"cleanupUsernames": value}} + } + list := listed(" synthetic-cleanup ,\n\n , \r\nsystem:synthetic-purger\r\n,") + for _, test := range []struct { + name string + input deletionInput + want bool + }{ + {"no params: listed name is not exempt", deletionInput{username: "synthetic-cleanup", lifecycle: "Active"}, false}, + {"no params: Retired is deletable", deletionInput{username: "synthetic-operator", lifecycle: "Retired"}, true}, + {"no params: deleting namespace", deletionInput{username: "synthetic-operator", lifecycle: "Active", namespaceDeleted: true}, true}, + {"listed name with padding", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: list}, true}, + {"listed name after CRLF and blank entries", deletionInput{username: "system:synthetic-purger", lifecycle: "Decommissioning", params: list}, true}, + {"unlisted name", deletionInput{username: "synthetic-operator", lifecycle: "Active", params: list}, false}, + {"prefix of a listed name", deletionInput{username: "synthetic-clean", lifecycle: "Active", params: list}, false}, + {"superset of a listed name", deletionInput{username: "synthetic-cleanup-extra", lifecycle: "Active", params: list}, false}, + {"listed name embedded", deletionInput{username: "xsynthetic-cleanup", lifecycle: "Active", params: list}, false}, + {"case differs", deletionInput{username: "Synthetic-Cleanup", lifecycle: "Active", params: list}, false}, + {"listed name as a group only", deletionInput{username: "synthetic-operator", groups: []string{"synthetic-cleanup"}, lifecycle: "Active", params: list}, false}, + {"empty username against empty entries", deletionInput{username: "", lifecycle: "Active", params: listed(",\n , \n")}, false}, + {"empty username against an empty value", deletionInput{username: "", lifecycle: "Active", params: listed("")}, false}, + {"wildcard entry is literal", deletionInput{username: "synthetic-operator", lifecycle: "Active", params: listed("*")}, false}, + {"ConfigMap without the key", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: &corev1.ConfigMap{Data: map[string]string{"other": "synthetic-cleanup"}}}, false}, + {"ConfigMap without data", deletionInput{username: "synthetic-cleanup", lifecycle: "Active", params: &corev1.ConfigMap{}}, false}, + {"params set: Retired still deletable", deletionInput{username: "synthetic-operator", lifecycle: "Retired", params: list}, true}, + {"params set: deleting namespace still deletable", deletionInput{username: "synthetic-operator", lifecycle: "Active", namespaceDeleted: true, params: list}, true}, + } { + t.Run(test.name, func(t *testing.T) { + if got := evaluateDeletion(t, evaluator, test.input); got != test.want { + t.Fatalf("admitted = %v, want %v", got, test.want) + } + }) + } +} + +func evaluateDeletion(t *testing.T, evaluator plugincel.ConditionEvaluator, input deletionInput) bool { + t.Helper() + gvk := schema.GroupVersionKind{Group: "fleet.datumapis.com", Version: "v1alpha1", Kind: "Device"} + gvr := schema.GroupVersionResource{Group: "fleet.datumapis.com", Version: "v1alpha1", Resource: "devices"} + old := &unstructured.Unstructured{Object: map[string]any{"apiVersion": gvk.GroupVersion().String(), "kind": gvk.Kind, "metadata": map[string]any{"name": "synthetic-device", "namespace": "default"}, "spec": map[string]any{"lifecycle": input.lifecycle}}} + caller := &user.DefaultInfo{Name: input.username, Groups: input.groups} + attributes := admission.NewAttributesRecord(nil, old, gvk, "default", "synthetic-device", gvr, "", admission.Delete, &metav1.DeleteOptions{}, false, caller) + versioned := &admission.VersionedAttributes{Attributes: attributes, VersionedOldObject: admission.NewLazyObject(old), VersionedKind: gvk} + request := &admissionv1.AdmissionRequest{Kind: metav1.GroupVersionKind(gvk), Resource: metav1.GroupVersionResource(gvr), Name: "synthetic-device", Namespace: "default", Operation: admissionv1.Delete, UserInfo: authenticationv1.UserInfo{Username: input.username, Groups: input.groups}} + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "default"}} + if input.namespaceDeleted { + now := metav1.Now() + namespace.DeletionTimestamp = &now + } + var params runtime.Object + if input.params != nil { + params = input.params + } + results, _, err := evaluator.ForInput(context.Background(), versioned, request, plugincel.OptionalVariableBindings{VersionedParams: params}, namespace, celconfig.RuntimeCELCostBudget) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 || results[0].Error != nil { + t.Fatalf("evaluation failed: %+v", results) + } + admitted, ok := results[0].EvalResult.Value().(bool) + if !ok { + t.Fatalf("expression returned %v, want a bool", results[0].EvalResult) + } + return admitted +} From c0f59d82b333f1cd20a3e4aa1f5fdb7246d66ca2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 17:14:14 -0600 Subject: [PATCH 11/16] docs: describe the Device cleanup identity Document the third Device deletion exception, how a deploying repository enables it with a ConfigMap and a paramRef that sets parameterNotFoundAction Deny, and that a missing ConfigMap then denies every Device delete. Note that impersonating a listed identity grants the exemption. Project deletion now completes when the cleanup identity is configured and stays blocked otherwise, unless every Device is Retired. Co-Authored-By: Claude Opus 5.5 --- .../inventory-capacity-registration.md | 186 +++++++++++++++--- docs/operations/physical-inventory.md | 7 +- 2 files changed, 164 insertions(+), 29 deletions(-) diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index e7cfe5c0..e5808df2 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -19,8 +19,9 @@ and growth limits. The user decided this was overengineering and replaced it with the following: 1. **In-service Devices are not deleted.** A reusable ValidatingAdmissionPolicy - component denies a Device `DELETE` unless the Device is `Retired` or its - namespace is being deleted. No root in this repository includes it; + component denies a Device `DELETE` unless the Device is `Retired`, its + namespace is being deleted, or the caller is a cleanup identity that the + deploying repository lists. No root in this repository includes it; deploying repositories opt in. See [Device lifecycle](#device-lifecycle) and [Device deletion protection](#device-deletion-protection). @@ -36,7 +37,8 @@ with the following: Rationale: when in-service Devices are never deleted, the live Device list already holds every identity the ledger used to remember, so a second store adds failure modes without adding information. A Device leaves the list only -after someone has retired it on purpose, or deleted its namespace. Environments +after someone has retired it on purpose, deleted its namespace, or deleted its +project through a configured cleanup identity. Environments that do not include the component, such as test and synthetic environments, do not hold real machines and do not need identity retention. @@ -209,11 +211,16 @@ when: 1. the Device's namespace is being deleted: the policy's `namespaceObject` has `metadata.deletionTimestamp` set. A missing namespace object does not - match; or -2. the Device being deleted (`oldObject`) has `spec.lifecycle: Retired`. - -Every other `DELETE` is denied with reason `Forbidden` and a message to move -the Device to `Decommissioning`, then `Retired`, first. The policy uses + match; +2. the Device being deleted (`oldObject`) has `spec.lifecycle: Retired`; or +3. the request's `userInfo.username` is listed exactly in the + `cleanupUsernames` key of the binding's parameter ConfigMap. The policy's + `paramKind` is core `v1` `ConfigMap`. This exception is off as shipped; see + [Cleanup identity](#cleanup-identity). + +Every other `DELETE` is denied with reason `Forbidden` (HTTP 403). The message +lists the three ways a delete is allowed and says to move the Device to +`Decommissioning`, then `Retired`, first. The policy uses `failurePolicy: Fail` and the binding `validationActions: [Deny]`, so an evaluation error also denies. @@ -228,13 +235,22 @@ evaluation error also denies. Confirm this on the deployed Milo before relying on it. - **Validation.** `hack/validate-overlay-isolation.sh` renders the component on its own and fails unless it is exactly this policy: the same name, - expression, `failurePolicy: Fail`, `Deny` only, and no match conditions, - selectors, exclusions, variables or parameters. It also fails if any root in - this repository renders the policy, under its own name or another, and if - the inventory component exists without this component. -- **No exemptions.** The policy does not look at the request's user, group or - service account. Cluster administrators are held to the same rule. Anyone - able to delete the binding is outside the guarantee. + expression, a `paramKind` of exactly core `v1` `ConfigMap`, + `failurePolicy: Fail`, `Deny` only, no `paramRef` on the binding, and no + match conditions, selectors, exclusions or variables. Because the expression + is compared exactly, the validator rejects wildcard or prefix username + matching, a group-based exemption, a null `params` treated as allow-all, a + dropped empty-username guard and an always-true clause. It also rejects a + `paramRef` in the component, including one with + `parameterNotFoundAction: Allow`: deploying repositories add the `paramRef`. + It fails if any root in this repository renders the policy, under its own + name or another, and if the inventory component exists without this + component. +- **The cleanup identity is the only subject exemption.** Apart from exact + usernames in the deploying repository's ConfigMap, the policy does not look + at the request's user, group or service account. Cluster administrators are + held to the same rule. Anyone able to delete or edit the binding, or to write + the parameter ConfigMap, is outside the guarantee. - **deletecollection, garbage collection and finalizers.** The API server admits each object of a collection delete individually as a `DELETE`, so a collection delete that reaches a Device that is not Retired is denied and @@ -250,19 +266,108 @@ evaluation error also denies. identities leave the duplicate check. The policy reads the namespace from the API server's namespace cache, which observes the deletion mark shortly after it is set. -- **Project deletion.** In pinned Milo `v0.36.9`, project purge first issues a - collection delete for every namespaced resource in every namespace, and only +- **Project deletion.** In pinned Milo `v0.36.9`, project purge + (`internal/controllers/projectpurge`) first issues a collection delete for + every namespaced resource in every namespace, `default` included, and only then deletes the namespaces. It never deletes `default`, which it drains in - place. In that first phase no namespace is marked yet, so a Device that is - not Retired stops the purge's collection delete. Registered Devices live in - `default`, which is never marked. A project that holds Devices that are not - Retired therefore does not finish purging while the component is installed: - retire its Devices first. This is from reading the pinned Milo source, not a - live test. + place. In that first phase no namespace is marked yet, so the + deleting-namespace exception never applies, and a denied collection delete + aborts the purge before it deletes any namespace. The purge runs as the Milo + controller-manager's own identity against the project's control plane. + - With the [cleanup identity](#cleanup-identity) configured to list that + username, the purge's collection deletes are admitted whatever the + Devices' lifecycle, and project teardown completes. + - Without it, a project that holds a Device that is not Retired does not + finish purging while the component is installed. Retire every Device + first. + + This comes from reading the pinned Milo source and from the envtest + simulation below, not from a live Milo test. - **Capacity is not deleted with its Device.** The registration webhook denies capacity deletes, so a namespace or project teardown that removes Devices still stops at their capacity; see the next section. +### Cleanup identity + +The binding ships without a `paramRef`. The policy then evaluates with +`params == null`, the third exception is off, and only the namespace and +Retired exceptions apply. A policy that declares `paramKind` does not need a +`paramRef` on its binding: Kubernetes evaluates such a binding with a null +`params` and no error. The envtest suite confirms this on Kubernetes 1.37.0. + +A deploying repository turns the exception on in the root it applies to Milo: + +1. Add a ConfigMap with a `cleanupUsernames` key that lists the usernames, one + per line or separated by commas. Entries are trimmed and empty entries are + ignored. Matching is exact and case-sensitive. Groups, prefixes and + wildcards never match, and an empty username never matches. List only the + identity that runs project cleanup: in pinned Milo, the controller-manager's + base identity. +2. Patch the binding with a `paramRef` that names that ConfigMap, sets its + `namespace` explicitly, and sets `parameterNotFoundAction: Deny`. Without + an explicit namespace, the API server looks for the ConfigMap in the + Device's own namespace. + +A synthetic example, rendered with `kustomize build`: + +```yaml +# kustomization.yaml in the deploying repository's Milo root. The component +# path stands in for however that repository vendors or references Fleet. +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +components: + - ../fleet/config/components/device-deletion-protection +resources: + - device-cleanup-identity.yaml +patches: + - target: + group: admissionregistration.k8s.io + kind: ValidatingAdmissionPolicyBinding + name: fleet-device-deletion-protection + patch: |- + - op: add + path: /spec/paramRef + value: + name: fleet-device-cleanup + namespace: example-system + parameterNotFoundAction: Deny +--- +# device-cleanup-identity.yaml +apiVersion: v1 +kind: ConfigMap +metadata: + name: fleet-device-cleanup + namespace: example-system +data: + cleanupUsernames: | + system:serviceaccount:example-system:example-controller-manager +``` + +Consequences to plan for: + +- **A missing ConfigMap denies every Device delete.** With + `parameterNotFoundAction: Deny`, a `paramRef` whose ConfigMap does not exist + denies every Device `DELETE`. That includes a Retired Device, a Device in a + deleting namespace and the listed identity's deletes, so namespace and + project teardown stop until the ConfigMap exists. This is the fail-closed + behaviour: an absent or deleted ConfigMap never widens who may delete. The + API server reports it as `422 Invalid` with the message ``no params found + for policy binding with `Deny` parameterNotFoundAction``, not as the + policy's 403. Apply the ConfigMap with the patch, or before it. Never use + `parameterNotFoundAction: Allow`: a missing ConfigMap would then skip the + policy and admit every Device `DELETE`. +- **Impersonation grants the exemption.** Anyone allowed to impersonate a + listed username is admitted as that username and can delete any Device. + Ordinary RBAC on `impersonate` applies. List only the cleanup controller's + identity, and restrict impersonation of it, and writes to the ConfigMap and + the binding, as tightly as the controller itself. +- **Where the ConfigMap lives in Milo.** The admission plugin reads the + ConfigMap through its informers. In pinned Milo `v0.36.9` those informers + run against the root control plane, not a project, so the ConfigMap belongs + in the root. This is inferred from the Milo source, as is the policy's use of + Milo's root admission for project-routed requests. Confirm on the deployed + Milo that the cleanup identity admits a project purge before relying on it. + ### Deleting a Device Deleting a Device that backs capacity, whether it is Retired, its namespace is @@ -317,9 +422,12 @@ Environment-owned inputs, none of which this repository supplies: reachability, and set `clientConfig.caBundle` to the serving CA. 3. Keep `--provider-projects` equal to the complete provider scope. 4. Decide whether the Milo root you apply includes - `config/components/device-deletion-protection`. With it, only Retired - Devices and Devices in a deleting namespace can be deleted; without it, - any authorized caller can delete a Device. + `config/components/device-deletion-protection`. With it, the only Device + deletes admitted are of Retired Devices, of Devices in a deleting namespace, + and by a configured [cleanup identity](#cleanup-identity); without it, any + authorized caller can delete a Device. If you include it, configure the + cleanup identity, or project deletion stays blocked until every Device in + the project is Retired. 5. Before rolling out the UI, verify caller-preserving project routing, named Device read denial, registration denial, capacity mutation denial, TLS rejection, Device deletion denial where installed, lifecycle transitions, and duplicate handling @@ -383,11 +491,29 @@ its manifest and checks that: move out of `Retired`; - deleting an Active or Decommissioning Device is denied for every caller, and deleting a Retired Device is allowed; +- with the shipped binding, which has no `paramRef`, the policy evaluates with + a null `params` and no error, and a would-be cleanup username is denied; - `deletecollection` over mixed Devices denies those that are not Retired; - after the namespace is deleted, its Devices can be deleted. envtest has no namespace controller, so the test issues the controller's deletions itself and they are admitted because `namespaceObject` has a deletion timestamp; -- Devices in other namespaces stay protected. +- Devices in other namespaces stay protected; +- with the ConfigMap and a `paramRef` set as a deploying repository sets them, + a listed username deletes Active and Decommissioning Devices and a mixed + collection. The admin, an unlisted user, and usernames that are a prefix, + superset, embedding, suffix or different case of a listed name are denied, + as is a user who holds a listed name only as a group. The Retired and + deleting-namespace exceptions still admit unlisted callers; +- a Milo-style purge, the listed user's collection delete in `default` and in + another namespace with mixed lifecycles, removes every Device; +- a `paramRef` to a missing ConfigMap under `parameterNotFoundAction: Deny` + denies every delete with `422 Invalid`, including a Retired Device, the + listed user, a Device in a deleting namespace and the purge. + +`internal/registration/deletion_policy_test.go` evaluates the component's +expression offline with the API server's admission CEL compiler, for cases +envtest cannot produce, such as an empty username: it never matches empty +entries, and padded, CRLF-separated entries match only exactly. Unit tests cover the remaining negative cases, normalization, cross-project duplicates, project lifetime and the packaged webhook shape. @@ -396,7 +522,11 @@ transport. `internal/api/inventory/v1alpha1/lifecycle_test.go` runs the lifecycle default and transition rules through the CRD schema offline. The overlay isolation tests fail when a root includes the deletion component and when the component's policy is renamed, made audit-only, fail-open, scoped, -exempted or given a weaker expression. Frontend tests cover the derived name, +exempted or given a weaker expression. The weaker expressions include +wildcard, prefix, group-based, null-params-allows-all, empty-username and +always-true cleanup clauses. The tests also fail on a different or missing +`paramKind`, and on a `paramRef` in the component with either +`parameterNotFoundAction`. Frontend tests cover the derived name, conflict marking including Retired Devices, and refusal of Devices that are not Active, with mocked transport. None of this is a live Milo deployment or an independent security review. diff --git a/docs/operations/physical-inventory.md b/docs/operations/physical-inventory.md index 79234491..9b172c73 100644 --- a/docs/operations/physical-inventory.md +++ b/docs/operations/physical-inventory.md @@ -335,7 +335,12 @@ that names the same claim. Leave the old Device in place and move its Retired is terminal and still counts in the duplicate-identity check while the Device exists. Environments with [Device deletion protection](../development/inventory-capacity-registration.md#device-deletion-protection) -delete a Device only once it is Retired, or with its namespace. +delete a Device only once it is Retired, or with its namespace. The one other +path is project teardown: when the deploying repository configures the +[cleanup identity](../development/inventory-capacity-registration.md#cleanup-identity), +that identity, and anyone allowed to impersonate it, can delete Devices +whatever their lifecycle, so a project purge completes. Without it, a project +that holds a Device that is not Retired cannot finish deleting. ## Relationship to the inventory proposal From 06be8efd6f396f73c4b6d9b3b17c6c89ecf3eca4 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 17:59:41 -0600 Subject: [PATCH 12/16] docs: note Milo should purge namespaces first Mark the cleanup identity exemption as a stopgap. Once Milo marks each namespace it purges, default included, before deleting its contents, the deletion policy can rely on the namespace signal alone. Co-Authored-By: Claude Opus 5.5 --- config/components/device-deletion-protection/policy.yaml | 7 +++++++ docs/development/inventory-capacity-registration.md | 7 +++++++ 2 files changed, 14 insertions(+) diff --git a/config/components/device-deletion-protection/policy.yaml b/config/components/device-deletion-protection/policy.yaml index 870d7fa6..7f96fa87 100644 --- a/config/components/device-deletion-protection/policy.yaml +++ b/config/components/device-deletion-protection/policy.yaml @@ -17,6 +17,13 @@ # and an empty username never match. Groups, prefixes and wildcards are not # consulted. # +# Exception 3 is a stopgap. Milo's project cleanup deletes namespaced +# resources before it marks any namespace for deletion, and it never deletes +# `default`, so exception 1 cannot cover project teardown today. Milo should +# mark every namespace it purges, `default` included, before deleting its +# contents. This policy can then rely on that namespace signal and drop the +# subject exemption. +# # The binding below has no paramRef, so params is null and exception 3 is off. # A deploying repository turns it on by adding the ConfigMap and patching the # binding with a paramRef that sets parameterNotFoundAction: Deny; a missing diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index e5808df2..adda25c1 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -289,6 +289,13 @@ evaluation error also denies. ### Cleanup identity +The cleanup identity is a stopgap. Milo's project cleanup deletes namespaced +resources before it marks any namespace for deletion, and it never deletes +`default`, so the namespace exception cannot cover project teardown. Milo +should mark every namespace it purges, `default` included, before deleting +its contents. The policy can then rely on that namespace signal and drop the +subject exemption. + The binding ships without a `paramRef`. The policy then evaluates with `params == null`, the third exception is off, and only the namespace and Retired exceptions apply. A policy that declares `paramKind` does not need a From b3dc951361708c5728c51ca556b84ac5b0e4facc Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 18:18:55 -0600 Subject: [PATCH 13/16] Scope registration webhook to marked capacity The capacity registration webhook matched every MachineCapacity create, update and delete, and every status write, in every namespace, and denied all but gated creates. That blocked synthetic capacity a GitOps controller re-applies, a synthetic provider's status writes, and hand-made capacity. The webhook now governs only inventory-backed capacity: capacity carrying a fleet.datumapis.com/registration-* annotation on the new or old object, or a create under the derived device- name. A match condition routes only those requests, so adding, changing or removing the marker is still denied. Status writes are no longer routed; the status subresource cannot change metadata or spec, so they cannot strip the marker or enable capacity. The handler allows unmarked requests without reading Devices. failurePolicy Fail, sideEffects None and the timeout are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../registration-admission/webhook.yaml | 21 +- docs/development/README.md | 4 +- .../inventory-capacity-registration.md | 134 +++++++++++-- internal/registration/admission.go | 64 ++++++- internal/registration/envtest_test.go | 3 +- internal/registration/manifest_test.go | 42 +++- internal/registration/scope_envtest_test.go | 180 ++++++++++++++++++ internal/registration/scope_test.go | 114 +++++++++++ 8 files changed, 533 insertions(+), 29 deletions(-) create mode 100644 internal/registration/scope_envtest_test.go create mode 100644 internal/registration/scope_test.go diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml index b75500a9..ae5a2a30 100644 --- a/config/components/registration-admission/webhook.yaml +++ b/config/components/registration-admission/webhook.yaml @@ -3,8 +3,14 @@ kind: ValidatingWebhookConfiguration metadata: name: fleet-capacity-registration webhooks: - # Every capacity write is fail-closed. Creates are checked against live - # Devices; updates, status writes and deletes are always denied. + # Only inventory-backed capacity is routed here, and it is fail-closed. + # Creates are checked against live Devices; updates and deletes are always + # denied. Capacity is inventory-backed when it carries a registration + # annotation (fleet.datumapis.com/registration-*) on the new or old object, + # or when a create uses the derived device- name. Adding, changing or + # removing a registration annotation is therefore always routed. Capacity + # without the marker, such as synthetic or hand-made capacity, and every + # status write are not routed and are governed by RBAC alone. - name: registration.fleet.datumapis.com admissionReviewVersions: [v1] failurePolicy: Fail @@ -17,5 +23,14 @@ webhooks: - apiGroups: [metal.datumapis.com] apiVersions: [v1alpha1] operations: [CREATE, UPDATE, DELETE] - resources: [machinecapacities, machinecapacities/status] + resources: [machinecapacities] scope: Namespaced + matchConditions: + - name: inventory-backed-capacity + expression: >- + (request.operation == 'CREATE' && object != null + && has(object.metadata.name) && object.metadata.name.startsWith('device-')) + || (object != null && has(object.metadata.annotations) + && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) + || (oldObject != null && has(oldObject.metadata.annotations) + && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) diff --git a/docs/development/README.md b/docs/development/README.md index 364bf6c8..f3c19b7d 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -25,7 +25,9 @@ Devices, one capacity per Device through a Device-derived name, a Device lifecycle (`Active`, `Decommissioning`, terminal `Retired`), an opt-in Device deletion protection component that admits deletes only for Retired Devices or a deleting namespace, and a session-fenced default-namespace Device picker. It admits only Disabled/Retain records with cleaning explicitly -unconfigured; deployment trust inputs and live Milo acceptance remain required. +unconfigured, and governs only capacity that carries the registration marker; +synthetic, hand-made and legacy capacity and all capacity status writes are not +routed to it. Deployment trust inputs and live Milo acceptance remain required. An opt-in [local KVM installation harness](../operations/local-vm.md) implements a bounded libvirt executor and guest installer using the same lifecycle library. It uses a disposable Kubernetes API and explicit local authority fixtures; it is diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index adda25c1..c07d418c 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -73,14 +73,16 @@ operation ID is no longer used for deduplication. An empty cleaning-policy name explicitly means **unconfigured**, not a policy named `default`, synthetic cleaning, or authorization to prepare. The CRD -permits it only while Disabled. The webhook rejects *all* capacity updates, -status updates and deletes. An update that would move capacity out of +permits it only while Disabled. The webhook rejects every update and delete +of [inventory-backed capacity](#scope-inventory-backed-capacity-only). An +update that would move capacity out of `Disabled` while its Device is `Decommissioning` or `Retired` is denied for that reason; the webhook first checks that the caller can read the Device. Real policy resolution and policy-use authorization are future prerequisites for a separately designed transition; there is no stage-1 preparation endpoint. -`cmd/fleet-registration` serves the validating webhook. For each create it: +`cmd/fleet-registration` serves the validating webhook. For each create of +inventory-backed capacity it: 1. requires Milo's authenticated `iam.miloapis.com/parent-*` extras naming a single Project in the configured provider scope, and an actor UID; @@ -106,6 +108,84 @@ stage-1 preparation endpoint. established; or - any capacity is backed by a Device that shares an alias. +## Scope: inventory-backed capacity only + +The webhook governs only **inventory-backed** capacity, meaning capacity that +registration creates from a Device. Other capacity, such as synthetic +capacity that a GitOps controller applies, capacity whose status a synthetic +provider writes, and hand-made capacity, is not routed to it at all. + +The marker is registration's own metadata: + +- any annotation whose key starts with `fleet.datumapis.com/registration-` + (the three annotations above), on the new or the old object; or +- on create only, a name starting with `device-`, the derived name. + +The marker is reliable because the webhook admits no create of +inventory-backed capacity without all three annotations and the derived +name, and admits no later update or delete of it, so the annotations cannot +be removed or changed after creation. A label was not used: registration +sets none, adding one would change the portal's wire contract, and a match +condition can read annotations directly. The name is part of the marker only +on create, so that the derived name space is reserved for registration and +no unannotated create can occupy a Device's derived name. Capacity is not +renamed, so the annotations alone identify it afterwards. + +The packaged webhook routes requests with one rule and one match condition: + +```yaml +rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE, DELETE] + resources: [machinecapacities] + scope: Namespaced +matchConditions: + - name: inventory-backed-capacity + expression: >- + (request.operation == 'CREATE' && object != null + && has(object.metadata.name) && object.metadata.name.startsWith('device-')) + || (object != null && has(object.metadata.annotations) + && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) + || (oldObject != null && has(oldObject.metadata.annotations) + && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-'))) +``` + +`object` is null for a delete and `oldObject` is null for a create. Checking +both objects routes, and so denies, an update that adds a registration +annotation to unmarked capacity, which would make it look inventory-backed, +and an update or delete that removes or changes the annotation on marked +capacity, which would let it escape the gate. `failurePolicy: Fail` applies +to a match condition that fails to evaluate. + +The handler applies the same test as defence in depth: a request for capacity +without the marker that reaches it anyway is allowed without reading Devices +or the provider project. A marked request is handled as before: creates are +gated in full, and updates, deletes and any routed subresource are denied. + +**Status writes are not routed.** `machinecapacities/status` is not in the +rule. Stage 1 has no status writer for inventory-backed capacity, but a +provider may need one later, and the webhook would then have to be changed +first. Status writes are governed by RBAC alone; in the packaged IAM roles +only the controller role holds `machinecapacities.updateStatus`. This is +acceptable because a status write cannot widen what capacity offers: + +- the CRD's status subresource ignores changes to `metadata` and `spec`, so a + status write cannot strip the marker or move capacity out of `Disabled`; +- allocation requires `spec.allocationPolicy: Enabled`, which status cannot + set. + +The envtest suite confirms the first point on Kubernetes 1.37.0. A future +stage that lets status influence availability must revisit this. + +**Unmarked capacity is not gated.** Capacity without the marker, including +legacy capacity created before registration admission, can again be created, +updated and deleted by any caller RBAC allows, with no Device check and no +Disabled requirement. It is not inventory-backed and makes no claim about a +Device. Registration still reads it: a create of inventory-backed capacity is +denied while any capacity in the provider scope references the Device, or has +unresolved physical identity. + The webhook writes nothing. Dry-run requests are evaluated like real ones (`sideEffects: None`). Controller credentials supply reads and SAR evaluation, not the caller's registration authority. Errors about records in another @@ -150,8 +230,8 @@ The duplicate check is a point-in-time list. It does not close this race: No reservation store closes this, by decision. The consequences are bounded: - B can never be registered, because A now exists and shares its alias. -- A's capacity is `Disabled`, and the webhook denies every capacity update, so - it can never become available in stage 1. +- A's capacity is `Disabled`, and the webhook denies every update of + inventory-backed capacity, so it can never become available in stage 1. - The staff registration form lists every Device and marks each one that shares an alias with another as **Conflicting**, so both A and B show the conflict until a person resolves it. @@ -193,8 +273,8 @@ Registration semantics, enforced by the registration webhook: - Only an `Active` Device can get new capacity. - Capacity whose Device is `Decommissioning` or `Retired` cannot leave - `Disabled`. Stage 1 already denies every capacity update, so this states the - rule a future enabling transition must keep. + `Disabled`. Stage 1 already denies every update of inventory-backed + capacity, so this states the rule a future enabling transition must keep. - A Retired Device still takes part in the duplicate-identity check for as long as it exists. Deleting it removes its identity from that check. @@ -284,7 +364,7 @@ evaluation error also denies. This comes from reading the pinned Milo source and from the envtest simulation below, not from a live Milo test. - **Capacity is not deleted with its Device.** The registration webhook denies - capacity deletes, so a namespace or project teardown that removes Devices + deletes of inventory-backed capacity, so a namespace or project teardown that removes Devices still stops at their capacity; see the next section. ### Cleanup identity @@ -382,18 +462,20 @@ being deleted, or the component is not installed, leaves the capacity in place, still `Disabled`. The webhook denies every update and delete of it, so it cannot become available. No owner reference links the two: the webhook rejects owner references on registration, and garbage collection would be -denied anyway because capacity deletes are fenced. The orphaned capacity keeps +denied anyway because deletes of inventory-backed capacity are fenced. The orphaned capacity keeps its Device UID annotation and name, which also prevents a replacement Device with the same name from registering. Clean it up only in environments where -capacity writes are not fenced, such as synthetic ones. +the registration webhook is not installed, such as synthetic ones. ## Production packaging and rollout - `config/milo` includes the mandatory fail-closed registration webhook (`config/components/registration-admission`). Its one entry matches - capacity create/update/delete and status in every namespace, with no - selectors or match conditions. An unreachable service blocks capacity - writes globally and nothing else: Device, namespace and Project writes do + capacity create, update and delete in every namespace, narrowed by the + [inventory-backed match condition](#scope-inventory-backed-capacity-only) + and with no selectors. Status writes are not matched. An unreachable + 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. - No root in this repository includes Device deletion protection. A deploying repository adds `config/components/device-deletion-protection` to @@ -413,8 +495,9 @@ capacity writes are not fenced, such as synthetic ones. actor identity is preserved, and that nested Organization/User contexts do not present as a Project. Only a singleton `Project`/`resourcemanager.miloapis.com` context is accepted. -- Legacy capacity writes fail closed; legacy records remain readable and - unchanged. +- Writes to inventory-backed capacity fail closed. Legacy and other unmarked + capacity is not governed by the webhook; its writes are subject to RBAC + alone. Environment-owned inputs, none of which this repository supplies: @@ -488,7 +571,22 @@ packaged webhook against a real API server and checks that: - a Decommissioning or Retired Device cannot be registered, a Retired Device still blocks a duplicate, and capacity cannot leave `Disabled` once its Device is Decommissioning or Retired; -- a webhook outage blocks capacity writes but not Device writes. +- a webhook outage blocks capacity registration but not Device writes. + +`internal/registration/scope_envtest_test.go` installs the same packaged +webhook and checks that: + +- updates and deletes of registered capacity are denied, including by the + admin; +- removing all or one registration annotation, or changing one, is denied by + update and by merge patch, and adding one to unmarked capacity is denied; +- an unannotated create under a `device-` name is denied; +- with the webhook backend closed, a synthetic capacity's server-side-apply + create and spec update, its status write, and the update and delete of + hand-made capacity in `default` all succeed, so they are not routed; +- with the backend closed, a status write on registered capacity succeeds but + leaves its annotations and spec unchanged, while its update and delete, and + adding the marker to unmarked capacity, fail closed. `internal/registration/deletion_envtest_test.go` applies the component from its manifest and checks that: @@ -522,7 +620,9 @@ expression offline with the API server's admission CEL compiler, for cases envtest cannot produce, such as an empty username: it never matches empty entries, and padded, CRLF-separated entries match only exactly. -Unit tests cover the remaining negative cases, normalization, cross-project +Unit tests cover the remaining negative cases, the handler's own scope test +(unmarked create, update, status and delete are allowed without reading +Devices; marker additions, removals and changes are denied), normalization, cross-project duplicates, project lifetime and the packaged webhook shape. `cmd/fleet-registration` tests reject unauthenticated and untrusted webhook transport. `internal/api/inventory/v1alpha1/lifecycle_test.go` runs the diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 526cdf25..3accfd7b 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -1,5 +1,10 @@ // Package registration admits inert, inventory-backed MachineCapacity records. // +// Only inventory-backed capacity is governed: capacity that carries a +// registration annotation, or a create under the derived device- name. +// Other capacity, such as synthetic or hand-made capacity, is allowed without +// reading Devices, and the packaged webhook does not route it at all. +// // The webhook keeps no state of its own. Every decision is made against live // Devices and capacities in the configured provider projects, so the API // server remains the only store. One capacity per Device is enforced by the @@ -26,6 +31,7 @@ import ( admissionv1 "k8s.io/api/admission/v1" authenticationv1 "k8s.io/api/authentication/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -36,6 +42,11 @@ const ( DeviceVersionAnnotation = "fleet.datumapis.com/registration-device-version" OperationAnnotation = "fleet.datumapis.com/registration-operation" + // RegistrationAnnotationPrefix starts every annotation registration sets. + // Any annotation with this prefix marks capacity as inventory-backed, so + // adding, changing or removing one is always gated. + RegistrationAnnotationPrefix = "fleet.datumapis.com/registration-" + // CapacityNamePrefix starts every registered capacity name. The rest of // the name is the backing Device's UID. CapacityNamePrefix = "device-" @@ -111,6 +122,14 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a if request.Resource.Group != metal.GroupVersion.Group || request.Resource.Resource != "machinecapacities" { return admission.Denied("unsupported registration admission resource") } + backed, err := inventoryBacked(request) + if err != nil { + return admission.Denied("capacity could not be decoded: " + err.Error()) + } + if !backed { + // Defence in depth: the packaged webhook does not route this request. + return admission.Allowed("capacity is not inventory-backed; registration admission does not govern it") + } if request.SubResource != "" || (request.Operation != admissionv1.Create && request.Operation != admissionv1.Update) { return admission.Denied(mutationDisabled) } @@ -130,7 +149,50 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a return admission.Allowed("inert inventory registration only; no availability or preparation authority") } -const mutationDisabled = "capacity mutation and deletion are disabled; registered and legacy capacity require operator reconciliation" +// inventoryBacked reports whether a request concerns inventory-backed +// capacity. It matches the packaged webhook's match condition: a create +// under the derived name, or a registration annotation on the new or the old +// object. Checking both objects means an update that adds the marker, and an +// update or delete that removes or changes it, are both governed. +func inventoryBacked(request admission.Request) (bool, error) { + newObject, err := registrationMetadata(request.Object.Raw) + if err != nil { + return false, err + } + oldObject, err := registrationMetadata(request.OldObject.Raw) + if err != nil { + return false, err + } + if request.Operation == admissionv1.Create && (strings.HasPrefix(request.Name, CapacityNamePrefix) || (newObject != nil && strings.HasPrefix(newObject.Name, CapacityNamePrefix))) { + return true, nil + } + return marked(newObject) || marked(oldObject), nil +} + +func registrationMetadata(raw []byte) (*metav1.PartialObjectMetadata, error) { + if len(raw) == 0 { + return nil, nil + } + object := &metav1.PartialObjectMetadata{} + if err := json.Unmarshal(raw, object); err != nil { + return nil, err + } + return object, nil +} + +func marked(object *metav1.PartialObjectMetadata) bool { + if object == nil { + return false + } + for key := range object.Annotations { + if strings.HasPrefix(key, RegistrationAnnotationPrefix) { + return true + } + } + return false +} + +const mutationDisabled = "capacity mutation and deletion are disabled for inventory-backed capacity; registration annotations cannot be added, changed or removed" // evaluateUpdate explains why a capacity update is denied. Stage 1 denies // every update. An update that would move capacity out of Disabled for a diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index 734161ed..ed002f52 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -140,7 +140,8 @@ func (api *liveAPI) installWebhook() *httptest.Server { } operator := api.actor("operator", "system:masters") api.eventually("registration webhook", func() bool { - probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "webhook-probe", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "absent"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + // Only marked capacity is routed, so the probe carries the marker. + probe := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName("webhook-probe"), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: "webhook-probe", DeviceVersionAnnotation: "1", OperationAnnotation: "webhook-probe"}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "absent"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} return apierrors.IsForbidden(operator.Create(context.Background(), probe, client.DryRunAll)) }) return server diff --git a/internal/registration/manifest_test.go b/internal/registration/manifest_test.go index 8c981b23..5bd181e2 100644 --- a/internal/registration/manifest_test.go +++ b/internal/registration/manifest_test.go @@ -3,15 +3,28 @@ package registration import ( "os" "slices" + "strings" "testing" admissionregistrationv1 "k8s.io/api/admissionregistration/v1" "sigs.k8s.io/yaml" ) -// The packaged webhook is the only gate on capacity writes, so it must stay -// fail-closed over every capacity write and must not reach anything else. -func TestPackagedWebhookFencesOnlyCapacityWrites(t *testing.T) { +// inventoryBackedCondition is the packaged webhook's only match condition. It +// routes a create under the derived name and any request whose new or old +// object carries a registration annotation, so adding, changing or removing +// the marker is always gated. +const inventoryBackedCondition = "(request.operation == 'CREATE' && object != null" + + " && has(object.metadata.name) && object.metadata.name.startsWith('device-'))" + + " || (object != null && has(object.metadata.annotations)" + + " && object.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-')))" + + " || (oldObject != null && has(oldObject.metadata.annotations)" + + " && oldObject.metadata.annotations.exists(key, key.startsWith('fleet.datumapis.com/registration-')))" + +// The packaged webhook is fail-closed over writes to inventory-backed +// capacity only. It must not route status writes, other capacity or any +// other resource. +func TestPackagedWebhookFencesOnlyInventoryBackedCapacity(t *testing.T) { data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") if err != nil { t.Fatal(err) @@ -27,14 +40,31 @@ func TestPackagedWebhookFencesOnlyCapacityWrites(t *testing.T) { if webhook.FailurePolicy == nil || *webhook.FailurePolicy != admissionregistrationv1.Fail || webhook.SideEffects == nil || *webhook.SideEffects != admissionregistrationv1.SideEffectClassNone || webhook.MatchPolicy == nil || *webhook.MatchPolicy != admissionregistrationv1.Equivalent { t.Fatal("capacity webhook must fail closed, be side-effect free and match equivalent versions") } - if webhook.NamespaceSelector != nil || webhook.ObjectSelector != nil || len(webhook.MatchConditions) != 0 { - t.Fatal("capacity webhook must not be narrowed by selectors or conditions") + if webhook.TimeoutSeconds == nil || *webhook.TimeoutSeconds != 20 { + t.Fatal("capacity webhook timeout drifted") + } + if webhook.NamespaceSelector != nil || webhook.ObjectSelector != nil { + t.Fatal("capacity webhook must not be narrowed by selectors") + } + if len(webhook.MatchConditions) != 1 || webhook.MatchConditions[0].Name != "inventory-backed-capacity" || webhook.MatchConditions[0].Expression != inventoryBackedCondition { + t.Fatalf("capacity webhook match conditions drifted: %+v", webhook.MatchConditions) } if len(webhook.Rules) != 1 { t.Fatal("capacity webhook must have exactly one rule") } rule := webhook.Rules[0] - if !slices.Equal(rule.APIGroups, []string{"metal.datumapis.com"}) || !slices.Equal(rule.Resources, []string{"machinecapacities", "machinecapacities/status"}) || !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete}) { + if !slices.Equal(rule.APIGroups, []string{"metal.datumapis.com"}) || !slices.Equal(rule.APIVersions, []string{"v1alpha1"}) || !slices.Equal(rule.Resources, []string{"machinecapacities"}) || !slices.Equal(rule.Operations, []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update, admissionregistrationv1.Delete}) || rule.Scope == nil || *rule.Scope != admissionregistrationv1.NamespacedScope { t.Fatalf("capacity webhook rule drifted: %+v", rule) } + // The condition's literals must stay in step with the handler's marker. + for _, literal := range []string{"'" + CapacityNamePrefix + "'", "'" + RegistrationAnnotationPrefix + "'"} { + if !strings.Contains(inventoryBackedCondition, literal) { + t.Fatalf("match condition does not use the handler's marker %s", literal) + } + } + for _, annotation := range []string{DeviceUIDAnnotation, DeviceVersionAnnotation, OperationAnnotation} { + if !strings.HasPrefix(annotation, RegistrationAnnotationPrefix) { + t.Fatalf("registration annotation %s is outside the marker prefix", annotation) + } + } } diff --git a/internal/registration/scope_envtest_test.go b/internal/registration/scope_envtest_test.go new file mode 100644 index 00000000..57ac1ed5 --- /dev/null +++ b/internal/registration/scope_envtest_test.go @@ -0,0 +1,180 @@ +package registration + +import ( + "context" + "testing" + + metal "go.datum.net/fleet/internal/api/v1alpha1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// syntheticCapacity is a non-inventory capacity as a GitOps controller +// applies it with server-side apply. +func syntheticCapacity(policy, cleaning string) *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "metal.datumapis.com/v1alpha1", + "kind": "MachineCapacity", + "metadata": map[string]any{ + "name": "synthetic-01", + "namespace": "synthetic-provider", + "labels": map[string]any{"fleet.datumapis.com/capacity-pool": "synthetic"}, + }, + "spec": map[string]any{ + "deviceRef": map[string]any{"name": "synthetic-device-01"}, + "allocationPolicy": policy, + "cleaningPolicyRef": map[string]any{"name": cleaning}, + "reclaimPolicy": "Retain", + }, + }} +} + +// TestWebhookGovernsOnlyInventoryBackedCapacity runs the packaged webhook +// configuration against a real API server. Capacity without the registration +// marker is never routed, so its writes succeed even with the backend gone. +// Marked capacity stays fenced, and the marker cannot be added, changed or +// removed. +func TestWebhookGovernsOnlyInventoryBackedCapacity(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + if err := api.admin.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-provider"}}); err != nil { + t.Fatal(err) + } + device := api.device("scoped", "default", "scoped-serial", "77777777-7777-7777-7777-777777777771") + webhook := api.installWebhook() + operator := api.actor("operator", "system:masters") + + registered := api.registration(device) + if err := operator.Create(ctx, registered); err != nil { + t.Fatalf("eligible registration denied: %v", err) + } + current := func() *metal.MachineCapacity { + t.Helper() + capacity := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), capacity); err != nil { + t.Fatal(err) + } + return capacity + } + + // Hand-made capacity in the inventory namespace, created while the + // webhook is serving. + handMade := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "hand-made", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := operator.Create(ctx, handMade); err != nil { + t.Fatalf("hand-made capacity denied: %v", err) + } + + t.Run("marked capacity cannot be updated or deleted", func(t *testing.T) { + capacity := current() + capacity.Labels = map[string]string{"edited": "true"} + requireDenied(t, operator.Update(ctx, capacity), "mutation and deletion are disabled") + requireDenied(t, operator.Delete(ctx, current()), "mutation and deletion are disabled") + requireDenied(t, api.admin.Delete(ctx, current()), "mutation and deletion are disabled") + }) + t.Run("the marker cannot be removed or changed", func(t *testing.T) { + stripped := current() + stripped.Annotations = nil + requireDenied(t, operator.Update(ctx, stripped), "mutation and deletion are disabled") + partial := current() + delete(partial.Annotations, DeviceUIDAnnotation) + requireDenied(t, operator.Update(ctx, partial), "mutation and deletion are disabled") + changed := current() + changed.Annotations[DeviceUIDAnnotation] = "another-device" + requireDenied(t, operator.Update(ctx, changed), "mutation and deletion are disabled") + patch := client.RawPatch("application/merge-patch+json", []byte(`{"metadata":{"annotations":{"`+DeviceUIDAnnotation+`":null,"`+DeviceVersionAnnotation+`":null,"`+OperationAnnotation+`":null}}}`)) + requireDenied(t, operator.Patch(ctx, current(), patch), "mutation and deletion are disabled") + if annotations := current().Annotations; annotations[DeviceUIDAnnotation] != string(device.UID) || len(annotations) != 3 { + t.Fatalf("marker changed: %v", annotations) + } + }) + t.Run("the marker cannot be added to unmarked capacity", func(t *testing.T) { + adopted := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(handMade), adopted); err != nil { + t.Fatal(err) + } + adopted.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} + requireDenied(t, operator.Update(ctx, adopted), "mutation and deletion are disabled") + patch := client.RawPatch("application/merge-patch+json", []byte(`{"metadata":{"annotations":{"`+OperationAnnotation+`":"adopt"}}}`)) + requireDenied(t, operator.Patch(ctx, handMade, patch), "mutation and deletion are disabled") + }) + t.Run("an unmarked create under the derived name is gated", func(t *testing.T) { + squatter := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName("77777777-0000-0000-0000-000000000000"), Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "squatted"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + requireDenied(t, operator.Create(ctx, squatter), "exact Device UID/resourceVersion") + }) + + // From here on the backend is unreachable. Only routed requests fail. + webhook.Close() + + t.Run("unmarked capacity is not routed", func(t *testing.T) { + owner := []client.ApplyOption{client.FieldOwner("synthetic-gitops"), client.ForceOwnership} + if err := api.admin.Apply(ctx, client.ApplyConfigurationFromUnstructured(syntheticCapacity("Enabled", "synthetic-tenant-reuse-v1")), owner...); err != nil { + t.Fatalf("synthetic create by apply: %v", err) + } + if err := api.admin.Apply(ctx, client.ApplyConfigurationFromUnstructured(syntheticCapacity("Disabled", "synthetic-tenant-reuse-v2")), owner...); err != nil { + t.Fatalf("synthetic spec update by apply: %v", err) + } + synthetic := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKey{Namespace: "synthetic-provider", Name: "synthetic-01"}, synthetic); err != nil { + t.Fatal(err) + } + if synthetic.Spec.AllocationPolicy != "Disabled" || synthetic.Spec.CleaningPolicyRef.Name != "synthetic-tenant-reuse-v2" { + t.Fatalf("synthetic apply did not persist: %+v", synthetic.Spec) + } + synthetic.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionTrue, Reason: "SyntheticProvider", LastTransitionTime: metav1.Now()}} + if err := api.admin.Status().Update(ctx, synthetic); err != nil { + t.Fatalf("synthetic provider status write: %v", err) + } + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(handMade), handMade); err != nil { + t.Fatal(err) + } + handMade.Labels = map[string]string{"edited": "true"} + if err := operator.Update(ctx, handMade); err != nil { + t.Fatalf("hand-made capacity update: %v", err) + } + for _, capacity := range []client.Object{synthetic, handMade} { + if err := api.admin.Delete(ctx, capacity); err != nil { + t.Fatalf("unmarked capacity delete: %v", err) + } + if api.exists(capacity) { + t.Fatal("unmarked capacity survived deletion") + } + } + }) + t.Run("marked capacity status writes are not routed", func(t *testing.T) { + // Status is governed by RBAC alone. The status subresource cannot + // change metadata, so it cannot strip the marker or touch spec. + capacity := current() + capacity.Annotations = nil + capacity.Spec.AllocationPolicy = "Enabled" + capacity.Spec.CleaningPolicyRef.Name = "invented-policy" + capacity.Status.Conditions = []metav1.Condition{{Type: "Observed", Status: metav1.ConditionUnknown, Reason: "Synthetic", LastTransitionTime: metav1.Now()}} + if err := api.admin.Status().Update(ctx, capacity); err != nil { + t.Fatalf("status write on marked capacity: %v", err) + } + after := current() + if len(after.Annotations) != 3 || after.Annotations[DeviceUIDAnnotation] != string(device.UID) || after.Spec.AllocationPolicy != "Disabled" || after.Spec.CleaningPolicyRef.Name != "" || len(after.Status.Conditions) != 1 { + t.Fatalf("status write changed more than status: %+v %+v", after.Annotations, after.Spec) + } + }) + t.Run("marked capacity writes fail closed without the backend", func(t *testing.T) { + capacity := current() + capacity.Labels = map[string]string{"edited": "true"} + if err := operator.Update(ctx, capacity); err == nil { + t.Fatal("marked capacity updated without the webhook") + } + if err := api.admin.Delete(ctx, current()); err == nil { + t.Fatal("marked capacity deleted without the webhook") + } + unmarked := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "late-hand-made", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "late"}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := api.admin.Create(ctx, unmarked); err != nil { + t.Fatalf("unmarked create without the webhook: %v", err) + } + unmarked.Annotations = map[string]string{DeviceUIDAnnotation: "adopted"} + if err := api.admin.Update(ctx, unmarked); err == nil || apierrors.IsConflict(err) { + t.Fatalf("marker added without the webhook: %v", err) + } + }) +} diff --git a/internal/registration/scope_test.go b/internal/registration/scope_test.go new file mode 100644 index 00000000..3d568722 --- /dev/null +++ b/internal/registration/scope_test.go @@ -0,0 +1,114 @@ +package registration + +import ( + "context" + "encoding/json" + "errors" + "testing" + + metal "go.datum.net/fleet/internal/api/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" +) + +func capacityRaw(t *testing.T, capacity *metal.MachineCapacity) runtime.RawExtension { + t.Helper() + raw, err := json.Marshal(capacity) + if err != nil { + t.Fatal(err) + } + return runtime.RawExtension{Raw: raw} +} + +func clone(capacity *metal.MachineCapacity) *metal.MachineCapacity { + return capacity.DeepCopyObject().(*metal.MachineCapacity) +} + +// Capacity without the registration marker is not inventory-backed. The +// handler allows it without touching Devices or the provider project, even +// when both are unavailable. +func TestUnmarkedCapacityIsNotGoverned(t *testing.T) { + handler := &Handler{Projects: []string{"provider"}, Resolve: func(context.Context, string) (Project, error) { + t.Error("unmarked capacity resolved the provider project") + return Project{}, errors.New("unavailable") + }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { + t.Error("unmarked capacity was authorized against Devices") + return errors.New("unavailable") + }} + synthetic := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "synthetic-01", Namespace: "fleet-provider", Labels: map[string]string{"fleet.datumapis.com/capacity-pool": "synthetic"}, Annotations: map[string]string{"example.com/note": "synthetic"}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: "synthetic-device"}, AllocationPolicy: "Enabled", ReclaimPolicy: "Retain", CleaningPolicyRef: metal.LocalReference{Name: "synthetic-tenant-reuse-v1"}}} + changed := clone(synthetic) + changed.Spec.AllocationPolicy = "Disabled" + resource := metav1.GroupVersionResource{Group: "metal.datumapis.com", Version: "v1alpha1", Resource: "machinecapacities"} + requests := map[string]admissionv1.AdmissionRequest{ + "create": {Operation: admissionv1.Create, Object: capacityRaw(t, synthetic)}, + "spec update": {Operation: admissionv1.Update, Object: capacityRaw(t, changed), OldObject: capacityRaw(t, synthetic)}, + "status update": {Operation: admissionv1.Update, SubResource: "status", Object: capacityRaw(t, changed), OldObject: capacityRaw(t, synthetic)}, + "delete": {Operation: admissionv1.Delete, OldObject: capacityRaw(t, synthetic)}, + } + for name, request := range requests { + t.Run(name, func(t *testing.T) { + request.Name, request.Namespace, request.Resource = synthetic.Name, synthetic.Namespace, resource + if response := handler.Handle(context.Background(), admission.Request{AdmissionRequest: request}); !response.Allowed { + t.Fatalf("unmarked capacity denied: %s", response.Result.Message) + } + }) + } +} + +// Marked capacity stays fenced, and the marker cannot be added, changed or +// removed to move capacity into or out of the gate. +func TestMarkerTransitionsAreDenied(t *testing.T) { + handler, device := fixture(t) + registration := registrationRequest(t, device) + var registered metal.MachineCapacity + if err := json.Unmarshal(registration.Object.Raw, ®istered); err != nil { + t.Fatal(err) + } + unmarked := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "hand-made", Namespace: "default"}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + adopted := clone(unmarked) + adopted.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} + enabledAdoption := clone(adopted) + enabledAdoption.Spec.AllocationPolicy = "Enabled" + stripped := clone(®istered) + stripped.Annotations = nil + changed := clone(®istered) + changed.Annotations[DeviceUIDAnnotation] = "other" + partial := clone(®istered) + delete(partial.Annotations, DeviceUIDAnnotation) + squatted := clone(unmarked) + squatted.Name = CapacityName("squatted") + cases := map[string]struct { + operation admissionv1.Operation + subresource string + object, old *metal.MachineCapacity + }{ + "marker added": {operation: admissionv1.Update, object: adopted, old: unmarked}, + "marker added while enabling": {operation: admissionv1.Update, object: enabledAdoption, old: unmarked}, + "marker removed": {operation: admissionv1.Update, object: stripped, old: ®istered}, + "marker changed": {operation: admissionv1.Update, object: changed, old: ®istered}, + "one marker removed": {operation: admissionv1.Update, object: partial, old: ®istered}, + "marked update": {operation: admissionv1.Update, object: ®istered, old: ®istered}, + "marked delete": {operation: admissionv1.Delete, old: ®istered}, + "marked status when routed": {operation: admissionv1.Update, subresource: "status", object: ®istered, old: ®istered}, + "derived name without marker": {operation: admissionv1.Create, object: squatted}, + } + for name, test := range cases { + t.Run(name, func(t *testing.T) { + request := registration + request.Operation, request.SubResource = test.operation, test.subresource + request.Object, request.OldObject = runtime.RawExtension{}, runtime.RawExtension{} + if test.object != nil { + request.Object, request.Name = capacityRaw(t, test.object), test.object.Name + } + if test.old != nil { + request.OldObject, request.Name = capacityRaw(t, test.old), test.old.Name + } + if response := handler.Handle(context.Background(), request); response.Allowed { + t.Fatal("inventory-backed capacity escaped the gate") + } + }) + } +} From 8b4e57d61d2392071d777ccacf9b5d72430c901c Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 21:02:16 -0600 Subject: [PATCH 14/16] test(registration): pin the project scope check The provider-project check was the only gate on which project a request is judged in, yet disabling it left every suite green: each Resolve stub returned a fixed route, so the route check denied first. Likewise no stub returned a route other than the one asked for. Add unit and envtest cases with a Resolve that resolves any name, and project clients and SubjectAccessReviews that fail the test if they are reached. A project outside the scope is denied on create and on an enabling update before any of them run, and a mismatched route is denied on both paths before its client is used. Disabling the scope check or either route check now fails these tests. Co-Authored-By: Claude Opus 5.5 --- internal/registration/envtest_test.go | 18 +++- internal/registration/tenancy_envtest_test.go | 91 +++++++++++++++++ internal/registration/tenancy_test.go | 99 +++++++++++++++++++ 3 files changed, 205 insertions(+), 3 deletions(-) create mode 100644 internal/registration/tenancy_envtest_test.go create mode 100644 internal/registration/tenancy_test.go diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index ed002f52..75cc4668 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -72,9 +72,15 @@ func startAPI(t *testing.T) *liveAPI { // actor impersonates a caller routed through the provider project, as Milo's // routing filters establish it. func (api *liveAPI) actor(name string, groups ...string) client.Client { + api.t.Helper() + return api.actorIn("datum-cloud", name, groups...) +} + +// actorIn impersonates a caller routed through the named project. +func (api *liveAPI) actorIn(project, name string, groups ...string) client.Client { api.t.Helper() config := rest.CopyConfig(api.config) - config.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: groups, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"datum-cloud"}}} + config.Impersonate = rest.ImpersonationConfig{UserName: name, UID: name + "-uid", Groups: groups, Extra: map[string][]string{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {project}}} actor, err := client.New(config, client.Options{Scheme: api.scheme}) if err != nil { api.t.Fatal(err) @@ -118,9 +124,15 @@ func (api *liveAPI) retire(device *inventory.Device) { // configuration and returns the server so a test can take it away. func (api *liveAPI) installWebhook() *httptest.Server { api.t.Helper() - handler := &Handler{Projects: []string{"datum-cloud"}, Resolve: func(context.Context, string) (Project, error) { + return api.installHandler(&Handler{Projects: []string{"datum-cloud"}, Resolve: func(context.Context, string) (Project, error) { return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api.admin}, nil - }, Authorize: Authorize} + }, Authorize: Authorize}) +} + +// installHandler serves the given handler behind the packaged webhook +// configuration. +func (api *liveAPI) installHandler(handler *Handler) *httptest.Server { + api.t.Helper() server := httptest.NewTLSServer(&admission.Webhook{Handler: handler}) api.t.Cleanup(server.Close) data, err := os.ReadFile("../../config/components/registration-admission/webhook.yaml") diff --git a/internal/registration/tenancy_envtest_test.go b/internal/registration/tenancy_envtest_test.go new file mode 100644 index 00000000..ef5fbe95 --- /dev/null +++ b/internal/registration/tenancy_envtest_test.go @@ -0,0 +1,91 @@ +package registration + +import ( + "context" + "sync/atomic" + "testing" + + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + authenticationv1 "k8s.io/api/authentication/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// TestWebhookJudgesOnlyTheConfiguredProject runs the provider-project scope +// check and the resolved-route check behind the packaged webhook. The +// handler's Resolve resolves any name it is given, as the production one +// does, and its project client and SubjectAccessReview fail the test when a +// request outside the configured scope, or with a mismatched route, reaches +// them. +func TestWebhookJudgesOnlyTheConfiguredProject(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + registeredDevice := api.device("tenancy-registered", "default", "tenancy-serial-1", "77777777-7777-7777-7777-777777777781") + candidate := api.device("tenancy-candidate", "default", "tenancy-serial-2", "77777777-7777-7777-7777-777777777782") + + var mismatched atomic.Bool + outOfScope := tripwire(t, "out-of-scope project") + misrouted := tripwire(t, "mismatched route") + api.installHandler(&Handler{Projects: []string{"datum-cloud"}, Resolve: func(_ context.Context, name string) (Project, error) { + if name != "datum-cloud" { + t.Errorf("Resolve(%q) was called for a project outside the scope", name) + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: name, UID: types.UID("project-" + name)}, Client: outOfScope}, nil + } + if mismatched.Load() { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "elsewhere", UID: "project-elsewhere"}, Client: misrouted}, nil + } + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "datum-cloud", UID: "project-1"}, Client: api.admin}, nil + }, Authorize: func(ctx context.Context, project Project, actor authenticationv1.UserInfo, group, resource, name string) error { + if values := actor.Extra[iam.ParentNameExtraKey]; len(values) != 1 || values[0] != "datum-cloud" { + t.Errorf("SubjectAccessReview for %s was attempted for project %v", resource, values) + return context.Canceled + } + if mismatched.Load() { + t.Errorf("SubjectAccessReview for %s was attempted after a mismatched route", resource) + return context.Canceled + } + return Authorize(ctx, project, actor, group, resource, name) + }}) + operator := api.actor("operator", "system:masters") + registered := api.registration(registeredDevice) + if err := operator.Create(ctx, registered); err != nil { + t.Fatalf("in-scope registration denied: %v", err) + } + enable := func(actor client.Client) error { + current := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), current); err != nil { + t.Fatal(err) + } + current.Spec.AllocationPolicy = "Enabled" + current.Spec.CleaningPolicyRef.Name = "invented-policy" + return actor.Update(ctx, current) + } + + // The outsider is cluster-admin in the API server, so only the webhook's + // scope check stands between it and a verdict about Devices. + outsider := api.actorIn("other-provider", "outsider", "system:masters") + t.Run("a project outside the scope cannot register", func(t *testing.T) { + capacity := api.registration(candidate) + requireDenied(t, outsider.Create(ctx, capacity), "outside the configured provider registration scope") + if api.exists(capacity) { + t.Fatal("out-of-scope registration persisted") + } + }) + t.Run("a project outside the scope cannot learn why capacity stays Disabled", func(t *testing.T) { + requireDenied(t, enable(outsider), "outside the configured provider registration scope") + }) + + mismatched.Store(true) + t.Run("a mismatched route denies registration", func(t *testing.T) { + capacity := api.registration(candidate) + requireDenied(t, operator.Create(ctx, capacity), "provider project lifetime is unavailable") + if api.exists(capacity) { + t.Fatal("misrouted registration persisted") + } + }) + t.Run("a mismatched route denies an enabling update", func(t *testing.T) { + requireDenied(t, enable(operator), "provider project lifetime is unavailable") + }) +} diff --git a/internal/registration/tenancy_test.go b/internal/registration/tenancy_test.go new file mode 100644 index 00000000..76de815d --- /dev/null +++ b/internal/registration/tenancy_test.go @@ -0,0 +1,99 @@ +package registration + +import ( + "context" + "strings" + "testing" + + "go.datum.net/fleet/internal/controller" + iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + authenticationv1 "k8s.io/api/authentication/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// tripwire is a project client that fails the test on any read or write, so +// a test can prove that a decision was reached before Devices, capacity or a +// SubjectAccessReview were touched. +func tripwire(t *testing.T, why string) client.Client { + t.Helper() + fail := func(operation string) error { + t.Errorf("%s: project client %s was called", why, operation) + return context.Canceled + } + return interceptor.NewClient(fake.NewClientBuilder().WithScheme(testScheme(t)).Build(), interceptor.Funcs{ + Get: func(context.Context, client.WithWatch, client.ObjectKey, client.Object, ...client.GetOption) error { + return fail("Get") + }, + List: func(context.Context, client.WithWatch, client.ObjectList, ...client.ListOption) error { + return fail("List") + }, + Create: func(context.Context, client.WithWatch, client.Object, ...client.CreateOption) error { + return fail("Create") + }, + }) +} + +// tripwireAuthorize fails the test if a SubjectAccessReview is attempted. +func tripwireAuthorize(t *testing.T, why string) func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { + return func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + t.Errorf("%s: SubjectAccessReview for %s was attempted", why, resource) + return context.Canceled + } +} + +// decisionPaths are the two admission paths that resolve a project: a +// registration create, and an update that tries to leave Disabled. +func decisionPaths(t *testing.T) map[string]admission.Request { + t.Helper() + _, device := fixture(t) + return map[string]admission.Request{ + "create": registrationRequest(t, device), + "enabling update": capacityUpdate(t, device, "Enabled"), + } +} + +// The provider-project check is the only gate on which project a request is +// judged in: Resolve, the webhook match conditions and the +// SubjectAccessReview all take the project from the request. A request +// routed through a project outside the configured scope must be denied +// before any of them run. The Resolve stub here behaves like the real one +// and resolves whatever name it is given, so no later check can mask a +// missing scope guard. +func TestOutOfScopeProjectIsDeniedBeforeAnyRead(t *testing.T) { + for path, request := range decisionPaths(t) { + t.Run(path, func(t *testing.T) { + why := "out-of-scope project" + handler := &Handler{Projects: []string{"provider"}, Resolve: func(_ context.Context, name string) (Project, error) { + t.Errorf("%s: Resolve(%q) was called", why, name) + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: name, UID: types.UID("project-" + name)}, Client: tripwire(t, why)}, nil + }, Authorize: tripwireAuthorize(t, why)} + request.UserInfo.Extra = map[string]authenticationv1.ExtraValue{iam.ParentKindExtraKey: {"Project"}, iam.ParentAPIGroupExtraKey: {"resourcemanager.miloapis.com"}, iam.ParentNameExtraKey: {"consumer"}} + response := handler.Handle(context.Background(), request) + if response.Allowed || !strings.Contains(response.Result.Message, "outside the configured provider registration scope") { + t.Fatalf("out-of-scope project: %+v", response.Result) + } + }) + } +} + +// Resolve must return the project that was asked for. If it returns a +// different route, the request is denied before the returned project's +// client is used for a Device read or a SubjectAccessReview. +func TestResolvedRouteMismatchIsDenied(t *testing.T) { + for path, request := range decisionPaths(t) { + t.Run(path, func(t *testing.T) { + why := "mismatched route" + handler := &Handler{Projects: []string{"provider"}, Resolve: func(context.Context, string) (Project, error) { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: "elsewhere", UID: "project-elsewhere"}, Client: tripwire(t, why)}, nil + }, Authorize: tripwireAuthorize(t, why)} + response := handler.Handle(context.Background(), request) + if response.Allowed || response.Result.Message != "provider project lifetime is unavailable" { + t.Fatalf("mismatched route: %+v", response.Result) + } + }) + } +} From 98e285f00e35a12300506ee996c1ffa8dd0cd909 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 21:02:39 -0600 Subject: [PATCH 15/16] docs(registration): record stage-2 blockers State that the provider-project scope check is the only limit on what a client certificate holder can learn until the webhook checks its caller (#149). State that allocation must not be enabled for inventory-backed capacity until the same-serial race is closed. Describe orphaned capacity: it stays Disabled and immutable, blocks a same-name replacement, and blocks every registration in the provider scope. Document re-recording the deleted machine as Retired under its old name, and pin that remediation in a unit test. List all three as stage-2 blockers. Co-Authored-By: Claude Opus 5.5 --- .../inventory-capacity-registration.md | 116 +++++++++++++++++- internal/registration/admission_test.go | 37 ++++++ 2 files changed, 149 insertions(+), 4 deletions(-) diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index c07d418c..ff900184 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -108,6 +108,34 @@ inventory-backed capacity it: established; or - any capacity is backed by a Device that shares an alias. +### Provider-project scope + +Step 1 is the only check that decides which project a request is judged in. +Nothing after it is limited to the provider projects on its own: `Resolve` +resolves whatever project name it is given, the webhook match conditions do +not look at the project, and the SubjectAccessReviews carry the request's own +user and extras. If step 1 let a project through, every later check would run +against that project. So a request whose project is outside +`--provider-projects` is denied before any project is resolved, any Device or +capacity is read, or any SubjectAccessReview is sent. The same holds for an +update that would leave `Disabled`. Separately, if `Resolve` returns a project +whose route name differs from the one requested, the request is denied before +that project's client is used. `internal/registration/tenancy_test.go` and +`tenancy_envtest_test.go` pin both checks with project clients and +SubjectAccessReview stubs that fail the test if they are called. + +**The scope check is currently the only limit on what a certificate holder can +learn.** The webhook does not yet check who is calling it +([#149](https://github.com/datum-cloud/fleet/issues/149)). Any holder of a +client certificate from the webhook's client CA can post an AdmissionReview +directly and read the verdict, and a verdict can name Devices and their +lifecycle. Such a caller writes the review's user and extras itself, so the +SubjectAccessReviews do not limit it: it can claim any identity. Until #149 is +fixed, the provider-project scope check is the only thing that bounds what it +learns, and it bounds it to the configured provider projects. Treat every +certificate from that CA as read access to Device names and lifecycle across +the provider scope. + ## Scope: inventory-backed capacity only The webhook governs only **inventory-backed** capacity, meaning capacity that @@ -238,6 +266,14 @@ No reservation store closes this, by decision. The consequences are bounded: - Any future transition that enables capacity must recheck duplicates against live Devices at that time. +**This race is open, and it blocks stage 2.** The bounds above hold only while +inventory-backed capacity stays `Disabled`. Allocation must not be enabled for +inventory-backed capacity, by the webhook allowing an update out of +`Disabled` or by any other path, until this race is closed. A recheck at +enable time narrows the window but does not close it, because a duplicate +Device can still appear after the recheck. See +[Stage 2 blockers](#stage-2-blockers). + Two registrations racing for two already-existing Devices that share an alias both fail, because each sees the other Device. Device status has no writer today, so there is no server-side eligibility condition to set; reporting @@ -462,10 +498,51 @@ being deleted, or the component is not installed, leaves the capacity in place, still `Disabled`. The webhook denies every update and delete of it, so it cannot become available. No owner reference links the two: the webhook rejects owner references on registration, and garbage collection would be -denied anyway because deletes of inventory-backed capacity are fenced. The orphaned capacity keeps -its Device UID annotation and name, which also prevents a replacement Device -with the same name from registering. Clean it up only in environments where -the registration webhook is not installed, such as synthetic ones. +denied anyway because deletes of inventory-backed capacity are fenced. + +The deletion policy narrows when this happens but does not prevent it: a +Retired Device, a Device in a deleting namespace, and a delete by a cleanup +identity are all still admitted. No root in this repository installs the +policy, so in an environment built from these roots alone any authorized +caller can delete a Device, including one that a registration checked just +before its capacity was admitted. + +The resulting orphaned capacity is in this state: + +- It stays `Disabled` and is immutable. The webhook denies every update and + delete of inventory-backed capacity for every caller, administrators + included, and an update out of `Disabled` is denied with + `its Device does not exist`. +- It keeps its Device UID annotation and its `spec.deviceRef` name. A + replacement Device created under the same name cannot register, because + the capacity already references that name. +- Its Device reference no longer resolves, so it has unresolved physical + identity. Registration denies **every** create in the provider scope while + such capacity exists, not only the same-name replacement, with + `capacity default/ has unresolved physical identity`. + `TestOrphanedCapacityBlocksUnrelatedRegistration` pins this. + +Remediation, in stage 1: + +1. Re-record the deleted machine as a Device under its **old name**, with its + original serial and system UUID, created directly in `Retired` (a Device + may be created in any lifecycle). The capacity's reference resolves again, + so other Devices can register. The Retired Device cannot register, the + capacity stays `Disabled`, and the machine's identity is back in the + duplicate check. The same test pins this. +2. Register the real replacement machine under a **new** Device name. The old + name stays bound to the old capacity. +3. Where the deletion policy is installed, do not delete the re-recorded + Retired Device: the policy admits that delete, and the capacity would be + orphaned again. + +There is no stage-1 path that removes the orphaned capacity itself in an +environment where the registration webhook is installed. Removing it would +mean taking the webhook out of the admission path, which unfences every +inventory-backed capacity write while it is out, so it needs a separately +reviewed change, not an operator action. Clean up orphaned capacity directly +only in environments where the registration webhook is not installed, such as +synthetic ones. ## Production packaging and rollout @@ -529,6 +606,24 @@ old `fleet-capacity-registration-v1` Secret, its segments, the `fleet-registration-control` ConfigMap, or the old retention policies keeps those objects until its owner removes them; the new service ignores them. +## Stage 2 blockers + +Stage 1 is safe because inventory-backed capacity never leaves `Disabled`. +These must be resolved before any stage lets it: + +1. **Close the duplicate race.** Allocation must not be enabled for + inventory-backed capacity until the + [same-serial race](#the-documented-duplicate-race) is closed. A recheck at + enable time is not enough on its own. +2. **Give orphaned capacity a way out.** Capacity whose Device was deleted + [cannot be removed](#deleting-a-device) while the webhook is installed, and + it blocks every registration in the provider scope until its Device is + re-recorded. +3. **Authenticate the webhook's caller** + ([#149](https://github.com/datum-cloud/fleet/issues/149)). Until then the + [provider-project scope check](#provider-project-scope) is the only limit + on what a certificate holder can learn. + ## UI The Datum dialog uses the existing host-session boundary and isolated read @@ -588,6 +683,19 @@ webhook and checks that: leaves its annotations and spec unchanged, while its update and delete, and adding the marker to unmarked capacity, fail closed. +`internal/registration/tenancy_envtest_test.go` installs the same packaged +webhook with a handler whose project client and SubjectAccessReview fail the +test if they are reached, and checks that: + +- a cluster-admin caller routed through a project outside the provider scope + cannot register, and cannot learn why registered capacity stays `Disabled`; +- when `Resolve` returns a different route name than the one requested, a + registration and an update that would leave `Disabled` are both denied. + +`internal/registration/tenancy_test.go` checks the same two cases on the +handler directly. Disabling the scope check, or either route-name check, fails +these tests. + `internal/registration/deletion_envtest_test.go` applies the component from its manifest and checks that: diff --git a/internal/registration/admission_test.go b/internal/registration/admission_test.go index cfde8b47..d39bb5e0 100644 --- a/internal/registration/admission_test.go +++ b/internal/registration/admission_test.go @@ -355,6 +355,43 @@ func TestReplacementDeviceUnderSameNameCannotRegister(t *testing.T) { } } +// Capacity whose Device was deleted has no resolvable identity, so it blocks +// every registration in the provider scope, not only a same-name +// replacement. The operator guide documents this and its remediation. +func TestOrphanedCapacityBlocksUnrelatedRegistration(t *testing.T) { + handler, device := fixture(t) + api := providerClient(t, handler) + registered := &metal.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: CapacityName(device.UID), Namespace: "default", Annotations: map[string]string{DeviceUIDAnnotation: string(device.UID)}}, Spec: metal.MachineCapacitySpec{DeviceRef: metal.LocalReference{Name: device.Name}, AllocationPolicy: "Disabled", ReclaimPolicy: "Retain"}} + if err := api.Create(context.Background(), registered); err != nil { + t.Fatal(err) + } + if err := api.Delete(context.Background(), device); err != nil { + t.Fatal(err) + } + unrelated := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "unrelated", Namespace: "default", UID: "device-unrelated"}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "unrelated-serial", SystemUUID: "55555555-5555-5555-5555-555555555555", Model: "test"}}} + if err := api.Create(context.Background(), unrelated); err != nil { + t.Fatal(err) + } + response := handler.Handle(context.Background(), registrationRequest(t, unrelated)) + if response.Allowed || !strings.Contains(response.Result.Message, "capacity "+registered.Namespace+"/"+registered.Name+" has unresolved physical identity") { + t.Fatalf("registration beside orphaned capacity: %+v", response.Result) + } + + // Remediation: re-record the deleted machine under its old name and + // identity as Retired. The capacity resolves again and stays Disabled, + // the re-recorded Device cannot register, and other Devices can. + restored := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: device.Name, Namespace: "default", UID: "device-restored"}, Spec: inventory.DeviceSpec{Lifecycle: inventory.DeviceRetired, Identity: device.Spec.Identity}} + if err := api.Create(context.Background(), restored); err != nil { + t.Fatal(err) + } + if response := handler.Handle(context.Background(), registrationRequest(t, unrelated)); !response.Allowed { + t.Fatalf("registration still blocked after re-recording the Device: %s", response.Result.Message) + } + if handler.Handle(context.Background(), registrationRequest(t, restored)).Allowed { + t.Fatal("re-recorded Retired Device registered") + } +} + func TestNonConflictingLegacyCapacityAndAllocationRemainUntouched(t *testing.T) { handler, device := fixture(t) ctx := context.Background() From b01ce4862991d002df43084c6e8123cf36690f21 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sun, 22 Nov 2026 21:02:43 -0600 Subject: [PATCH 16/16] docs(registration): explain leftover ledger cleanup Prune removes only what the ledger manifests applied. List the objects the ledger revisions created at runtime: the root Secret and sealed segment Secrets in fleet-system-private and the control ConfigMap in fleet-system. Say to remove them by hand, in which order, and not to delete the shared private namespace. Environments that never deployed the registration service have nothing to clean. Co-Authored-By: Claude Opus 5.5 --- .../inventory-capacity-registration.md | 47 +++++++++++++++++-- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index ff900184..ff7b146b 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -601,10 +601,49 @@ Environment-owned inputs, none of which this repository supplies: in the target environment. This change performs **no live writes or deployment**, so it does not claim those checks. -Removing the ledger deletes nothing live. An environment that bootstrapped the -old `fleet-capacity-registration-v1` Secret, its segments, the -`fleet-registration-control` ConfigMap, or the old retention policies keeps -those objects until its owner removes them; the new service ignores them. +### Leftover ledger objects + +Removing the ledger deletes nothing that the ledger service or its operator +created at runtime. GitOps prune removes only what the old manifests applied. +The ledger revisions created these objects on the host cluster: + +| Object | Namespace | Created by | Removed by prune | +| --- | --- | --- | --- | +| Secret `fleet-capacity-registration-v1` (the ledger root) | `fleet-system-private` | the operator, once, at bootstrap | no | +| Immutable Secrets `fleet-registration-segment--` (sealed segments) | `fleet-system-private` | the registration service, on expansion | no | +| ConfigMap `fleet-registration-control` (`public.pem`, `request.json`) | `fleet-system` | the environment owner | only if the owner applied it with GitOps and has stopped | +| ValidatingAdmissionPolicies and bindings `fleet-registration-ledger-protection` and `fleet-registration-namespace-protection` | cluster | `config/base/registration` | yes | +| Role and RoleBinding `fleet-registration-ledger` | `fleet-system-private` | `config/base/registration` | yes | + +Remove the Secrets and the ConfigMap by hand. The current service never reads +them, and they hold Device identity digests, project names and signed control +requests that no longer protect anything. If you want a record of the +identities the ledger retained, export the Secrets to private storage outside +Git first. Do not delete the `fleet-system-private` namespace: the manager +keeps its own private records there. + +Delete in this order, on the host cluster, after the current registration +release is running and no older registration pod remains: + +```sh +# 1. The retention policies must be gone, or they deny the Secret delete. +kubectl get validatingadmissionpolicybindings \ + fleet-registration-ledger-protection fleet-registration-namespace-protection +# Expect NotFound for both. If either exists, prune did not run; fix that +# first rather than deleting the policies by hand. + +# 2. The ledger root and its segments. +kubectl -n fleet-system-private delete secret fleet-capacity-registration-v1 --ignore-not-found +kubectl -n fleet-system-private get secrets -o name \ + | grep '^secret/fleet-registration-segment-' \ + | xargs -r kubectl -n fleet-system-private delete + +# 3. The control ConfigMap, after removing it from the environment overlay. +kubectl -n fleet-system delete configmap fleet-registration-control --ignore-not-found +``` + +Environments that never deployed the registration service have none of these +objects and nothing to clean. ## Stage 2 blockers