diff --git a/cmd/fleet-registration/main.go b/cmd/fleet-registration/main.go index 98c80483..4e99bbb2 100644 --- a/cmd/fleet-registration/main.go +++ b/cmd/fleet-registration/main.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "os" + "slices" "sort" "strings" "time" @@ -24,24 +25,27 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" + "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/custody/creatorwebhook" ) func main() { - var configFile, providers, cert, key, clientCA string + var configFile, providers, cert, key, clientCA, clients, projectors string flag.StringVar(&configFile, "config", "", "Fleet manager discovery configuration") flag.StringVar(&providers, "provider-projects", "", "complete comma-separated provider scope searched for duplicate hardware identity") flag.StringVar(&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(&clients, "client-identities", "", "required comma-separated subjects of the API-server webhook client certificates; any other certificate is refused") + flag.StringVar(&projectors, "capacity-projectors", "", "comma-separated usernames of the capacity projector, the only writer of registered capacity status") flag.Parse() - if err := run(ctrl.SetupSignalHandler(), configFile, providers, cert, key, clientCA); err != nil { + if err := run(ctrl.SetupSignalHandler(), configFile, providers, cert, key, clientCA, list(clients), list(projectors)); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } -func run(ctx context.Context, configFile, providers, cert, key, clientCA string) error { +func run(ctx context.Context, configFile, providers, cert, key, clientCA string, clients, projectors []string) error { config, err := projectdiscovery.LoadConfig(configFile) if err != nil { return err @@ -72,7 +76,11 @@ func run(ctx context.Context, configFile, providers, cert, key, clientCA string) } } handler := registration.NewHandler(config.AuthorityID, projects, root, template, scheme) - tlsConfig, err := webhookTLS(clientCA) + handler.Projectors = projectors + // No cleaning policy resolver exists yet: the cleaning policy owner + // provides it. Until then no registered capacity can be enabled. + handler.Cleaning = capacity.Unresolved + tlsConfig, err := webhookTLS(clientCA, clients) if err != nil { return err } @@ -101,7 +109,24 @@ func providerScope(providers string) ([]string, error) { return projects, nil } -func webhookTLS(clientCA string) (*tls.Config, error) { +func list(value string) []string { + var out []string + for _, item := range strings.Split(value, ",") { + if item = strings.TrimSpace(item); item != "" { + out = append(out, item) + } + } + return out +} + +// webhookTLS accepts only clients whose certificate chains to the dedicated +// client CA and whose subject common name is one of the configured API +// server identities. Any other certificate is refused during the handshake, +// before a request is read. +func webhookTLS(clientCA string, identities []string) (*tls.Config, error) { + if len(identities) == 0 { + return nil, errors.New("--client-identities must name the API-server webhook clients") + } caBytes, err := os.ReadFile(clientCA) if err != nil { return nil, err @@ -110,5 +135,11 @@ func webhookTLS(clientCA string) (*tls.Config, error) { if !pool.AppendCertsFromPEM(caBytes) { return nil, errors.New("API-server client CA is invalid") } - return &tls.Config{MinVersion: tls.VersionTLS13, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool}, nil + return &tls.Config{MinVersion: tls.VersionTLS13, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: pool, + VerifyConnection: func(state tls.ConnectionState) error { + if len(state.PeerCertificates) == 0 || !slices.Contains(identities, state.PeerCertificates[0].Subject.CommonName) { + return errors.New("the client certificate is not a configured API-server webhook client") + } + return nil + }}, nil } diff --git a/cmd/fleet-registration/main_test.go b/cmd/fleet-registration/main_test.go index c93dbcf3..668aae19 100644 --- a/cmd/fleet-registration/main_test.go +++ b/cmd/fleet-registration/main_test.go @@ -37,7 +37,7 @@ func TestWebhookRequiresTrustedAPIServerClient(t *testing.T) { if err := os.WriteFile(path, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca}), 0600); err != nil { t.Fatal(err) } - config, err := webhookTLS(path) + config, err := webhookTLS(path, []string{"synthetic-api-server"}) if err != nil { t.Fatal(err) } @@ -68,7 +68,23 @@ func TestWebhookRequiresTrustedAPIServerClient(t *testing.T) { response.Body.Close() t.Fatal("untrusted client certificate was accepted") } - if _, err := webhookTLS(filepath.Join(t.TempDir(), "absent")); err == nil { + if _, err := webhookTLS(filepath.Join(t.TempDir(), "absent"), []string{"synthetic-api-server"}); err == nil { t.Fatal("missing CA accepted") } + if _, err := webhookTLS(path, nil); err == nil { + t.Fatal("a webhook with no configured client identity started") + } + // A certificate from the same CA with another subject is refused during + // the handshake. + other := &x509.Certificate{SerialNumber: big.NewInt(3), Subject: pkix.Name{CommonName: "synthetic-other-client"}, NotBefore: issuer.NotBefore, NotAfter: issuer.NotAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, KeyUsage: x509.KeyUsageDigitalSignature} + otherCertificate, err := x509.CreateCertificate(rand.Reader, other, issuer, publicKey, privateKey) + if err != nil { + t.Fatal(err) + } + otherTransport := server.Client().Transport.(*http.Transport).Clone() + otherTransport.TLSClientConfig.Certificates = []tls.Certificate{{Certificate: [][]byte{otherCertificate}, PrivateKey: privateKey}} + if response, err := (&http.Client{Transport: otherTransport}).Get(server.URL); err == nil { + response.Body.Close() + t.Fatal("a client certificate with an unlisted subject was accepted") + } } diff --git a/config/base/registration/deployment.yaml b/config/base/registration/deployment.yaml index 327f18fe..553a94b4 100644 --- a/config/base/registration/deployment.yaml +++ b/config/base/registration/deployment.yaml @@ -50,6 +50,11 @@ spec: args: - --config=/etc/fleet/manager/config.yaml - --provider-projects=datum-cloud + # Environment-owned: the subjects of the API-server webhook + # client certificates, and the capacity projector's username. + # The placeholders accept no real caller. + - --client-identities=replace-with-api-server-webhook-client + - --capacity-projectors=replace-with-capacity-projector ports: - name: https containerPort: 9443 diff --git a/config/components/registration-admission/webhook.yaml b/config/components/registration-admission/webhook.yaml index ae5a2a30..96505547 100644 --- a/config/components/registration-admission/webhook.yaml +++ b/config/components/registration-admission/webhook.yaml @@ -4,13 +4,15 @@ metadata: name: fleet-capacity-registration webhooks: # 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. + # Creates are checked against live Devices. Updates may change only the + # allocation policy, cleaning policy and pool label, under the stage-2 + # rules; deletes only remove Disabled capacity whose Device is gone or + # Retired; status writes come only from the capacity projector. 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. Capacity without the marker, such + # as synthetic or hand-made capacity, is not routed and is governed by RBAC + # alone. - name: registration.fleet.datumapis.com admissionReviewVersions: [v1] failurePolicy: Fail @@ -23,7 +25,7 @@ webhooks: - apiGroups: [metal.datumapis.com] apiVersions: [v1alpha1] operations: [CREATE, UPDATE, DELETE] - resources: [machinecapacities] + resources: [machinecapacities, machinecapacities/status] scope: Namespaced matchConditions: - name: inventory-backed-capacity diff --git a/docs/development/inventory-capacity-registration.md b/docs/development/inventory-capacity-registration.md index b3b12759..27d460bc 100644 --- a/docs/development/inventory-capacity-registration.md +++ b/docs/development/inventory-capacity-registration.md @@ -1,9 +1,13 @@ -# Inventory-backed capacity registration, stage 1 +# Inventory-backed capacity registration [Implementation status](README.md) · [Inventory proposal](../proposals/fleet-management/inventory.md) · [Enrollment contract](../proposals/fleet-management/bare-metal-provisioning.md#enrollment-and-explicit-preparation) -This implements an inert registration boundary, not hardware enrollment, -preparation, allocation, or verification. It supersedes the blocker-only UI +Stage 1 registers inert, `Disabled` capacity. [Stage 2](#stage-2) lets +registered capacity be enabled, removed when orphaned, and written only by +the capacity projector, as the [commissioning +proposal](https://github.com/datum-cloud/fleet/pull/185) describes. Sections +below that describe stage 1 say where stage 2 changed them. Registration is +not hardware enrollment, preparation, allocation or verification. It supersedes the blocker-only UI guardrail in PR140 (`12439e1fdf0d229352b4e32c27d9985993ca117d`). The synthetic name-derived Device reference, invented cleaning default, allocation checkbox, and unrestricted frontend create helper remain removed. Existing capacity @@ -73,11 +77,12 @@ 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 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 +permits it only while Disabled. Updates and deletes of [inventory-backed +capacity](#scope-inventory-backed-capacity-only) follow the [stage 2 +rules](#stage-2); stage 1 denied all of them. 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. @@ -126,9 +131,10 @@ 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 +**Stage 1 did not check who called the webhook** +([#149](https://github.com/datum-cloud/fleet/issues/149)); stage 2 does, as +[Who may call the webhook](#who-may-call-the-webhook) describes. Before that +change: 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 @@ -153,8 +159,8 @@ The marker is registration's own metadata: 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 +name, and no later update may add, change or remove a registration +annotation, 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 @@ -168,7 +174,7 @@ rules: - apiGroups: [metal.datumapis.com] apiVersions: [v1alpha1] operations: [CREATE, UPDATE, DELETE] - resources: [machinecapacities] + resources: [machinecapacities, machinecapacities/status] scope: Namespaced matchConditions: - name: inventory-backed-capacity @@ -193,8 +199,9 @@ 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 +**Stage 2 routes status writes** to registered capacity and admits them only +from the capacity projector; see [Stage 2](#stage-2). In stage 1, +`machinecapacities/status` was 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 capacity projector role holds `machinecapacities.updateStatus`. This is @@ -260,21 +267,21 @@ 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 update of - inventory-backed capacity, so it can never become available in stage 1. +- In stage 1, A's capacity was `Disabled`, and the webhook denied every + update of inventory-backed capacity, so it could never become available. - 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. -**This race is open, and it blocks stage 2.** The bounds above hold only while +**In stage 1 this race was open, and it blocked stage 2.** Stage 2 makes it +harmless rather than closing it; see [The duplicate race](#the-duplicate-race). 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). +Device can still appear after the recheck. 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 @@ -311,8 +318,7 @@ 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 update of inventory-backed - capacity, so this states the rule a future enabling transition must keep. + `Disabled`. Stage 2 enforces this when it enables capacity. - 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. @@ -401,9 +407,10 @@ 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 - deletes of inventory-backed capacity, so a namespace or project teardown that removes Devices - still stops at their capacity; see the next section. +- **Capacity is not deleted with its Device.** The registration webhook + admits the delete of registered capacity only once it is `Disabled` and its + Device is gone or Retired, so a namespace or project teardown that removes + Devices still stops at enabled capacity; see the next section. ### Cleanup identity @@ -497,10 +504,10 @@ Consequences to plan for: 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 deletes of inventory-backed capacity are fenced. +place, still `Disabled`. It cannot be enabled, because enabling needs its +Device. No owner reference links the two: the webhook rejects owner +references on registration and on every later update. Stage 2 lets a person +remove it; see [Removing orphaned capacity](#removing-orphaned-capacity). 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 @@ -511,10 +518,9 @@ 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 stays `Disabled`: an update out of `Disabled` is denied with `its Device + does not exist`. In stage 1 it was also immutable and could not be + deleted. - 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. @@ -524,7 +530,8 @@ The resulting orphaned capacity is in this state: `capacity default/ has unresolved physical identity`. `TestOrphanedCapacityBlocksUnrelatedRegistration` pins this. -Remediation, in stage 1: +Stage 2 removes such capacity directly: see [Removing orphaned +capacity](#removing-orphaned-capacity). The stage-1 remediation, still valid: 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 @@ -538,24 +545,24 @@ Remediation, in stage 1: 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. +In stage 1 nothing could remove the orphaned capacity itself while the +webhook was installed. ## Production packaging and rollout - `config/milo` includes the mandatory fail-closed registration webhook (`config/components/registration-admission`). Its one entry matches - 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. + capacity create, update and delete, and capacity status writes, in every + namespace, narrowed by the [inventory-backed match + condition](#scope-inventory-backed-capacity-only) and with no selectors. An + unreachable service blocks writes to inventory-backed capacity, including + the projector's status writes, and nothing else: unmarked capacity, Device, + namespace and Project writes do not pass through the registration webhook. +- The same server serves the creator webhook for Device operations. Its + `--client-identities` pin applies to both, so until an environment sets the + real API-server identities, the base manifest's placeholder refuses every + caller: no capacity registration and no operation create succeeds. `args` + is a list, so an overlay replaces it as a whole. - 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. @@ -589,7 +596,11 @@ Environment-owned inputs, none of which this repository supplies: `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. +3. Keep `--provider-projects` equal to the complete provider scope. Set + `--client-identities` to the subjects of the API-server webhook client + certificates, and `--capacity-projectors` to the capacity projector's + username. The projector writes status through the provider project, so + its requests carry the project context the webhook requires. 4. Decide whether the Milo root you apply includes `config/components/device-deletion-protection`. With it, the only Device deletes admitted are of Retired Devices, of Devices in a deleting namespace, @@ -648,23 +659,136 @@ kubectl -n fleet-system delete configmap fleet-registration-control --ignore-not Environments that never deployed the registration service have none of these objects and nothing to clean. -## 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. +## Stage 2 + +Stage 1 kept registered capacity `Disabled` until three blockers closed. Stage +2 closes each, and lets capacity be enabled. It is **implemented**, and +verified by tests against a real API server behind the packaged webhook +(`TestStageTwoEnablesRegisteredCapacity`) and by handler tests. + +### Enabling registered capacity + +The webhook admits an update of registered capacity that changes only +`spec.allocationPolicy`, `spec.cleaningPolicyRef` and the +`fleet.datumapis.com/capacity-pool` label. Every other change, including the +registration annotations and other labels, is denied. + +- While the capacity is `Disabled`, the three fields change freely. +- While it is `Enabled`, the only permitted change is to `Disabled`. +- Moving to `Enabled` requires, at the time of the update: the caller's + `update` permission on the capacity and `get` on its Device; the annotated + Device incarnation, `Active`, not deleting, and still recording a complete, + non-placeholder identity; a pool label; a cleaning policy that resolves; + and no other Device in the provider scope, Retired ones included, that + shares an identity alias. +- An update that changes none of the three fields, such as an unchanged + apply, is admitted. + +Enabling does not require commissioning. The capacity projector offers the +capacity only once it is `Prepared` and `Healthy`. + +**The pool label.** The capacity operator sets the pool label at registration +or while the capacity is `Disabled`. It is frozen while the capacity is +`Enabled`, so a MachineClass never gains or loses capacity without the +capacity being disabled first. + +**The cleaning policy.** The webhook resolves the policy name through a +resolver that returns a digest, `ErrUnresolved`, or another error. Fleet owns +the production cleaning-policy resolver. It is built on the cleaning policy +pinned at allocation ([#183](https://github.com/datum-cloud/fleet/pull/183), +[#193](https://github.com/datum-cloud/fleet/pull/193)) and lands with the +cleaning stack. Until then the webhook uses one that resolves nothing, so no +registered capacity can be enabled in production. + +### The duplicate race + +The race in [The documented duplicate race](#the-documented-duplicate-race) +is not prevented: no object can make one Device's create and another +Device's registration atomic. Stage 2 makes the duplicate harmless instead. + +- Commissioning reads the serial number and system UUID from the BMC and + fails if they differ from the Device's. Admission refuses a BMC key that + another Device records. A `Prepared` server is the one its record names. +- Enabling, the projector's `Available`, and the allocator each refuse a + Device with a duplicate, at the moment they act. +- The window left is between the allocator's check and its custody claim. + Nothing catches a duplicate recorded in it, but that duplicate does not + change which server the customer gets, because commissioning proved the + serial number and system UUID over the BMC. The provider host tuple is not + proven by the BMC; for that alias the recheck is the only protection. + +To resolve a conflict, correct the wrong record's identity, or move it to +`Decommissioning`, then `Retired`, and delete it. + +### Removing orphaned capacity + +The webhook admits the delete of registered capacity when it is `Disabled`; +its annotated Device is missing, another incarnation, or `Retired`; no +MachineAllocation in its namespace that is not `Released` names it; and the +caller may delete it. Enabling needs an `Active` Device of the annotated +incarnation, so the capacity stays `Disabled`. An allocator that selected the +capacity while it was enabled re-reads it after creating its allocation, and +withdraws the allocation, before claiming the Device, if the capacity is gone +or `Disabled`. Any other delete of registered capacity is still denied. + +### Disabling races a claim already past its check + +Disabling stops every new selection, and every claim that has not yet +re-read the capacity. It does not stop a claim already past that re-read. +The custody claim is a conditional update of the Device's custody alone, and +Kubernetes has no write conditional on a second object, so the claim cannot +also require the capacity to be unchanged. An allocation whose claim passed +the check holds the Device as if it had been made a moment before the +capacity was disabled. It is released the normal way, and while it is not +`Released` the capacity cannot be removed. A test pins this interleaving. + +### The Device incarnation + +Registered capacity records its Device's incarnation in metadata, never in +its spec: the name is `device-` and the Device UID, and the +`registration-device-uid` annotation repeats it. Registration keeps both +unchanged. A Device recreated under the same name inherits nothing: the +webhook refuses to enable the old capacity for it, and the projector reports +the capacity not `Prepared` (`DeviceReplaced`), so the allocator never offers +it. The allocator also skips such capacity when it reads the Device after the +offer, and withdraws an allocation that has not claimed its Device once the +Device is no longer the incarnation the allocation names. A Device recreated +after that last check is still not claimed: the custody claim takes the +incarnation from the allocation's `device-uid` label and refuses unless both +the live Device and custody name it, so the allocation is withdrawn and the +allocator selects again (`TestADeviceRecreatedAfterTheLastCheckIsNotClaimed`). +These checks land with stage 2 because enabling is what makes a recreated +Device reachable: before it, registered capacity could not leave `Disabled`, +so it was never offered. The custody claim's check of the live Device +predates stage 2; stage 2 adds the test above, which fails without it. +The name carries the raw UID rather than a hash of it, as stage 1 named it; it +is deterministic and holds one capacity per incarnation. The no-UIDs-in-spec +rule allows a UID in a name, so the naming stays. + +### Status writes + +`machinecapacities/status` is in the webhook rule. A status write to +registered capacity is admitted only from a username in +`--capacity-projectors`. The webhook fails closed, so an outage stops status +updates. The allocator evaluates capacity from live evidence and never reads +the conditions, so stale or edited status cannot make a server allocatable. +Status writes to unmarked capacity are still not routed. + +### Who may call the webhook + +The webhook accepts a client only if its certificate chains to the dedicated +client CA **and** its subject common name is in `--client-identities`. Any +other certificate is refused during the TLS handshake, before a request is +read. The flag is required. The environment must keep the CA dedicated to the +API servers that call the webhook; the identity list is a second check, not a +replacement for that. + +### Configuration + +| Flag | Meaning | +| --- | --- | +| `--client-identities` | Required. Subjects of the API-server webhook client certificates. The base manifest carries a placeholder that admits no caller. | +| `--capacity-projectors` | Usernames of the capacity projector. Empty denies every status write to registered capacity. | ## UI @@ -685,12 +809,9 @@ 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. -Registration sets no `fleet.datumapis.com/capacity-pool` label, so no -MachineClass selects registered capacity. The webhook does not inspect labels -on create, but it denies every later update, so a label set at registration -could never be corrected, and registered capacity stays `Disabled` in this -stage anyway. Which writer sets the pool label, at registration or when a -future stage enables capacity, is undecided. +The registration form sets no pool label. The capacity operator sets it +while the capacity is `Disabled`; see [Enabling registered +capacity](#enabling-registered-capacity). The UI does not yet edit it. ## Verification diff --git a/internal/allocation/allocator.go b/internal/allocation/allocator.go index deefd850..46d809b0 100644 --- a/internal/allocation/allocator.go +++ b/internal/allocation/allocator.go @@ -29,6 +29,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/custody" "go.datum.net/fleet/internal/tenancy" ) @@ -222,6 +223,19 @@ func (a *Allocator) claim(ctx context.Context, allocation *fleetv1.MachineAlloca case fleetv1.AllocationReleasing, fleetv1.AllocationReleased: return false, ErrReleased } + // The capacity may have been disabled or removed, or its Device + // recreated, after it was selected. An allocation that has not claimed + // its Device yet is withdrawn then, so removing Disabled capacity never + // races an allocation onto it and a recreated Device inherits nothing. + if allocation.Status.Phase != fleetv1.AllocationActive { + usable, err := a.capacityUsable(ctx, allocation) + if err != nil { + return false, err + } + if !usable && !a.holds(ctx, allocation) { + return false, a.withdraw(ctx, allocation) + } + } err := a.Custody.Claim(ctx, allocation.Spec.DeviceRef.Name, types.UID(allocation.Labels[fleetv1.LabelDeviceUID]), allocation.Name) switch { case err == nil: @@ -232,11 +246,58 @@ func (a *Allocator) claim(ctx context.Context, allocation *fleetv1.MachineAlloca return false, ErrCustodyLost } // No effect ran under this allocation: it never held the Device. + return false, a.withdraw(ctx, allocation) +} + +// withdraw deletes an allocation that never held its Device. +func (a *Allocator) withdraw(ctx context.Context, allocation *fleetv1.MachineAllocation) error { uid, version := allocation.UID, allocation.ResourceVersion if err := a.Provider.Delete(ctx, allocation, client.Preconditions{UID: &uid, ResourceVersion: &version}); err != nil && !apierrors.IsNotFound(err) && !apierrors.IsConflict(err) { + return err + } + return nil +} + +// capacityUsable reports whether the allocation's capacity still exists, +// enabled and not deleting, and its Device is still the incarnation the +// allocation and the capacity's registration name. +func (a *Allocator) capacityUsable(ctx context.Context, allocation *fleetv1.MachineAllocation) (bool, error) { + reference := allocation.Spec.MachineCapacityRef + machine := &fleetv1.MachineCapacity{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: reference.Namespace, Name: reference.Name}, machine); apierrors.IsNotFound(err) { + return false, nil + } else if err != nil { + return false, err + } + if machine.Spec.AllocationPolicy != "Enabled" || !machine.DeletionTimestamp.IsZero() { + return false, nil + } + device := &inventory.Device{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, device); apierrors.IsNotFound(err) { + return false, nil + } else if err != nil { return false, err } - return false, nil + return string(device.UID) == allocation.Labels[fleetv1.LabelDeviceUID] && registeredFor(machine, device), nil +} + +// registeredFor reports whether registered capacity was created for this +// Device incarnation. Capacity that registration did not create records +// none. +func registeredFor(machine *fleetv1.MachineCapacity, device *inventory.Device) bool { + registered, ok := machine.Annotations[capacity.RegisteredDeviceUID] + return !ok || registered == string(device.UID) +} + +// holds reports whether custody already names the allocation, as after a +// claim whose phase write was lost. +func (a *Allocator) holds(ctx context.Context, allocation *fleetv1.MachineAllocation) bool { + state := &ops.DeviceCustody{} + if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: allocation.Spec.DeviceRef.Name}, state); err != nil { + return false + } + holder := state.Spec.Holder + return holder.AllocationRef != nil && holder.AllocationRef.Name == allocation.Name } // candidate returns the first capacity, by name, that the projection offers @@ -285,6 +346,10 @@ func (a *Allocator) candidate(ctx context.Context, request Request, tried map[st if inventory.CapacityBackingError(device) != nil { continue } + // The Device may have been recreated since the projection read it. + if !registeredFor(capacity, device) { + continue + } state := &ops.DeviceCustody{} if err := a.Provider.Get(ctx, client.ObjectKey{Namespace: a.Namespace, Name: device.Name}, state); apierrors.IsNotFound(err) { continue diff --git a/internal/allocation/capacity_test.go b/internal/allocation/capacity_test.go index c38a820c..98aeec47 100644 --- a/internal/allocation/capacity_test.go +++ b/internal/allocation/capacity_test.go @@ -1,13 +1,17 @@ package allocation import ( + "context" "errors" "testing" + "time" inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" ops "go.datum.net/fleet/internal/api/operations/v1alpha1" fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + fleetcapacity "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/custody" + apierrors "k8s.io/apimachinery/pkg/api/errors" apiMeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" @@ -155,3 +159,250 @@ func TestARegressionWithdrawsTheNextOffer(t *testing.T) { }) } } + +// TestAnAllocationOnDisabledCapacityIsWithdrawn creates an allocation, as an +// allocator would after selecting the capacity, and then disables the +// capacity before the claim. The allocator withdraws the allocation instead +// of claiming the Device. +func TestAnAllocationOnDisabledCapacityIsWithdrawn(t *testing.T) { + e := startEnv(t) + device := e.server(1) + capacity := e.capacity(device.Name) + stale, err := e.allocator.newAllocation(e.request(1), capacity, device, fleetv1.Hardware{}, "") + if err != nil { + t.Fatal(err) + } + e.create(stale) + capacity.Spec.AllocationPolicy = "Disabled" + if err := e.admin.Update(e.ctx, capacity); err != nil { + t.Fatal(err) + } + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("allocation on Disabled capacity: %v", err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(stale), stale); err == nil { + t.Fatal("the allocation on Disabled capacity was kept") + } + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderNone { + t.Fatalf("custody was claimed for Disabled capacity: %+v", holder) + } +} + +// TestARecreatedDeviceIsNotClaimed creates an allocation, as an allocator +// would after selecting the capacity, for an earlier incarnation of the +// Device. The allocator withdraws it instead of claiming the Device. +func TestARecreatedDeviceIsNotClaimed(t *testing.T) { + e := startEnv(t) + device := e.server(1) + capacity := e.capacity(device.Name) + stale, err := e.allocator.newAllocation(e.request(1), capacity, device, fleetv1.Hardware{}, "") + if err != nil { + t.Fatal(err) + } + // The allocation names another incarnation than the Device now stored. + stale.Labels[fleetv1.LabelDeviceUID] = uid(990) + e.create(stale) + if held, err := e.allocator.claim(e.ctx, stale); err != nil || held { + t.Fatalf("claim for an earlier incarnation: held %v, %v", held, err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(stale), stale); err == nil { + t.Fatal("the allocation for an earlier incarnation was kept") + } + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderNone { + t.Fatalf("custody was claimed for an earlier incarnation: %+v", holder) + } +} + +// offerAll offers every capacity, as a projection read before the Device was +// recreated would. +type offerAll struct{ hardware fleetv1.Hardware } + +func (o offerAll) Offer(context.Context, *fleetv1.MachineCapacity) (bool, fleetv1.Hardware, error) { + return true, o.hardware, nil +} + +// TestCapacityRegisteredForAnotherIncarnationIsSkipped records another Device +// incarnation as the capacity's registration. Even when the offer was made, +// the allocator does not select the capacity. +func TestCapacityRegisteredForAnotherIncarnationIsSkipped(t *testing.T) { + e := startEnv(t) + device := e.server(1) + capacity := e.capacity(device.Name) + e.until("the projector offers the capacity", func() bool { + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(capacity), capacity); err != nil { + t.Fatal(err) + } + available := apiMeta.FindStatusCondition(capacity.Status.Conditions, custody.ConditionAvailable) + return available != nil && available.Status == metav1.ConditionTrue + }) + e.allocator.Capacity = offerAll{hardware: capacity.Status.Hardware} + capacity.Annotations = map[string]string{fleetcapacity.RegisteredDeviceUID: uid(990)} + if err := e.admin.Update(e.ctx, capacity); err != nil { + t.Fatal(err) + } + // Selection skips it, and so does the recheck before the claim. + if _, _, _, err := e.allocator.candidate(e.ctx, e.request(1), map[string]bool{}); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("capacity registered for another incarnation was a candidate: %v", err) + } + if _, err := e.allocator.Allocate(e.ctx, e.request(1)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("capacity registered for another incarnation was selected: %v", err) + } + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderNone { + t.Fatalf("custody was claimed: %+v", holder) + } +} + +// afterCheckRecreatingProvider recreates the allocation's Device right after +// the allocator's last check read it, before the custody claim. With +// relabel, it also verifies custody for the new Device, as an operator's +// resolve would. The check sees the incarnation the allocation names, so +// only the claim can refuse. +type afterCheckRecreatingProvider struct { + client.Client + e *env + relabel, armed, recreated bool +} + +func (p *afterCheckRecreatingProvider) Create(ctx context.Context, object client.Object, options ...client.CreateOption) error { + if err := p.Client.Create(ctx, object, options...); err != nil { + return err + } + if _, ok := object.(*fleetv1.MachineAllocation); ok { + p.armed = true + } + return nil +} + +func (p *afterCheckRecreatingProvider) Get(ctx context.Context, key client.ObjectKey, object client.Object, options ...client.GetOption) error { + if err := p.Client.Get(ctx, key, object, options...); err != nil { + return err + } + device, ok := object.(*inventory.Device) + if !ok || !p.armed || p.recreated { + return nil + } + p.recreated = true + e := p.e + stored := device.DeepCopyObject().(*inventory.Device) + stored.Finalizers = nil + if err := e.admin.Update(ctx, stored); err != nil { + return err + } + if err := e.admin.Delete(ctx, stored); err != nil { + return err + } + again := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: stored.Name, Namespace: namespace, Labels: stored.Labels}, Spec: stored.Spec} + for { + if err := e.admin.Create(ctx, again); err == nil { + break + } else if !apierrors.IsAlreadyExists(err) { + return err + } + time.Sleep(20 * time.Millisecond) + } + if !p.relabel { + return nil + } + state := e.custody(stored.Name) + state.Labels[ops.LabelDeviceUID] = string(again.UID) + return e.admin.Update(ctx, state) +} + +// TestADeviceRecreatedAfterTheLastCheckIsNotClaimed recreates the selected +// Device after the allocator's last check and before its custody claim. The +// claim takes the incarnation from the allocation's device-uid label and +// refuses, so the allocation is withdrawn and the allocator selects again. +// While custody still names the old incarnation, only the claim's check of +// the live Device refuses; once custody names the new one, its check of +// custody refuses too. +func TestADeviceRecreatedAfterTheLastCheckIsNotClaimed(t *testing.T) { + for name, relabel := range map[string]bool{"custody still for the old Device": false, "custody verified for the new Device": true} { + t.Run(name, func(t *testing.T) { + e := startEnv(t) + original := e.server(1) + e.server(2) + provider := &afterCheckRecreatingProvider{Client: e.admin, e: e, relabel: relabel} + e.allocator.Provider = provider + allocation, err := e.allocator.Allocate(e.ctx, e.request(1)) + if err != nil { + t.Fatal(err) + } + if !provider.recreated { + t.Fatal("the Device was not recreated after the last check") + } + live := &inventory.Device{} + if err := e.admin.Get(e.ctx, client.ObjectKey{Namespace: namespace, Name: allocation.Spec.DeviceRef.Name}, live); err != nil { + t.Fatal(err) + } + if got := allocation.Labels[fleetv1.LabelDeviceUID]; got != string(live.UID) { + t.Fatalf("custody of %s was claimed for an allocation made against Device %s, the live Device is %s", live.Name, got, live.UID) + } + if holder := e.custody(original.Name).Spec.Holder; holder.Type != ops.HolderNone { + t.Fatalf("the recreated Device was claimed: %+v", holder) + } + }) + } +} + +// afterDeviceRead runs once, after the first read of a Device, as a +// concurrent writer would act between the allocator's last check and its +// custody claim. +type afterDeviceRead struct { + client.Client + once func() +} + +func (r *afterDeviceRead) Get(ctx context.Context, key client.ObjectKey, object client.Object, options ...client.GetOption) error { + err := r.Client.Get(ctx, key, object, options...) + if _, ok := object.(*inventory.Device); ok && r.once != nil { + once := r.once + r.once = nil + once() + } + return err +} + +// TestDisablingAfterTheLastCheckDoesNotStopTheClaim pins the one window the +// model cannot close. The custody claim is a conditional update of the +// DeviceCustody alone; Kubernetes has no write conditional on a second +// object, so the claim cannot also require the capacity to be unchanged. A +// capacity disabled after the allocator's last check of it, and before the +// custody claim, does not stop that claim. Disable stops every selection +// and every claim that has not passed the check; it does not reach back to +// one that has. The allocation holds the Device like one made a moment +// before the capacity was disabled, and nothing new is allocated on it. +func TestDisablingAfterTheLastCheckDoesNotStopTheClaim(t *testing.T) { + e := startEnv(t) + device := e.server(1) + capacity := e.capacity(device.Name) + allocation, err := e.allocator.newAllocation(e.request(1), capacity, device, fleetv1.Hardware{}, "") + if err != nil { + t.Fatal(err) + } + e.create(allocation) + disabled := false + e.allocator.Provider = &afterDeviceRead{Client: e.admin, once: func() { + current := &fleetv1.MachineCapacity{} + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(capacity), current); err != nil { + t.Error(err) + return + } + current.Spec.AllocationPolicy = "Disabled" + if err := e.admin.Update(e.ctx, current); err != nil { + t.Error(err) + return + } + disabled = true + }} + held, err := e.allocator.claim(e.ctx, allocation) + if err != nil || !held || !disabled { + t.Fatalf("claim across a concurrent disable: held %v, disabled %v, %v", held, disabled, err) + } + if holder := e.custody(device.Name).Spec.Holder; holder.Type != ops.HolderAllocation || holder.AllocationRef.Name != allocation.Name { + t.Fatalf("custody after the claim: %+v", holder) + } + e.allocator.Provider = e.admin + if _, err := e.allocator.Allocate(e.ctx, e.request(2)); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("a new allocation on Disabled capacity: %v", err) + } +} diff --git a/internal/registration/admission.go b/internal/registration/admission.go index 973a04bc..f9e31127 100644 --- a/internal/registration/admission.go +++ b/internal/registration/admission.go @@ -24,6 +24,7 @@ import ( inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/capacity" "go.datum.net/fleet/internal/controller" iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" admissionv1 "k8s.io/api/admission/v1" @@ -36,7 +37,7 @@ import ( ) const ( - DeviceUIDAnnotation = "fleet.datumapis.com/registration-device-uid" + DeviceUIDAnnotation = capacity.RegisteredDeviceUID DeviceVersionAnnotation = "fleet.datumapis.com/registration-device-version" OperationAnnotation = "fleet.datumapis.com/registration-operation" @@ -68,11 +69,23 @@ type Project struct { type Handler struct { // 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 + Projects []string + Resolve func(context.Context, string) (Project, error) + // Authorize runs a SubjectAccessReview for the caller: verb, group, + // resource and object name. + Authorize func(ctx context.Context, project Project, actor authenticationv1.UserInfo, verb, group, resource, name string) error + // Cleaning resolves a cleaning policy name to its digest. It returns + // capacity.ErrUnresolved for a name that does not resolve. Nil resolves + // nothing, so no registered capacity can be enabled. + Cleaning capacity.CleaningResolver + // Projectors are the usernames of the capacity projector, the only + // identity that may write the status of registered capacity. + Projectors []string } +// PoolLabel is the label a MachineClass selects capacity by. +const PoolLabel = "fleet.datumapis.com/capacity-pool" + var systemUUIDPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) func eligible(device *inventory.Device) bool { @@ -109,9 +122,6 @@ func (handler *Handler) Handle(ctx context.Context, request admission.Request) a // 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) - } name, err := projectName(request.UserInfo) if err != nil { return admission.Denied(err.Error()) @@ -119,8 +129,28 @@ 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()) + switch { + case request.SubResource == "status" && request.Operation == admissionv1.Update: + // Only the capacity projector writes the status of registered + // capacity. The status subresource ignores metadata and spec. + if !slices.Contains(handler.Projectors, request.UserInfo.Username) { + return admission.Denied("only the capacity projector writes the status of registered capacity") + } + return admission.Allowed("the capacity projector writes derived status") + case request.SubResource != "": + return admission.Denied(mutationDisabled) + case request.Operation == admissionv1.Update: + if err := handler.evaluateUpdate(ctx, name, request); err != nil { + return admission.Denied(err.Error()) + } + return admission.Allowed("only the allocation policy, cleaning policy and pool changed, under the stage-2 rules") + case request.Operation == admissionv1.Delete: + if err := handler.evaluateDelete(ctx, name, request); err != nil { + return admission.Denied(err.Error()) + } + return admission.Allowed("the capacity is Disabled and its Device is gone or Retired") + case request.Operation != admissionv1.Create: + return admission.Denied(mutationDisabled) } if err := handler.evaluate(ctx, name, request); err != nil { return admission.Denied(err.Error()) @@ -171,41 +201,172 @@ func marked(object *metav1.PartialObjectMetadata) bool { return false } -const mutationDisabled = "capacity mutation and deletion are disabled for inventory-backed capacity; registration annotations cannot be added, changed or removed" +const mutationDisabled = "registered capacity changes only its allocation policy, cleaning policy and pool label; 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 -// 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. +// evaluateUpdate admits an update of registered capacity that changes only +// the allocation policy, the cleaning policy reference and the pool label. +// While the capacity is Enabled, the only change is to Disabled. Enabling +// requires, at the time of the update, the caller's update permission, the +// annotated Device incarnation Active, no duplicate identity in the provider +// scope, a resolving cleaning policy and a pool label. 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 { + var next, previous metal.MachineCapacity + if err := json.Unmarshal(request.Object.Raw, &next); err != nil { + return err + } + if err := json.Unmarshal(request.OldObject.Raw, &previous); err != nil { return err } - if capacity.Spec.AllocationPolicy == "Disabled" { + if !onlyStageTwoFields(previous, next) { return errors.New(mutationDisabled) } + enabled := func(capacity metal.MachineCapacity) bool { return capacity.Spec.AllocationPolicy == "Enabled" } + unchanged := previous.Spec.AllocationPolicy == next.Spec.AllocationPolicy && reflect.DeepEqual(previous.Spec.CleaningPolicyRef, next.Spec.CleaningPolicyRef) && previous.Labels[PoolLabel] == next.Labels[PoolLabel] + switch { + case unchanged: + // An identical update, such as an unchanged apply, changes nothing. + return nil + case next.Spec.AllocationPolicy != "Enabled" && next.Spec.AllocationPolicy != "Disabled": + return errors.New("the allocation policy is Enabled or Disabled") + case enabled(previous) && (enabled(next) || !reflect.DeepEqual(previous.Spec.CleaningPolicyRef, next.Spec.CleaningPolicyRef) || previous.Labels[PoolLabel] != next.Labels[PoolLabel]): + return errors.New("enabled capacity changes only to Disabled; disable it before changing its cleaning policy or pool") + case !enabled(next): + return nil + } 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 { + if err := handler.Authorize(ctx, project, request.UserInfo, "update", metal.GroupVersion.Group, "machinecapacities", next.Name); err != nil { + return err + } + if err := handler.Authorize(ctx, project, request.UserInfo, "get", inventory.GroupVersion.Group, "devices", next.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 err := project.Client.Get(ctx, client.ObjectKey{Namespace: request.Namespace, Name: next.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 string(device.UID) != next.Annotations[DeviceUIDAnnotation] || !device.DeletionTimestamp.IsZero() { + return errors.New("capacity cannot leave Disabled: its Device is another incarnation than the one registered") + } 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) + if !eligible(device) { + return errors.New("capacity cannot leave Disabled: its Device no longer records a complete, non-placeholder identity") + } + if next.Labels[PoolLabel] == "" { + return errors.New("capacity cannot leave Disabled without a " + PoolLabel + " label") + } + resolve := handler.Cleaning + if resolve == nil { + resolve = capacity.Unresolved + } + if next.Spec.CleaningPolicyRef.Name == "" { + return errors.New("capacity cannot leave Disabled without a cleaning policy") + } + if _, err := resolve(ctx, next.Spec.CleaningPolicyRef.Name); errors.Is(err, capacity.ErrUnresolved) { + return fmt.Errorf("capacity cannot leave Disabled: cleaning policy %q does not resolve", next.Spec.CleaningPolicyRef.Name) + } else if err != nil { + return errors.New("capacity cannot leave Disabled: the cleaning policy owner is unavailable") + } + return handler.duplicates(ctx, name, device) +} + +// onlyStageTwoFields reports whether an update changes nothing but the +// allocation policy, the cleaning policy reference and the pool label. +func onlyStageTwoFields(previous, next metal.MachineCapacity) bool { + strip := func(capacity metal.MachineCapacity) metal.MachineCapacity { + capacity.Spec.AllocationPolicy, capacity.Spec.CleaningPolicyRef = "", metal.LocalReference{} + capacity.Status = metal.MachineCapacityStatus{} + labels := map[string]string{} + for key, value := range capacity.Labels { + if key != PoolLabel { + labels[key] = value + } + } + capacity.Labels = labels + capacity.ResourceVersion, capacity.Generation, capacity.ManagedFields = "", 0, nil + return capacity + } + return reflect.DeepEqual(strip(previous), strip(next)) +} + +// evaluateDelete admits the delete of registered capacity only when it is +// Disabled, its annotated Device is missing, another incarnation or +// Retired, no MachineAllocation that is not Released names it, and the +// caller may delete it. Enabling needs an Active Device of the annotated +// incarnation, so the capacity stays Disabled. An allocator that selected +// the capacity while it was Enabled re-reads it after creating its +// allocation and withdraws the allocation if the capacity is gone or +// Disabled, before it claims the Device. +func (handler *Handler) evaluateDelete(ctx context.Context, name string, request admission.Request) error { + var registered metal.MachineCapacity + if err := json.Unmarshal(request.OldObject.Raw, ®istered); err != nil { + return err + } + if registered.Spec.AllocationPolicy != "Disabled" { + return errors.New("disable the capacity before deleting it") + } + project, err := handler.Resolve(ctx, name) + if err != nil || !project.Identity.Valid() || project.Identity.RouteName != name { + return errors.New("provider project lifetime is unavailable") + } + if err := handler.Authorize(ctx, project, request.UserInfo, "delete", metal.GroupVersion.Group, "machinecapacities", registered.Name); err != nil { + return err + } + if err := handler.Authorize(ctx, project, request.UserInfo, "get", inventory.GroupVersion.Group, "devices", registered.Spec.DeviceRef.Name); err != nil { + return err + } + device := &inventory.Device{} + switch err := project.Client.Get(ctx, client.ObjectKey{Namespace: request.Namespace, Name: registered.Spec.DeviceRef.Name}, device); { + case apierrors.IsNotFound(err): + case err != nil: + return errors.New("the capacity's Device is unavailable") + case string(device.UID) == registered.Annotations[DeviceUIDAnnotation] && inventory.LifecycleOf(device) != inventory.DeviceRetired: + return errors.New("registered capacity is removed only after its Device is deleted or Retired") + } + var allocations metal.MachineAllocationList + if err := project.Client.List(ctx, &allocations, client.InNamespace(request.Namespace)); err != nil { + return errors.New("the allocations that may name the capacity are unavailable") + } + for _, allocation := range allocations.Items { + reference := allocation.Spec.MachineCapacityRef + if reference.Name == registered.Name && (reference.Namespace == "" || reference.Namespace == registered.Namespace) && allocation.Status.Phase != metal.AllocationReleased { + return fmt.Errorf("allocation %s still names the capacity", allocation.Name) + } + } + return nil +} + +// duplicates refuses a Device that shares an identity alias with any other +// Device in the provider scope, Retired ones included. +func (handler *Handler) duplicates(ctx context.Context, selectedProject string, selected *inventory.Device) error { + selectedAliases := inventory.Aliases(selected) + for _, name := range handler.Projects { + project, err := handler.Resolve(ctx, name) + if err != nil { + return errors.New("provider identity scope is unavailable") + } + var devices inventory.DeviceList + if err := project.Client.List(ctx, &devices); err != nil { + return errors.New("provider identity inventory is unavailable") + } + for index := range devices.Items { + device := &devices.Items[index] + if name == selectedProject && device.UID == selected.UID { + continue + } + if overlaps(inventory.Aliases(device), selectedAliases) { + return fmt.Errorf("another Device (%s) shares recorded hardware identity; resolve the duplicate before enabling", describe(name, selectedProject, device.Namespace, device.Name)) + } + } + } + return nil } func (handler *Handler) evaluate(ctx context.Context, name string, request admission.Request) error { @@ -241,10 +402,10 @@ func (handler *Handler) evaluate(ctx context.Context, name string, request admis } // 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 { + if err := handler.Authorize(ctx, project, request.UserInfo, "create", metal.GroupVersion.Group, "machinecapacities", ""); err != nil { return err } - if err := handler.Authorize(ctx, project, request.UserInfo, inventory.GroupVersion.Group, "devices", capacity.Spec.DeviceRef.Name); err != nil { + if err := handler.Authorize(ctx, project, request.UserInfo, "get", inventory.GroupVersion.Group, "devices", capacity.Spec.DeviceRef.Name); err != nil { return err } device := &inventory.Device{} diff --git a/internal/registration/admission_test.go b/internal/registration/admission_test.go index 5e17430b..5764a3dd 100644 --- a/internal/registration/admission_test.go +++ b/internal/registration/admission_test.go @@ -40,7 +40,9 @@ func fixture(t *testing.T) (*Handler, *inventory.Device) { 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 + }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string, string) error { + return nil + }}, device } func registrationRequest(t *testing.T, device *inventory.Device) admission.Request { @@ -90,7 +92,7 @@ func TestRegistrationAllowsLiveEligibleDeviceWithoutEffects(t *testing.T) { func TestRegistrationIdentifiesTheCallerByUsername(t *testing.T) { handler, device := fixture(t) var reviewed []authenticationv1.UserInfo - handler.Authorize = func(_ context.Context, _ Project, actor authenticationv1.UserInfo, _, _, _ string) error { + handler.Authorize = func(_ context.Context, _ Project, actor authenticationv1.UserInfo, _, _, _, _ string) error { reviewed = append(reviewed, actor) return nil } @@ -164,7 +166,7 @@ func TestRegistrationNegatives(t *testing.T) { 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 { + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, _, resource, _ string) error { if resource == "machinecapacities" { return errors.New("denied") } @@ -172,7 +174,7 @@ func TestRegistrationNegatives(t *testing.T) { } }, "device permission revoked": func(handler *Handler, _ *inventory.Device, _ *admission.Request) { - handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, resource, _ string) error { + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, _, resource, _ string) error { if resource == "devices" { return errors.New("denied") } @@ -225,7 +227,7 @@ func TestUnauthorizedCallerCannotProbeDeviceExistence(t *testing.T) { if err := providerClient(t, handler).Delete(context.Background(), device); err != nil { t.Fatal(err) } - handler.Authorize = func(context.Context, Project, authenticationv1.UserInfo, string, string, string) error { + handler.Authorize = func(context.Context, Project, authenticationv1.UserInfo, string, string, string, string) error { return errors.New("current get permission on devices is required") } response := handler.Handle(context.Background(), registrationRequest(t, device)) diff --git a/internal/registration/envtest_test.go b/internal/registration/envtest_test.go index a67d290b..da77370f 100644 --- a/internal/registration/envtest_test.go +++ b/internal/registration/envtest_test.go @@ -344,7 +344,7 @@ func TestRegistrationAgainstLiveDevices(t *testing.T) { 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) { + t.Run("without the component Device DELETE is allowed, and its Disabled capacity can then be removed", func(t *testing.T) { registered := api.registration(server) if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), registered); err != nil { t.Fatal(err) @@ -363,11 +363,15 @@ func TestRegistrationAgainstLiveDevices(t *testing.T) { 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) { - 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") + // The orphaned capacity is removed, and the replacement registers. + if err := operator.Delete(ctx, registered); err != nil { + t.Fatalf("orphaned capacity could not be removed: %v", err) + } + if err := operator.Create(ctx, api.registration(replacement)); err != nil { + t.Fatalf("the replacement could not register after the orphan was removed: %v", err) + } }) t.Run("only an Active Device can be registered", func(t *testing.T) { @@ -396,7 +400,7 @@ func TestRegistrationAgainstLiveDevices(t *testing.T) { current.Spec.CleaningPolicyRef.Name = "invented-policy" return operator.Update(ctx, current) } - requireDenied(t, enable(), "mutation and deletion are disabled") + requireDenied(t, enable(), "without a fleet.datumapis.com/capacity-pool label") api.setLifecycle(device, inventory.DeviceDecommissioning) requireDenied(t, enable(), "its Device is Decommissioning") api.setLifecycle(device, inventory.DeviceRetired) diff --git a/internal/registration/lifecycle_test.go b/internal/registration/lifecycle_test.go index c4b1e6f8..9e523495 100644 --- a/internal/registration/lifecycle_test.go +++ b/internal/registration/lifecycle_test.go @@ -77,21 +77,20 @@ func TestCapacityCannotLeaveDisabledForInactiveDevice(t *testing.T) { } }) } - // 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"}, - } { + // An Active Device's capacity is enabled only with a pool label and a + // resolving cleaning policy; an update that stays Disabled is allowed. + t.Run("Active enabled without a pool", func(t *testing.T) { + handler, device := fixture(t) + response := handler.Handle(context.Background(), capacityUpdate(t, device, "Enabled")) + if response.Allowed || !strings.Contains(response.Result.Message, "capacity-pool label") { + t.Fatalf("capacity update: %+v", response.Result) + } + }) + for name, lifecycle := range map[string]inventory.DeviceLifecycle{"Retired staying Disabled": inventory.DeviceRetired, "Decommissioning unchanged": inventory.DeviceDecommissioning} { 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 { + setLifecycle(t, handler, device, lifecycle) + if response := handler.Handle(context.Background(), capacityUpdate(t, device, "Disabled")); !response.Allowed { t.Fatalf("capacity update: %+v", response.Result) } }) @@ -99,7 +98,7 @@ func TestCapacityCannotLeaveDisabledForInactiveDevice(t *testing.T) { 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 { + handler.Authorize = func(_ context.Context, _ Project, _ authenticationv1.UserInfo, _, _, resource, _ string) error { if resource == "devices" { return errors.New("get permission on devices is required") } diff --git a/internal/registration/manifest_test.go b/internal/registration/manifest_test.go index 5bd181e2..ed1b9036 100644 --- a/internal/registration/manifest_test.go +++ b/internal/registration/manifest_test.go @@ -53,7 +53,7 @@ func TestPackagedWebhookFencesOnlyInventoryBackedCapacity(t *testing.T) { 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.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 { + if !slices.Equal(rule.APIGroups, []string{"metal.datumapis.com"}) || !slices.Equal(rule.APIVersions, []string{"v1alpha1"}) || !slices.Equal(rule.Resources, []string{"machinecapacities", "machinecapacities/status"}) || !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. diff --git a/internal/registration/runtime.go b/internal/registration/runtime.go index dc3f4527..00960410 100644 --- a/internal/registration/runtime.go +++ b/internal/registration/runtime.go @@ -35,11 +35,7 @@ func NewHandler(authority string, projects []string, root client.Client, templat // Authorize evaluates the caller's own permission with a SubjectAccessReview // carrying the caller's username, UID when present, 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" { - verb = "create" - } +func Authorize(ctx context.Context, project Project, actor authenticationv1.UserInfo, verb, group, resource, name string) error { extra := map[string]authorizationv1.ExtraValue{} for key, values := range actor.Extra { extra[key] = authorizationv1.ExtraValue(append([]string(nil), values...)) diff --git a/internal/registration/scope_envtest_test.go b/internal/registration/scope_envtest_test.go index 57ac1ed5..17fd3687 100644 --- a/internal/registration/scope_envtest_test.go +++ b/internal/registration/scope_envtest_test.go @@ -70,22 +70,22 @@ func TestWebhookGovernsOnlyInventoryBackedCapacity(t *testing.T) { 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") + requireDenied(t, operator.Update(ctx, capacity), "registration annotations cannot be added") + requireDenied(t, operator.Delete(ctx, current()), "removed only after its Device is deleted or Retired") + requireDenied(t, api.admin.Delete(ctx, current()), "project context is required") }) 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") + requireDenied(t, operator.Update(ctx, stripped), "registration annotations cannot be added") partial := current() delete(partial.Annotations, DeviceUIDAnnotation) - requireDenied(t, operator.Update(ctx, partial), "mutation and deletion are disabled") + requireDenied(t, operator.Update(ctx, partial), "registration annotations cannot be added") changed := current() changed.Annotations[DeviceUIDAnnotation] = "another-device" - requireDenied(t, operator.Update(ctx, changed), "mutation and deletion are disabled") + requireDenied(t, operator.Update(ctx, changed), "registration annotations cannot be added") 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") + requireDenied(t, operator.Patch(ctx, current(), patch), "registration annotations cannot be added") if annotations := current().Annotations; annotations[DeviceUIDAnnotation] != string(device.UID) || len(annotations) != 3 { t.Fatalf("marker changed: %v", annotations) } @@ -96,9 +96,9 @@ func TestWebhookGovernsOnlyInventoryBackedCapacity(t *testing.T) { t.Fatal(err) } adopted.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} - requireDenied(t, operator.Update(ctx, adopted), "mutation and deletion are disabled") + requireDenied(t, operator.Update(ctx, adopted), "registration annotations cannot be added") patch := client.RawPatch("application/merge-patch+json", []byte(`{"metadata":{"annotations":{"`+OperationAnnotation+`":"adopt"}}}`)) - requireDenied(t, operator.Patch(ctx, handMade, patch), "mutation and deletion are disabled") + requireDenied(t, operator.Patch(ctx, handMade, patch), "registration annotations cannot be added") }) 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"}} @@ -143,20 +143,16 @@ func TestWebhookGovernsOnlyInventoryBackedCapacity(t *testing.T) { } } }) - 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. + t.Run("marked capacity status writes fail closed", func(t *testing.T) { + // Status writes to registered capacity are routed, so only the + // capacity projector can make them, and an outage blocks them. 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) + capacity.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionTrue, Reason: "Edited", LastTransitionTime: metav1.Now()}} + if err := api.admin.Status().Update(ctx, capacity); err == nil { + t.Fatal("a status write on registered capacity was admitted without the webhook") + } + if after := current(); len(after.Status.Conditions) != 0 { + t.Fatalf("status changed during the outage: %+v", after.Status.Conditions) } }) t.Run("marked capacity writes fail closed without the backend", func(t *testing.T) { diff --git a/internal/registration/scope_test.go b/internal/registration/scope_test.go index 3d568722..2670e3ee 100644 --- a/internal/registration/scope_test.go +++ b/internal/registration/scope_test.go @@ -34,7 +34,7 @@ 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 { + }, Authorize: func(context.Context, Project, authenticationv1.UserInfo, string, string, string, string) error { t.Error("unmarked capacity was authorized against Devices") return errors.New("unavailable") }} @@ -72,6 +72,8 @@ func TestMarkerTransitionsAreDenied(t *testing.T) { adopted.Annotations = map[string]string{DeviceUIDAnnotation: string(device.UID)} enabledAdoption := clone(adopted) enabledAdoption.Spec.AllocationPolicy = "Enabled" + relabeled := clone(®istered) + relabeled.Labels = map[string]string{"edited": "true"} stripped := clone(®istered) stripped.Annotations = nil changed := clone(®istered) @@ -85,15 +87,15 @@ func TestMarkerTransitionsAreDenied(t *testing.T) { 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}, + "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 of another field": {operation: admissionv1.Update, object: relabeled, 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) { diff --git a/internal/registration/stage2_envtest_test.go b/internal/registration/stage2_envtest_test.go new file mode 100644 index 00000000..3d2269a7 --- /dev/null +++ b/internal/registration/stage2_envtest_test.go @@ -0,0 +1,219 @@ +package registration + +import ( + "context" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/controller" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const stageTwoPolicyDigest = "sha256:0c2b77e1d9a4000000000000000000000000000000000000000000000000cafe" + +// TestStageTwoEnablesRegisteredCapacity runs the stage-2 rules through the +// packaged webhook against a real API server: enabling, the frozen fields of +// enabled capacity, duplicates, the projector's status writes, and removing +// orphaned capacity. +func TestStageTwoEnablesRegisteredCapacity(t *testing.T) { + api := startAPI(t) + ctx := context.Background() + 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, Cleaning: capacity.Fixed(map[string]string{"tenant-reuse": stageTwoPolicyDigest}), Projectors: []string{"capacity-projector"}}) + operator := api.actor("operator", "system:masters") + projector := api.actor("capacity-projector", "system:masters") + register := func(device *inventory.Device) *metal.MachineCapacity { + t.Helper() + registered := api.registration(device) + if err := operator.Create(ctx, registered); err != nil { + t.Fatal(err) + } + return registered + } + current := func(registered *metal.MachineCapacity) *metal.MachineCapacity { + t.Helper() + out := &metal.MachineCapacity{} + if err := api.admin.Get(ctx, client.ObjectKeyFromObject(registered), out); err != nil { + t.Fatal(err) + } + return out + } + edit := func(registered *metal.MachineCapacity, policy, cleaning, pool string) error { + next := current(registered) + next.Spec.AllocationPolicy, next.Spec.CleaningPolicyRef.Name = policy, cleaning + if next.Labels == nil { + next.Labels = map[string]string{} + } + if pool == "" { + delete(next.Labels, PoolLabel) + } else { + next.Labels[PoolLabel] = pool + } + return operator.Update(ctx, next) + } + + t.Run("enabling needs a resolving cleaning policy and a pool", func(t *testing.T) { + registered := register(api.device("enable", "default", "enable-serial", "a1111111-1111-1111-1111-111111111111")) + // The CRD already refuses Enabled capacity without a cleaning policy. + if err := edit(registered, "Enabled", "", "general"); err == nil { + t.Fatal("capacity was enabled without a cleaning policy") + } + requireDenied(t, edit(registered, "Enabled", "invented-policy", "general"), `cleaning policy "invented-policy" does not resolve`) + requireDenied(t, edit(registered, "Enabled", "tenant-reuse", ""), "capacity-pool label") + // While Disabled, the three fields change freely. + if err := edit(registered, "Disabled", "tenant-reuse", "general"); err != nil { + t.Fatalf("a Disabled edit: %v", err) + } + if err := edit(registered, "Enabled", "tenant-reuse", "general"); err != nil { + t.Fatalf("enabling: %v", err) + } + // Enabled capacity changes only to Disabled. + requireDenied(t, edit(registered, "Enabled", "tenant-reuse", "other-pool"), "changes only to Disabled") + requireDenied(t, edit(registered, "Enabled", "other-policy", "general"), "changes only to Disabled") + requireDenied(t, edit(registered, "Disabled", "tenant-reuse", "other-pool"), "changes only to Disabled") + if err := edit(registered, "Disabled", "tenant-reuse", "general"); err != nil { + t.Fatalf("disabling: %v", err) + } + if err := edit(registered, "Disabled", "tenant-reuse", "other-pool"); err != nil { + t.Fatalf("moving pools while Disabled: %v", err) + } + }) + + t.Run("a duplicate Device blocks enabling", func(t *testing.T) { + registered := register(api.device("original", "default", "twin-serial", "b1111111-1111-1111-1111-111111111111")) + api.device("late-twin", "default", "TWIN-SERIAL", "b2222222-2222-2222-2222-222222222222") + requireDenied(t, edit(registered, "Enabled", "tenant-reuse", "general"), "shares recorded hardware identity") + }) + + t.Run("only the projector writes registered capacity status", func(t *testing.T) { + registered := register(api.device("status", "default", "status-serial", "c1111111-1111-1111-1111-111111111111")) + edited := current(registered) + edited.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionTrue, Reason: "Edited", LastTransitionTime: metav1.Now()}} + requireDenied(t, operator.Status().Update(ctx, edited), "only the capacity projector") + projected := current(registered) + projected.Status.Conditions = []metav1.Condition{{Type: "Available", Status: metav1.ConditionFalse, Reason: "NotHealthy", LastTransitionTime: metav1.Now()}} + if err := projector.Status().Update(ctx, projected); err != nil { + t.Fatalf("the projector's status write: %v", err) + } + }) + + t.Run("orphaned capacity is removed only when nothing uses it", func(t *testing.T) { + device := api.device("orphan", "default", "orphan-serial", "d1111111-1111-1111-1111-111111111111") + registered := register(device) + requireDenied(t, operator.Delete(ctx, current(registered)), "removed only after its Device is deleted or Retired") + if err := edit(registered, "Enabled", "tenant-reuse", "general"); err != nil { + t.Fatal(err) + } + if err := api.admin.Delete(ctx, device); err != nil { + t.Fatal(err) + } + requireDenied(t, operator.Delete(ctx, current(registered)), "disable the capacity before deleting it") + if err := edit(registered, "Disabled", "tenant-reuse", "general"); err != nil { + t.Fatal(err) + } + allocation := &metal.MachineAllocation{ObjectMeta: metav1.ObjectMeta{Name: "alloc-orphan", Namespace: "default", Labels: map[string]string{ + metal.LabelMachineUID: "e2222222-2222-2222-2222-222222222222", metal.LabelConsumerUID: "e1111111-1111-1111-1111-111111111111", metal.LabelDeviceUID: string(device.UID)}}, Spec: metal.MachineAllocationSpec{ + ConsumerRef: metal.TypedReference{APIGroup: "resourcemanager.miloapis.com", Kind: "Project", Name: "consumer-example"}, + MachineRef: metal.AllocatedMachineReference{Namespace: "default", Name: "machine"}, + MachineCapacityRef: metal.NamespacedReference{Namespace: "default", Name: registered.Name}, + DeviceRef: metal.AllocatedDeviceReference{Name: device.Name}, + Accepted: metal.AcceptedContract{MachineClassRef: metal.ContentReference{Name: "class", Generation: 1, Digest: stageTwoPolicyDigest}, MachineProfileRef: metal.ContentReference{Name: "profile", Generation: 1, Digest: stageTwoPolicyDigest}, + CPU: metal.CPURequirement{Architecture: "amd64", Cores: 2}, Memory: metal.MemoryRequirement{Capacity: "2Gi"}}, + Authority: metal.AllocationAuthority{Principal: "fixture", Decision: "fixture"}, + CleaningPolicyDigest: stageTwoPolicyDigest, BootInterface: "primary", TargetDisks: []string{"disk-0"}, + }} + if err := api.admin.Create(ctx, allocation); err != nil { + t.Fatal(err) + } + allocation.Status.Phase = metal.AllocationReleasing + if err := api.admin.Status().Update(ctx, allocation); err != nil { + t.Fatal(err) + } + requireDenied(t, operator.Delete(ctx, current(registered)), "still names the capacity") + allocation.Status.Phase = metal.AllocationReleased + if err := api.admin.Status().Update(ctx, allocation); err != nil { + t.Fatal(err) + } + if err := operator.Delete(ctx, current(registered)); err != nil { + t.Fatalf("removing orphaned capacity: %v", err) + } + }) + + // Callers without system:masters, each missing one permission. The API + // server refuses a verb the caller lacks on the capacity; the webhook's + // own review refuses a caller who cannot read the Device. + t.Run("a caller without a permission is refused", func(t *testing.T) { + grant := func(user string, capacityVerbs []string, deviceGet bool) client.Client { + t.Helper() + rules := []rbacv1.PolicyRule{{APIGroups: []string{metal.GroupVersion.Group}, Resources: []string{"machinecapacities"}, Verbs: capacityVerbs}} + if deviceGet { + rules = append(rules, rbacv1.PolicyRule{APIGroups: []string{inventory.GroupVersion.Group}, Resources: []string{"devices"}, Verbs: []string{"get"}}) + } + if err := api.admin.Create(ctx, &rbacv1.Role{ObjectMeta: metav1.ObjectMeta{Name: user, Namespace: "default"}, Rules: rules}); err != nil { + t.Fatal(err) + } + if err := api.admin.Create(ctx, &rbacv1.RoleBinding{ObjectMeta: metav1.ObjectMeta{Name: user, Namespace: "default"}, RoleRef: rbacv1.RoleRef{APIGroup: "rbac.authorization.k8s.io", Kind: "Role", Name: user}, + Subjects: []rbacv1.Subject{{APIGroup: "rbac.authorization.k8s.io", Kind: "User", Name: user}}}); err != nil { + t.Fatal(err) + } + return api.actor(user) + } + enabled := func(registered *metal.MachineCapacity) *metal.MachineCapacity { + next := current(registered) + next.Spec.AllocationPolicy, next.Spec.CleaningPolicyRef.Name = "Enabled", "tenant-reuse" + next.Labels = map[string]string{PoolLabel: "general"} + return next + } + registered := register(api.device("permission", "default", "permission-serial", "a3333333-3333-3333-3333-333333333333")) + // Give the capacity a pool while Disabled, so enabling changes only + // the policy fields the stage-2 rules allow. + if err := edit(registered, "Disabled", "tenant-reuse", "general"); err != nil { + t.Fatal(err) + } + + noUpdate := grant("no-update", []string{"get", "delete"}, true) + if err := noUpdate.Update(ctx, enabled(registered)); !apierrors.IsForbidden(err) { + t.Fatalf("a caller without update enabled the capacity: %v", err) + } + noDeviceRead := grant("no-device-read", []string{"get", "update", "delete"}, false) + requireDenied(t, noDeviceRead.Update(ctx, enabled(registered)), "current get permission on devices is required") + if policy := current(registered).Spec.AllocationPolicy; policy != "Disabled" { + t.Fatalf("a refused caller changed the capacity: %s", policy) + } + + // The Device is Retired, so the capacity is removable by a caller + // who has every permission the delete needs. + device := &inventory.Device{} + if err := api.admin.Get(ctx, client.ObjectKey{Namespace: "default", Name: "permission"}, device); err != nil { + t.Fatal(err) + } + api.retire(device) + noDelete := grant("no-delete", []string{"get", "update"}, true) + if err := noDelete.Delete(ctx, current(registered)); !apierrors.IsForbidden(err) { + t.Fatalf("a caller without delete removed the capacity: %v", err) + } + requireDenied(t, noDeviceRead.Delete(ctx, current(registered)), "current get permission on devices is required") + if !api.exists(registered) { + t.Fatal("a refused caller removed the capacity") + } + allowed := grant("capacity-remover", []string{"get", "delete"}, true) + if err := allowed.Delete(ctx, current(registered)); err != nil { + t.Fatalf("a caller with every permission: %v", err) + } + }) + + t.Run("a Retired Device's Disabled capacity can be removed", func(t *testing.T) { + device := api.device("retiring", "default", "retiring-serial", "f1111111-1111-1111-1111-111111111111") + registered := register(device) + api.retire(device) + if err := operator.Delete(ctx, current(registered)); err != nil { + t.Fatalf("removing a Retired Device's capacity: %v", err) + } + }) +} diff --git a/internal/registration/stage2_test.go b/internal/registration/stage2_test.go new file mode 100644 index 00000000..8c1ce855 --- /dev/null +++ b/internal/registration/stage2_test.go @@ -0,0 +1,205 @@ +package registration + +import ( + "context" + "encoding/json" + "strings" + "testing" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + metal "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/capacity" + "go.datum.net/fleet/internal/controller" + 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" + "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/webhook/admission" +) + +// stageTwo is a handler whose cleaning resolver knows one policy and whose +// projector is "capacity-projector". +func stageTwo(t *testing.T) (*Handler, *inventory.Device) { + t.Helper() + handler, device := fixture(t) + handler.Cleaning = capacity.Fixed(map[string]string{"tenant-reuse": "sha256:" + strings.Repeat("a", 64)}) + handler.Projectors = []string{"capacity-projector"} + return handler, device +} + +// update builds an update of registered capacity from old to the mutated +// copy. +func update(t *testing.T, device *inventory.Device, old func(*metal.MachineCapacity), next func(*metal.MachineCapacity)) admission.Request { + t.Helper() + request := registrationRequest(t, device) + if old != nil { + changeCapacity(&request, old) + } + previous := request.Object + changeCapacity(&request, next) + request.Operation, request.OldObject = admissionv1.Update, previous + return request +} + +func enable(capacity *metal.MachineCapacity) { + capacity.Spec.AllocationPolicy, capacity.Spec.CleaningPolicyRef.Name = "Enabled", "tenant-reuse" + capacity.Labels = map[string]string{PoolLabel: "general"} +} + +func TestOnlyTheStageTwoFieldsChange(t *testing.T) { + for name, mutate := range map[string]func(*metal.MachineCapacity){ + "finalizers": func(c *metal.MachineCapacity) { c.Finalizers = []string{"example.com/hold"} }, + "owner references": func(c *metal.MachineCapacity) { + c.OwnerReferences = []metav1.OwnerReference{{APIVersion: "v1", Kind: "ConfigMap", Name: "owner", UID: "owner-uid"}} + }, + "reclaim policy": func(c *metal.MachineCapacity) { c.Spec.ReclaimPolicy = "Delete" }, + "Device reference": func(c *metal.MachineCapacity) { c.Spec.DeviceRef.Name = "another-server" }, + "another label": func(c *metal.MachineCapacity) { c.Labels = map[string]string{"edited": "true"} }, + "another annotation": func(c *metal.MachineCapacity) { + c.Annotations["example.com/note"] = "edited" + }, + } { + for _, state := range []string{"Disabled", "Enabled"} { + t.Run(name+" while "+state, func(t *testing.T) { + handler, device := stageTwo(t) + var start func(*metal.MachineCapacity) + if state == "Enabled" { + start = enable + } + request := update(t, device, start, func(c *metal.MachineCapacity) { + if start != nil { + start(c) + } + mutate(c) + }) + if response := handler.Handle(context.Background(), request); response.Allowed || response.Result.Message != mutationDisabled { + t.Fatalf("an update of %s was %+v", name, response.Result) + } + }) + } + } + t.Run("an identical update of enabled capacity", func(t *testing.T) { + handler, device := stageTwo(t) + if response := handler.Handle(context.Background(), update(t, device, enable, enable)); !response.Allowed { + t.Fatalf("an unchanged apply was denied: %+v", response.Result) + } + }) +} + +func TestEnablingChecksTheRegisteredDevice(t *testing.T) { + handler, device := stageTwo(t) + if response := handler.Handle(context.Background(), update(t, device, nil, enable)); !response.Allowed { + t.Fatalf("enabling an eligible Device: %+v", response.Result) + } + for name, test := range map[string]struct { + device func(*inventory.Device) + want string + }{ + "another incarnation": {func(d *inventory.Device) { d.UID = "device-2" }, "another incarnation"}, + "deleting": {func(d *inventory.Device) { + d.Finalizers, d.DeletionTimestamp = []string{"example.com/hold"}, &metav1.Time{} + }, "another incarnation"}, + "placeholder serial": {func(d *inventory.Device) { d.Spec.Identity.Serial = "To Be Filled By O.E.M." }, "complete, non-placeholder identity"}, + } { + t.Run(name, func(t *testing.T) { + handler, device := stageTwo(t) + api := providerClient(t, handler) + current := device.DeepCopyObject().(*inventory.Device) + test.device(current) + replace(t, api, device, current) + response := handler.Handle(context.Background(), update(t, device, nil, enable)) + if response.Allowed || !strings.Contains(response.Result.Message, test.want) { + t.Fatalf("enabling with %s: %+v", name, response.Result) + } + }) + } + t.Run("a duplicate in another provider project", func(t *testing.T) { + handler, device := stageTwo(t) + twin := &inventory.Device{ObjectMeta: metav1.ObjectMeta{Name: "twin", Namespace: "default", UID: "twin-1"}, Spec: inventory.DeviceSpec{Identity: inventory.DeviceIdentity{Serial: "serial-1", SystemUUID: "22222222-2222-2222-2222-222222222222", Model: "test"}}} + other := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(twin).Build() + resolve := handler.Resolve + handler.Projects = []string{"other-provider", "provider"} + handler.Resolve = func(ctx context.Context, name string) (Project, error) { + if name == "other-provider" { + return Project{Identity: controller.ProjectIdentity{AuthorityID: "milo", RouteName: name, UID: "project-2"}, Client: other}, nil + } + return resolve(ctx, name) + } + response := handler.Handle(context.Background(), update(t, device, nil, enable)) + if response.Allowed || !strings.Contains(response.Result.Message, "in another provider project") { + t.Fatalf("enabling beside a duplicate in another project: %+v", response.Result) + } + }) +} + +// replace swaps the stored Device for another version of it. +func replace(t *testing.T, api client.Client, device, current *inventory.Device) { + t.Helper() + if err := api.Delete(context.Background(), device); err != nil { + t.Fatal(err) + } + current.ResourceVersion = "" + deleting := current.DeletionTimestamp + current.DeletionTimestamp = nil + if err := api.Create(context.Background(), current); err != nil { + t.Fatal(err) + } + if deleting != nil { + if err := api.Delete(context.Background(), current); err != nil { + t.Fatal(err) + } + } +} + +func TestOrphanDeletionChecksTheIncarnation(t *testing.T) { + deletion := func(t *testing.T, device *inventory.Device) admission.Request { + request := registrationRequest(t, device) + request.Operation, request.OldObject, request.Object = admissionv1.Delete, request.Object, runtime.RawExtension{} + return request + } + t.Run("the same Active incarnation keeps its capacity", func(t *testing.T) { + handler, device := stageTwo(t) + if response := handler.Handle(context.Background(), deletion(t, device)); response.Allowed { + t.Fatal("capacity of an Active Device was deleted") + } + }) + t.Run("another incarnation under the name lets it go", func(t *testing.T) { + handler, device := stageTwo(t) + current := device.DeepCopyObject().(*inventory.Device) + current.UID = types.UID("device-2") + replace(t, providerClient(t, handler), device, current) + if response := handler.Handle(context.Background(), deletion(t, device)); !response.Allowed { + t.Fatalf("orphaned capacity: %+v", response.Result) + } + }) +} + +func TestStatusWritesComeOnlyFromTheProjector(t *testing.T) { + status := func(t *testing.T, device *inventory.Device, user authenticationv1.UserInfo) admission.Request { + request := registrationRequest(t, device) + request.Operation, request.SubResource, request.OldObject, request.UserInfo = admissionv1.Update, "status", request.Object, user + return request + } + handler, device := stageTwo(t) + extras := registrationRequest(t, device).UserInfo.Extra + if response := handler.Handle(context.Background(), status(t, device, authenticationv1.UserInfo{Username: "capacity-projector", UID: "projector-uid", Extra: extras})); !response.Allowed { + t.Fatalf("the projector's status write: %+v", response.Result) + } + if response := handler.Handle(context.Background(), status(t, device, authenticationv1.UserInfo{Username: "operator", UID: "actor-1", Extra: extras})); response.Allowed { + t.Fatal("an operator wrote registered capacity status") + } + // The projector writes through the provider project, which sets the + // project context; without it the write is refused. + if response := handler.Handle(context.Background(), status(t, device, authenticationv1.UserInfo{Username: "capacity-projector", UID: "projector-uid"})); response.Allowed { + t.Fatal("a status write without a project context was admitted") + } + handler.Projectors = nil + if response := handler.Handle(context.Background(), status(t, device, authenticationv1.UserInfo{Username: "capacity-projector", UID: "projector-uid", Extra: extras})); response.Allowed { + t.Fatal("a status write was admitted with no projector configured") + } +} + +var _ = json.Marshal diff --git a/internal/registration/tenancy_envtest_test.go b/internal/registration/tenancy_envtest_test.go index ef5fbe95..3f1e9929 100644 --- a/internal/registration/tenancy_envtest_test.go +++ b/internal/registration/tenancy_envtest_test.go @@ -37,7 +37,7 @@ func TestWebhookJudgesOnlyTheConfiguredProject(t *testing.T) { 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 { + }, Authorize: func(ctx context.Context, project Project, actor authenticationv1.UserInfo, verb, 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 @@ -46,7 +46,7 @@ func TestWebhookJudgesOnlyTheConfiguredProject(t *testing.T) { t.Errorf("SubjectAccessReview for %s was attempted after a mismatched route", resource) return context.Canceled } - return Authorize(ctx, project, actor, group, resource, name) + return Authorize(ctx, project, actor, verb, group, resource, name) }}) operator := api.actor("operator", "system:masters") registered := api.registration(registeredDevice) diff --git a/internal/registration/tenancy_test.go b/internal/registration/tenancy_test.go index 76de815d..4620b7d9 100644 --- a/internal/registration/tenancy_test.go +++ b/internal/registration/tenancy_test.go @@ -7,7 +7,9 @@ import ( "go.datum.net/fleet/internal/controller" iam "go.miloapis.com/milo/pkg/apis/iam/v1alpha1" + admissionv1 "k8s.io/api/admission/v1" authenticationv1 "k8s.io/api/authentication/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -38,21 +40,29 @@ func tripwire(t *testing.T, why string) client.Client { } // 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 { +func tripwireAuthorize(t *testing.T, why string) func(context.Context, Project, authenticationv1.UserInfo, string, 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. +// decisionPaths are the admission paths of registered capacity: a +// registration create, an update that tries to leave Disabled, the delete +// of Disabled capacity, and the projector's status write. All but the status +// write resolve the project; the status write must read nothing. func decisionPaths(t *testing.T) map[string]admission.Request { t.Helper() _, device := fixture(t) + removal := registrationRequest(t, device) + removal.Operation, removal.OldObject, removal.Object = admissionv1.Delete, removal.Object, runtime.RawExtension{} + status := capacityUpdate(t, device, "Disabled") + status.SubResource, status.UserInfo.Username = "status", "capacity-projector" return map[string]admission.Request{ "create": registrationRequest(t, device), "enabling update": capacityUpdate(t, device, "Enabled"), + "delete": removal, + "status": status, } } @@ -87,10 +97,20 @@ 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) { + resolved := false + handler := &Handler{Projects: []string{"provider"}, Projectors: []string{"capacity-projector"}, Resolve: func(context.Context, string) (Project, error) { + resolved = true 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 request.SubResource == "status" { + // The projector's status write is judged by its identity + // alone: it resolves no project and reads nothing. + if resolved || !response.Allowed { + t.Fatalf("status write: resolved %v, %+v", resolved, response.Result) + } + return + } if response.Allowed || response.Result.Message != "provider project lifetime is unavailable" { t.Fatalf("mismatched route: %+v", response.Result) }