From 6a289510df084eafc9f84f7a3e7fd2b0557ba0d2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Fri, 27 Nov 2026 21:20:50 -0600 Subject: [PATCH 1/3] feat(custody): Add the commissioning kinds Add DeviceCommissioning, with DeviceCommissioningPlan and DeviceCommissioningPlanApproval, as the commissioning proposal describes. A plan qualifies only when someone other than its author approves its exact generation and digest. Approver and author are told apart by username ignoring case; UIDs are compared only when both carry one, since a client certificate carries none. A Device's current plan is the one qualified plan that selects it and that no other selecting plan supersedes. No spec holds an object UID. An approval's name is the plan's name and a suffix derived from the plan's UID, and a commissioning names that approval, so a plan recreated under the same name inherits nothing. The Device incarnation is the device-uid label. Custody admits a commissioning from holder None, or from Service to settle a commissioning hold, under the Device's current plan with an exact copy of its content. A proven verdict ends Succeeded with a Passed or Failed result; anything else ends OutcomeUnknown. Two seams let a kind derive its deadline from its inputs and keep each Device's latest success past retention. Every mode's coordinator role reads the new kinds. The creator webhook and the standalone creator policy govern them, and a test keeps both packaged resource lists in step. The multi-plane CRD rule phase refuses a write that breaks each new CEL rule, and the standalone smoke and the harness custody reads cover the new kinds. Nothing runs a commissioning worker yet. Co-Authored-By: Claude Opus 5.5 --- .../crds/fleet.datumapis.com.yaml | 558 ++++++++++++++++++ .../devicecommissioning.yaml | 20 + .../devicecommissioningplan.yaml | 15 + .../devicecommissioningplanapproval.yaml | 15 + .../protected-resources/kustomization.yaml | 3 + .../device-operations/roles/coordinator.yaml | 12 + .../roles/device-commissioning-operator.yaml | 13 + .../device-commissioning-plan-approver.yaml | 14 + .../device-commissioning-plan-author.yaml | 14 + .../roles/kustomization.yaml | 3 + .../device-operations/roles/viewer.yaml | 9 + .../components/device-operations/webhook.yaml | 4 +- config/standalone/rbac.yaml | 7 +- config/standalone/site.yaml | 4 +- docs/development/device-custody.md | 79 ++- docs/operations/multiplane.md | 8 +- hack/multiplane/custody_crd_rules.py | 60 +- hack/multiplane/evidence.py | 2 +- hack/multiplane/harness.py | 3 +- hack/multiplane/milo.py | 7 +- hack/standalone-smoke.sh | 4 +- .../api/operations/v1alpha1/commissioning.go | 251 ++++++++ .../api/operations/v1alpha1/config_test.go | 53 +- internal/api/operations/v1alpha1/types.go | 2 +- internal/custody/commissioning.go | 389 ++++++++++++ internal/custody/commissioning_test.go | 516 ++++++++++++++++ internal/custody/coordinator.go | 6 +- internal/custody/coordinator_roles_test.go | 78 +++ internal/custody/creatorwebhook/handler.go | 2 +- .../custody/creatorwebhook/packaged_test.go | 70 +++ internal/custody/kinds.go | 4 +- internal/custody/registry.go | 8 + internal/custody/retention.go | 58 +- 33 files changed, 2253 insertions(+), 38 deletions(-) create mode 100644 config/components/device-operations/protected-resources/devicecommissioning.yaml create mode 100644 config/components/device-operations/protected-resources/devicecommissioningplan.yaml create mode 100644 config/components/device-operations/protected-resources/devicecommissioningplanapproval.yaml create mode 100644 config/components/device-operations/roles/device-commissioning-operator.yaml create mode 100644 config/components/device-operations/roles/device-commissioning-plan-approver.yaml create mode 100644 config/components/device-operations/roles/device-commissioning-plan-author.yaml create mode 100644 internal/api/operations/v1alpha1/commissioning.go create mode 100644 internal/custody/commissioning.go create mode 100644 internal/custody/commissioning_test.go create mode 100644 internal/custody/coordinator_roles_test.go create mode 100644 internal/custody/creatorwebhook/packaged_test.go diff --git a/config/components/device-operations/crds/fleet.datumapis.com.yaml b/config/components/device-operations/crds/fleet.datumapis.com.yaml index e3f20eb3..c5ca1033 100644 --- a/config/components/device-operations/crds/fleet.datumapis.com.yaml +++ b/config/components/device-operations/crds/fleet.datumapis.com.yaml @@ -1073,3 +1073,561 @@ spec: message: operation phases move forward only, and an ended phase is final required: - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecommissionings.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCommissioning + listKind: DeviceCommissioningList + plural: devicecommissionings + singular: devicecommissioning + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: + status: {} + additionalPrinterColumns: + - name: Device + type: string + jsonPath: .spec.deviceRef.name + - name: Phase + type: string + jsonPath: .status.phase + - name: Reason + type: string + jsonPath: .status.reason + - name: Fence + type: integer + jsonPath: .status.fence + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + authority: + type: object + properties: + allocationRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + required: + - name + serviceRequest: + type: object + properties: + reason: + type: string + minLength: 1 + maxLength: 512 + required: + - reason + x-kubernetes-validations: + - rule: has(self.allocationRef) != has(self.serviceRequest) + message: set exactly one of allocationRef and serviceRequest + plan: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 236 + generation: + type: integer + format: int64 + minimum: 1 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + approval: + type: string + minLength: 18 + maxLength: 253 + content: + type: object + properties: + inspection: + type: object + properties: + cpu: + type: object + properties: + architecture: + type: string + enum: [amd64, arm64] + cores: + type: integer + format: int64 + minimum: 1 + maximum: 4096 + required: [architecture, cores] + memory: + type: object + properties: + capacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [capacity] + disks: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + minCapacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [count, minCapacity] + interfaces: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + required: [count] + required: [cpu, memory, disks, interfaces] + firmware: + type: array + maxItems: 32 + items: + type: object + properties: + component: + type: string + minLength: 1 + maxLength: 128 + version: + type: string + minLength: 1 + maxLength: 128 + required: [component, version] + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [component] + burnIn: + type: object + properties: + image: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: [name, digest] + duration: + type: string + pattern: ^([0-9]+h)?([0-9]+m)?([0-9]+s)?$ + x-kubernetes-validations: + - rule: self != '' && duration(self) >= duration('1m') && duration(self) <= duration('24h') + message: burn-in runs from 1 minute to 24 hours + required: [image, duration] + required: [inspection, burnIn] + required: [name, generation, digest, approval, content] + required: + - creator + - deviceRef + - authority + - plan + x-kubernetes-validations: + - rule: self == oldSelf + message: an operation spec is immutable after create + status: + type: object + properties: + admission: + type: object + properties: + fence: + type: integer + format: int64 + minimum: 1 + required: + - fence + phase: + type: string + enum: + - Pending + - Admitted + - Dispatched + - Verifying + - Succeeded + - Failed + - Cancelled + - OutcomeUnknown + reason: + type: string + maxLength: 128 + message: + type: string + maxLength: 1024 + fence: + type: integer + format: int64 + minimum: 0 + admittedAt: + type: string + format: date-time + deadline: + type: string + format: date-time + finishedAt: + type: string + format: date-time + inputDigest: + type: string + maxLength: 128 + snapshot: + type: object + properties: + bmcEndpoint: + type: string + maxLength: 2048 + systemUUID: + type: string + maxLength: 64 + bootMACAddress: + type: string + maxLength: 32 + bmcPublicKeySHA256: + type: string + maxLength: 128 + deviceGeneration: + type: integer + format: int64 + discoveryObservedAt: + type: string + maxLength: 64 + extra: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 256 + evidence: + type: object + x-kubernetes-preserve-unknown-fields: true + x-kubernetes-validations: + - rule: '!has(oldSelf.phase) || (has(self.phase) && self.phase in {''Pending'': [''Pending'', ''Admitted'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Admitted'': [''Admitted'', ''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Dispatched'': [''Dispatched'', ''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Verifying'': [''Verifying'', ''Succeeded'', ''Failed'', ''Cancelled'', ''OutcomeUnknown''], ''Succeeded'': [''Succeeded''], ''Failed'': [''Failed''], ''Cancelled'': [''Cancelled''], ''OutcomeUnknown'': [''OutcomeUnknown'']}[oldSelf.phase])' + message: operation phases move forward only, and an ended phase is final + required: + - spec +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecommissioningplans.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCommissioningPlan + listKind: DeviceCommissioningPlanList + plural: devicecommissioningplans + singular: devicecommissioningplan + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: Creator + type: string + jsonPath: .spec.creator.username + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + deviceSelector: + type: object + properties: + matchLabels: + type: object + maxProperties: 16 + additionalProperties: + type: string + maxLength: 63 + matchExpressions: + type: array + maxItems: 16 + items: + type: object + properties: + key: + type: string + minLength: 1 + maxLength: 317 + operator: + type: string + enum: [In, NotIn, Exists, DoesNotExist] + values: + type: array + maxItems: 16 + items: + type: string + maxLength: 63 + required: [key, operator] + x-kubernetes-validations: + - rule: (has(self.matchLabels) && size(self.matchLabels) > 0) || (has(self.matchExpressions) && size(self.matchExpressions) > 0) + message: a plan must select Devices + supersedes: + type: array + maxItems: 16 + items: + type: string + minLength: 1 + maxLength: 253 + x-kubernetes-list-type: set + content: + type: object + properties: + inspection: + type: object + properties: + cpu: + type: object + properties: + architecture: + type: string + enum: [amd64, arm64] + cores: + type: integer + format: int64 + minimum: 1 + maximum: 4096 + required: [architecture, cores] + memory: + type: object + properties: + capacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [capacity] + disks: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + minCapacity: + type: string + pattern: ^[1-9][0-9]{0,6}(Mi|Gi|Ti)$ + required: [count, minCapacity] + interfaces: + type: object + properties: + count: + type: integer + format: int64 + minimum: 1 + maximum: 64 + required: [count] + required: [cpu, memory, disks, interfaces] + firmware: + type: array + maxItems: 32 + items: + type: object + properties: + component: + type: string + minLength: 1 + maxLength: 128 + version: + type: string + minLength: 1 + maxLength: 128 + required: [component, version] + x-kubernetes-list-type: map + x-kubernetes-list-map-keys: [component] + burnIn: + type: object + properties: + image: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 253 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: [name, digest] + duration: + type: string + pattern: ^([0-9]+h)?([0-9]+m)?([0-9]+s)?$ + x-kubernetes-validations: + - rule: self != '' && duration(self) >= duration('1m') && duration(self) <= duration('24h') + message: burn-in runs from 1 minute to 24 hours + required: [image, duration] + required: [inspection, burnIn] + evidenceLifetime: + type: string + pattern: ^([0-9]+h)?([0-9]+m)?([0-9]+s)?$ + x-kubernetes-validations: + - rule: self != '' && duration(self) >= duration('1h') && duration(self) <= duration('8760h') + message: evidence stays current from 1 hour to 365 days + required: + - creator + - deviceSelector + - content + - evidenceLifetime + x-kubernetes-validations: + - rule: self == oldSelf + message: the spec is immutable after create + required: + - spec + x-kubernetes-validations: + - rule: size(self.metadata.name) <= 236 + message: a plan's name leaves room for its approval's suffix +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: devicecommissioningplanapprovals.fleet.datumapis.com + annotations: + discovery.miloapis.com/parent-contexts: Project +spec: + group: fleet.datumapis.com + names: + kind: DeviceCommissioningPlanApproval + listKind: DeviceCommissioningPlanApprovalList + plural: devicecommissioningplanapprovals + singular: devicecommissioningplanapproval + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + additionalPrinterColumns: + - name: Approver + type: string + jsonPath: .spec.creator.username + - name: Digest + type: string + jsonPath: .spec.planRef.digest + schema: + openAPIV3Schema: + type: object + properties: + apiVersion: + type: string + kind: + type: string + metadata: + type: object + spec: + type: object + properties: + creator: + type: object + properties: + username: + type: string + minLength: 1 + maxLength: 512 + uid: + type: string + minLength: 1 + maxLength: 512 + required: + - username + planRef: + type: object + properties: + name: + type: string + minLength: 1 + maxLength: 236 + generation: + type: integer + format: int64 + minimum: 1 + digest: + type: string + pattern: ^sha256:[0-9a-f]{64}$ + required: [name, generation, digest] + required: + - creator + - planRef + x-kubernetes-validations: + - rule: self == oldSelf + message: the spec is immutable after create + required: + - spec + x-kubernetes-validations: + - rule: self.metadata.name.startsWith(self.spec.planRef.name + '-') && size(self.metadata.name) == size(self.spec.planRef.name) + 17 + message: an approval's name is its plan's name and a suffix derived from the plan's UID diff --git a/config/components/device-operations/protected-resources/devicecommissioning.yaml b/config/components/device-operations/protected-resources/devicecommissioning.yaml new file mode 100644 index 00000000..89bfbb7f --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecommissioning.yaml @@ -0,0 +1,20 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecommissioning +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCommissioning + plural: devicecommissionings + singular: devicecommissioning + # Status has one writer, the coordinator. With subresource authorization + # enabled, status writes use devicecommissionings/status.update and + # devicecommissionings/status.patch instead of updateStatus. + permissions: [list, get, watch, create, update, patch, delete, updateStatus] + subresources: + - name: status + permissions: [update, patch] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicecommissioningplan.yaml b/config/components/device-operations/protected-resources/devicecommissioningplan.yaml new file mode 100644 index 00000000..c319de68 --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecommissioningplan.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecommissioningplan +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCommissioningPlan + plural: devicecommissioningplans + singular: devicecommissioningplan + # The spec is immutable after create, so no role grants update or patch. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/devicecommissioningplanapproval.yaml b/config/components/device-operations/protected-resources/devicecommissioningplanapproval.yaml new file mode 100644 index 00000000..0c253986 --- /dev/null +++ b/config/components/device-operations/protected-resources/devicecommissioningplanapproval.yaml @@ -0,0 +1,15 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: ProtectedResource +metadata: + name: fleet.datumapis.com-devicecommissioningplanapproval +spec: + serviceRef: + name: fleet.datumapis.com + kind: DeviceCommissioningPlanApproval + plural: devicecommissioningplanapprovals + singular: devicecommissioningplanapproval + # The spec is immutable after create, so no role grants update or patch. + permissions: [list, get, watch, create, update, patch, delete] + parentResources: + - apiGroup: resourcemanager.miloapis.com + kind: Project diff --git a/config/components/device-operations/protected-resources/kustomization.yaml b/config/components/device-operations/protected-resources/kustomization.yaml index 7b5e6674..c42c594f 100644 --- a/config/components/device-operations/protected-resources/kustomization.yaml +++ b/config/components/device-operations/protected-resources/kustomization.yaml @@ -5,3 +5,6 @@ resources: - deviceinstallation.yaml - devicewipe.yaml - devicerecovery.yaml + - devicecommissioning.yaml + - devicecommissioningplan.yaml + - devicecommissioningplanapproval.yaml diff --git a/config/components/device-operations/roles/coordinator.yaml b/config/components/device-operations/roles/coordinator.yaml index facbdbdd..77b5c27b 100644 --- a/config/components/device-operations/roles/coordinator.yaml +++ b/config/components/device-operations/roles/coordinator.yaml @@ -32,6 +32,18 @@ spec: - fleet.datumapis.com/devicerecoveries.delete - fleet.datumapis.com/devicerecoveries.updateStatus - fleet.datumapis.com/devicerecoveries/status.update + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissionings.delete + - fleet.datumapis.com/devicecommissionings.updateStatus + - fleet.datumapis.com/devicecommissionings/status.update + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch - fleet.datumapis.com/devices.get - fleet.datumapis.com/devices.list - fleet.datumapis.com/devices.watch diff --git a/config/components/device-operations/roles/device-commissioning-operator.yaml b/config/components/device-operations/roles/device-commissioning-operator.yaml new file mode 100644 index 00000000..43db6147 --- /dev/null +++ b/config/components/device-operations/roles/device-commissioning-operator.yaml @@ -0,0 +1,13 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-commissioning-operator + annotations: + kubernetes.io/display-name: Fleet Device Commissioning Operator + kubernetes.io/description: Commission a Device that no customer holds, under its current qualified plan. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicecommissionings.create diff --git a/config/components/device-operations/roles/device-commissioning-plan-approver.yaml b/config/components/device-operations/roles/device-commissioning-plan-approver.yaml new file mode 100644 index 00000000..b4a9c013 --- /dev/null +++ b/config/components/device-operations/roles/device-commissioning-plan-approver.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-commissioning-plan-approver + annotations: + kubernetes.io/display-name: Fleet Device Commissioning Plan Approver + kubernetes.io/description: Approve another person's commissioning plan, or revoke an approval. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicecommissioningplanapprovals.create + - fleet.datumapis.com/devicecommissioningplanapprovals.delete diff --git a/config/components/device-operations/roles/device-commissioning-plan-author.yaml b/config/components/device-operations/roles/device-commissioning-plan-author.yaml new file mode 100644 index 00000000..ec4f503f --- /dev/null +++ b/config/components/device-operations/roles/device-commissioning-plan-author.yaml @@ -0,0 +1,14 @@ +apiVersion: iam.miloapis.com/v1alpha1 +kind: Role +metadata: + name: fleet.datumapis.com-device-commissioning-plan-author + annotations: + kubernetes.io/display-name: Fleet Device Commissioning Plan Author + kubernetes.io/description: Write and delete commissioning plans. An author cannot approve a plan they wrote. +spec: + launchStage: Alpha + inheritedRoles: + - name: fleet.datumapis.com-device-operations-viewer + includedPermissions: + - fleet.datumapis.com/devicecommissioningplans.create + - fleet.datumapis.com/devicecommissioningplans.delete diff --git a/config/components/device-operations/roles/kustomization.yaml b/config/components/device-operations/roles/kustomization.yaml index 0deb9bd5..8885e67a 100644 --- a/config/components/device-operations/roles/kustomization.yaml +++ b/config/components/device-operations/roles/kustomization.yaml @@ -6,3 +6,6 @@ resources: - recovery-operator.yaml - installation-requester.yaml - wipe-requester.yaml + - device-commissioning-operator.yaml + - device-commissioning-plan-author.yaml + - device-commissioning-plan-approver.yaml diff --git a/config/components/device-operations/roles/viewer.yaml b/config/components/device-operations/roles/viewer.yaml index 7a1e5100..49feb7c2 100644 --- a/config/components/device-operations/roles/viewer.yaml +++ b/config/components/device-operations/roles/viewer.yaml @@ -20,3 +20,12 @@ spec: - fleet.datumapis.com/devicerecoveries.get - fleet.datumapis.com/devicerecoveries.list - fleet.datumapis.com/devicerecoveries.watch + - fleet.datumapis.com/devicecommissionings.get + - fleet.datumapis.com/devicecommissionings.list + - fleet.datumapis.com/devicecommissionings.watch + - fleet.datumapis.com/devicecommissioningplans.get + - fleet.datumapis.com/devicecommissioningplans.list + - fleet.datumapis.com/devicecommissioningplans.watch + - fleet.datumapis.com/devicecommissioningplanapprovals.get + - fleet.datumapis.com/devicecommissioningplanapprovals.list + - fleet.datumapis.com/devicecommissioningplanapprovals.watch diff --git a/config/components/device-operations/webhook.yaml b/config/components/device-operations/webhook.yaml index 3958a845..cc3ba1e7 100644 --- a/config/components/device-operations/webhook.yaml +++ b/config/components/device-operations/webhook.yaml @@ -20,5 +20,7 @@ webhooks: - apiGroups: [fleet.datumapis.com] apiVersions: [v1alpha1] operations: [CREATE, UPDATE] - resources: [deviceinstallations, devicewipes, devicerecoveries] + # The same list as creatorwebhook.Resources and the standalone creator + # policy; TestPackagedResourcesMatch keeps them in step. + resources: [deviceinstallations, devicewipes, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] scope: Namespaced diff --git a/config/standalone/rbac.yaml b/config/standalone/rbac.yaml index 3c5e477b..ace349f6 100644 --- a/config/standalone/rbac.yaml +++ b/config/standalone/rbac.yaml @@ -133,11 +133,14 @@ rules: resources: [devicecustodies] verbs: [get, list, watch, create, update, delete] - apiGroups: [fleet.datumapis.com] - resources: [deviceinstallations, devicewipes, devicerecoveries] + resources: [deviceinstallations, devicewipes, devicerecoveries, devicecommissionings] verbs: [get, list, watch, delete] - apiGroups: [fleet.datumapis.com] - resources: [deviceinstallations/status, devicewipes/status, devicerecoveries/status] + resources: [deviceinstallations/status, devicewipes/status, devicerecoveries/status, devicecommissionings/status] verbs: [get, update] + - apiGroups: [fleet.datumapis.com] + resources: [devicecommissioningplans, devicecommissioningplanapprovals] + verbs: [get, list, watch] - apiGroups: [metal.datumapis.com] resources: [machineallocations] verbs: [get, list, watch] diff --git a/config/standalone/site.yaml b/config/standalone/site.yaml index 06b90e09..bca62a78 100644 --- a/config/standalone/site.yaml +++ b/config/standalone/site.yaml @@ -51,7 +51,9 @@ spec: - apiGroups: [fleet.datumapis.com] apiVersions: ["*"] operations: [CREATE, UPDATE] - resources: [deviceinstallations, devicewipes, devicerecoveries] + # The same list as the packaged webhook; TestPackagedResourcesMatch + # keeps them in step. + resources: [deviceinstallations, devicewipes, devicerecoveries, devicecommissionings, devicecommissioningplans, devicecommissioningplanapprovals] validations: - expression: "request.operation != 'CREATE' || (object.spec.creator.username == request.userInfo.username && (has(object.spec.creator.uid) ? object.spec.creator.uid : '') == (has(request.userInfo.uid) ? request.userInfo.uid : ''))" message: spec.creator must be the authenticated caller's username, and UID when it has one diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 71e36863..6a105b56 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -16,6 +16,7 @@ marked **implemented and verified**, **implemented and inert**, or | B: site execution | Per-Device fence store and journal, older-worker stop with a confirmation, deadlines, fenced typed results, per-Device credentials, pinned TLS, identity checks, the handoff payload, the site fence report, and the Redfish install and wipe phases behind the worker contract | **Implemented and verified.** Unit tested, including against TLS BMC stubs. Increment C delivers to it. | | C: cutover | MachineAllocations and quota claims named from the Machine UID, allocation and release on custody, the delivery loop, the simulator, local VM and Redfish sites, the creator webhook in the production Milo root, the manager's power projector, and deletion of the Secret-backed records and executors. See [Cutover](#cutover-increment-c). | **Implemented.** Verified by unit tests, tests against a real API server, the standalone smoke (`task standalone:test`), and both multi-plane runs, local VM and Redfish. | | D: end-to-end failure scenarios | Harness phases and evidence checks for the #174 acceptance tests, and the two site fixes they found. See [Failure scenarios](#failure-scenarios-increment-d). | **Implemented and verified** by unit tests and both multi-plane runs, local VM and Redfish. | +| Commissioning, step 1 | `DeviceCommissioning`, `DeviceCommissioningPlan` and `DeviceCommissioningPlanApproval`: CRDs, ProtectedResources, roles, the creator webhook route, the kind and its rows, plan qualification and the current plan. See [Commissioning](#commissioning). | **Implemented and inert.** Verified by tests against a real API server. No site runs a commissioning worker yet, and no mode creates one. | ## What Increment A adds @@ -817,17 +818,82 @@ these seams. Each is decided here. | 4 | The settle hook sees the hold's end time, its deadline and current Device status | The hold records when it ended (`Since`), the operation's deadline and its snapshot. The hook gets the Device as read when the recovery is admitted and again when it is applied. A hold that rebuild created has `Since` set to the rebuild time, and copies the deadline and snapshot from the operation's status, so both are absent for an operation whose status never recorded them. A hook checks for that. | Implemented and inert | | 5 | Kinds register their refusal reasons | Each reason is declared with where it is raised. The registry refuses a malformed name, a shared name, a duplicate, or a missing source. A coordinator refusal, or a site result, with an undeclared reason is recorded as `UndeclaredReason`. A recovery's refusal may carry the held kind's declared reason only when it comes from that kind's settle hook. The site framework's own reasons are shared, and the Redfish workers' reasons are declared on their kinds. | Implemented and inert | | 6 | A kind may settle no hold, and declares whether `Retry` applies | `Settles` may be empty. `Retryable` marks a kind whose holds a `Retry` may unblock: a wipe, and power, whose hold settles with `Settle` and fresh discovery evidence or with `Retry` and a later power operation. A hold counts the `Retry` decisions applied to it, and the operation created after a `Retry` is named from the held operation and that count, as [Retries](#admission) describes. | Implemented and inert | -| 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse eight forbidden writes, and removes them. | Implemented and verified in the local end-to-end runs | +| 7 | End-to-end proof that Milo enforces the CRD rules | The `custody-crd-rules` phase of both local end-to-end runs installs only these CRDs into the provider project, requires the project API to refuse 19 forbidden writes, eleven of them to the commissioning kinds, and removes them. | Implemented and verified in the local end-to-end runs | | 8 | Journal steps carry a kind's payload | A step records a payload of at most 1 KiB, such as the send time or the power state before, journaled before it is sent. Observation after a crash reads it back. | Implemented and inert | | 9 | Delivery carries the admission time, and kinds declare a start-by window | A kind that implements `StartBy` refuses as `Stale` when its worker starts later than the window after admission, with nothing sent. A worker resuming steps an earlier worker sent is not stale. | Implemented and inert | | 10 | The TLS and identity check is separate from install capabilities | The framework verifies the pin and the System only, through the Redfish client's identity walk. Each kind checks the capabilities it uses, such as the Pxe and Hdd boot targets, and drives the System through a connection bound to it. | Implemented and inert | | 11 | A worker refusal with nothing sent ends `Failed` | It ends `Failed` under the operation's fence and returns a `Service` holder to `None`. It never ends `OutcomeUnknown`. Whether anything was sent comes from the journal. | Implemented and inert | | 12 | The single writer of `Machine.status.power` | The manager's `PowerProjector` is the only writer. It reads the custody of the Machine's allocation: while a recovery hold exists, or custody is unverified, it reports power `Unknown`. Otherwise it reports the power state discovery last observed. A Machine with no active allocation has no power. The harness runners call the same projection. A power operation's evidence becomes a second source when the power kind exists. | Implemented and verified by the standalone smoke, which reads the projected state | +| 13 | A deadline from the operation's inputs | `DeadlineFor` replaces the kind's fixed `Deadline` at admission. Commissioning uses its plan's burn-in duration plus one hour. | Implemented and verified by `TestCommissioning` | +| 14 | Evidence kept past retention | `KeepsLatest` keeps each Device's latest succeeded operation of the kind. Commissioning uses it, because the capacity projector reads it. | Implemented and verified by `TestCommissioning` | Rows 1 to 11 keep the status recorded when Increment A added them. The install and wipe kinds use some of them, such as step payloads and the refusal -rule. No power or commissioning kind exists yet, so no shipped kind uses the -settle hook or `Supersedes`. None of these conflicts with #174. +rule. No power kind exists yet, and commissioning uses neither, so no shipped +kind uses the settle hook or `Supersedes`. None of these conflicts with #174. + +## Commissioning + +This implements the kinds of the [commissioning +proposal](https://github.com/datum-cloud/fleet/pull/185). Step 1 is +**implemented and inert**: custody admits, holds and settles commissioning, +but no site runs its worker. Staff with the commissioning operator role can +still create one. It then holds the Device as `Service` until its deadline +and ends `OutcomeUnknown`, leaving a commissioning hold that only a later +commissioning settles. Every mode's coordinator role can read the new kinds, +which a test pins, because the coordinator lists every registered kind. + +- **Plans.** `DeviceCommissioningPlan` has an immutable spec with a creator, a + non-empty Device selector, plans it supersedes, the content the site runs, + and an evidence lifetime of 1 hour to 365 days. Burn-in runs 1 minute to 24 + hours. No spec holds an object UID. An approval's name is the plan's name + and a suffix derived from the plan's UID (`custody.ApprovalName`), and its + spec names the plan's generation and the digest of its whole spec + (`custody.PlanDigest`). A commissioning names the plan the same way plus + the approval's name, which pins the plan incarnation. The creator webhook + governs all three, so each creator is the caller. +- **Qualified.** An approval qualifies its plan when it has the plan's + approval name, names the plan's current generation and digest, and its + creator is someone else: both creators have a username and the usernames + differ ignoring case. A client certificate carries no UID, so UIDs are + compared only when both creators have one, and then they must differ. A plan re-created under the same name has + another approval name, so it inherits no approval, and no commissioning + under the old plan is admitted under it. No role both writes and approves + plans, which a test pins. +- **Residual window.** Admission reads the plan and its approval before the + custody update, which re-checks only the Device. A plan revoked in between + can still be admitted once. No capacity projector reads commissioning yet, + so this increment makes nothing `Prepared`. The projector that does must + check the plan's qualification again when it reads a commissioning, so + that run cannot make a server `Prepared` under a revoked plan (O1). +- **Current plan.** The qualified plans whose selector matches the Device's + labels, minus those another of them supersedes. One left is the current + plan. None left with none matching is `NoCurrentPlan`. More than one, or + none left because the matching plans supersede each other, is + `PlanAmbiguous`. A supersession reaches only Devices the superseding plan + selects, and revoking it restores the old plan. `supersedes` names plans, + so a plan re-created under a superseded name stays superseded. That fails + closed: the plan inherits no approval, only the supersession. +- **Admission.** Two staff rows: from `None`, and from `Service` only to settle + a commissioning hold. The kind refuses a Device that is not `Active`, one + without a `primary` interface MAC (`BootInterfaceUnknown`), a plan that is + missing, re-created or not qualified (`PlanNotQualified`), a copied + content, generation or digest that differs from the plan (`PlanMismatch`), and a plan that is + not the Device's current plan (`PlanNotCurrent`). +- **Results.** A proven verdict ends `Succeeded` with result `Passed` or + `Failed` in its evidence. A `Passed` result must record the serial number, + system UUID and BMC key the admission snapshot holds, hardware that meets + the plan, every firmware baseline at its version, and a passed burn-in at + least as long as the plan's. A `Failed` result must name the phase and what + failed. Other evidence proves nothing, and the operation ends + `OutcomeUnknown`. Evidence is limited to 16 KiB. +- **Retention.** Each existing Device incarnation's latest succeeded + commissioning is kept past retention. Once the Device is deleted or + re-created, the old incarnation's record ages out normally. +- **Holds.** A later commissioning that ends `Succeeded` settles a + commissioning hold. It needs no `Retry`. + +The boot interface is fixed at `primary`, like the allocator's in every mode. ## Points for a person @@ -835,7 +901,12 @@ These need a decision before the increment that depends on them. - **O1: the interim source of `Prepared` and `Healthy`.** Still open after C. The projector stays unwired, so the synthetic fixtures write `Prepared`, - `Healthy` and `Available` themselves. + `Healthy` and `Available` themselves. When the projector reads + commissioning, it must check the plan's qualification again, which closes + the residual window of [Commissioning](#commissioning). +- **Who approves commissioning plans.** No team holds the plan approver role + in any deployed environment yet, so no plan qualifies there. The roles keep + the author and the approver apart by username. - **O10: the sealed store for bootstrap payloads.** Bootstrap stays refused in every increment until a store is chosen. - **A second person for `DeviceRecovery`.** Not required yet. A person diff --git a/docs/operations/multiplane.md b/docs/operations/multiplane.md index bb128f23..4d162455 100644 --- a/docs/operations/multiplane.md +++ b/docs/operations/multiplane.md @@ -328,11 +328,15 @@ The phases are then: it proves the narrowed grant and the admission policies on kro's writes ([trust model](site-execution.md#ownership-and-trust-model)). `custody-crd-rules` then installs only the [Device custody](../development/device-custody.md) - CRDs into the provider project. It requires the project API to refuse eight + CRDs into the provider project. It requires the project API to refuse 19 writes their CEL rules forbid: changing an operation's spec or creator, moving a phase backward or out of an ended phase, setting both authorities, lowering a custody fence, leaving `Retired`, and naming custody after - another Device. It then removes the objects and the CRDs. Milo ignores + another Device; and for the commissioning kinds, changing a plan's, + approval's or commissioning's spec, a plan that selects nothing, an + evidence lifetime or burn-in outside its bounds, a plan name with no room + for its approval's suffix, an approval not named for its plan, and moving a + commissioning's phase backward or out of an ended phase. It then removes the objects and the CRDs. Milo ignores admission policies stored in a project, so this proves the rules hold there. It sends nothing to any server. `import-inert` then requires that importing the Devices admitted, diff --git a/hack/multiplane/custody_crd_rules.py b/hack/multiplane/custody_crd_rules.py index 5de1a16b..7307959c 100644 --- a/hack/multiplane/custody_crd_rules.py +++ b/hack/multiplane/custody_crd_rules.py @@ -17,8 +17,11 @@ # creates no namespace, because a project API may not run a namespace # controller to finish deleting one. namespace = 'fleet-rules' -objects = (('devicerecovery', 'rules-recovery'), ('devicecustody', 'server-example-001')) -names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicerecoveries') +objects = (('devicerecovery', 'rules-recovery'), ('devicecustody', 'server-example-001'), ('devicecommissioning', 'rules-commissioning'), + ('devicecommissioningplanapproval', 'rules-plan-0123456789abcdef'), ('devicecommissioningplan', 'rules-plan')) +names = ('devicecustodies', 'deviceinstallations', 'devicewipes', 'devicerecoveries', 'devicecommissionings', 'devicecommissioningplans', + 'devicecommissioningplanapprovals') +DIGEST = 'sha256:' + '0' * 64 def kubectl(*args, stdin=None, check=True): @@ -43,6 +46,15 @@ def refused(what, *args, stdin=None): raise SystemExit('custody-crd-rules: the project API accepted a write that breaks: ' + what) +def copy(obj, name=None, **spec): + """A deep copy of obj, renamed and with spec fields replaced.""" + out = json.loads(json.dumps(obj)) + if name: + out['metadata']['name'] = name + out['spec'].update(spec) + return out + + def status(kind, name, phase): return kubectl('-n', namespace, 'patch', kind, name, '--subresource=status', '--type=merge', '-p', json.dumps({'status': {'phase': phase}}), check=False) @@ -91,6 +103,50 @@ def status(kind, name, phase): mismatch['metadata']['name'] = 'server-example-002' mismatch['metadata']['namespace'] = namespace refused('custody has the same name as its Device', 'create', '-f', '-', stdin=json.dumps(mismatch)) + + # Commissioning plans, their approvals and commissionings. The objects are + # synthetic; the coordinator never reads this namespace, so nothing + # qualifies the plan or admits the commissioning. + content = {'inspection': {'cpu': {'architecture': 'amd64', 'cores': 2}, 'memory': {'capacity': '2Gi'}, + 'disks': {'count': 1, 'minCapacity': '1Gi'}, 'interfaces': {'count': 1}}, + 'burnIn': {'image': {'name': 'burn-in-example', 'digest': DIGEST}, 'duration': '10m'}} + plan = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'DeviceCommissioningPlan', + 'metadata': {'name': 'rules-plan', 'namespace': namespace}, + 'spec': {'creator': envelope['creator'], 'deviceSelector': {'matchLabels': {'example.com/model': 'example'}}, + 'content': content, 'evidenceLifetime': '24h'}} + apply(plan) + refused('the spec is immutable after create', '-n', namespace, 'patch', 'devicecommissioningplan', 'rules-plan', + '--type=merge', '-p', json.dumps({'spec': {'evidenceLifetime': '48h'}})) + refused('a plan must select Devices', 'create', '-f', '-', stdin=json.dumps(copy(plan, 'rules-plan-unselective', deviceSelector={}))) + refused('evidence stays current from 1 hour to 365 days', 'create', '-f', '-', stdin=json.dumps(copy(plan, 'rules-plan-lifetime', evidenceLifetime='30m'))) + refused('burn-in runs from 1 minute to 24 hours', 'create', '-f', '-', + stdin=json.dumps(copy(plan, 'rules-plan-burn-in', content=dict(content, burnIn=dict(content['burnIn'], duration='25h'))))) + refused("a plan's name leaves room for its approval's suffix", 'create', '-f', '-', stdin=json.dumps(copy(plan, 'p' * 237))) + approval = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'DeviceCommissioningPlanApproval', + 'metadata': {'name': 'rules-plan-0123456789abcdef', 'namespace': namespace}, + 'spec': {'creator': {'username': 'approver-example'}, 'planRef': {'name': 'rules-plan', 'generation': 1, 'digest': DIGEST}}} + apply(approval) + refused('the spec is immutable after create', '-n', namespace, 'patch', 'devicecommissioningplanapproval', 'rules-plan-0123456789abcdef', + '--type=merge', '-p', json.dumps({'spec': {'planRef': {'generation': 2}}})) + refused("an approval's name is its plan's name and a suffix", 'create', '-f', '-', stdin=json.dumps(copy(approval, 'rules-plan-short'))) + commissioning = {'apiVersion': 'fleet.datumapis.com/v1alpha1', 'kind': 'DeviceCommissioning', + 'metadata': {'name': 'rules-commissioning', 'namespace': namespace}, + 'spec': dict(envelope, plan={'name': 'rules-plan', 'generation': 1, 'digest': DIGEST, + 'approval': 'rules-plan-0123456789abcdef', 'content': content})} + apply(commissioning) + refused('an operation spec is immutable after create', '-n', namespace, 'patch', 'devicecommissioning', 'rules-commissioning', + '--type=merge', '-p', json.dumps({'spec': {'authority': {'serviceRequest': {'reason': 'changed'}}}})) + refused('burn-in runs from 1 minute to 24 hours', 'create', '-f', '-', + stdin=json.dumps(copy(commissioning, 'rules-commissioning-short', plan=dict(commissioning['spec']['plan'], content=dict(content, burnIn=dict(content['burnIn'], duration='30s')))))) + for phase in ('Pending', 'Admitted', 'Dispatched'): + if status('devicecommissioning', 'rules-commissioning', phase).returncode != 0: + raise SystemExit('custody-crd-rules: a forward commissioning phase change was refused') + refused('operation phases move forward only', '-n', namespace, 'patch', 'devicecommissioning', 'rules-commissioning', '--subresource=status', + '--type=merge', '-p', json.dumps({'status': {'phase': 'Pending'}})) + if status('devicecommissioning', 'rules-commissioning', 'Failed').returncode != 0: + raise SystemExit('custody-crd-rules: ending a commissioning Failed was refused') + refused('an ended phase is final', '-n', namespace, 'patch', 'devicecommissioning', 'rules-commissioning', '--subresource=status', + '--type=merge', '-p', json.dumps({'status': {'phase': 'Succeeded'}})) finally: # The rule-check custody carries no finalizer: nothing reconciles this # namespace, so it is deleted at once. diff --git a/hack/multiplane/evidence.py b/hack/multiplane/evidence.py index 5ef5357f..476cd39f 100755 --- a/hack/multiplane/evidence.py +++ b/hack/multiplane/evidence.py @@ -79,7 +79,7 @@ def copy_out(source, destination): fail('missing independent native project create/watch evidence') custody_rules = json.loads((ev / 'custody-crd-rules.json').read_text()) -if not custody_rules.get('objectsRemoved') or len(custody_rules.get('checks', [])) != 8 or not all(c.get('refused') for c in custody_rules['checks']): +if not custody_rules.get('objectsRemoved') or len(custody_rules.get('checks', [])) != 19 or not all(c.get('refused') for c in custody_rules['checks']): fail('the provider project API did not refuse every forbidden custody write') phases = (s / 'phases.log').read_text() diff --git a/hack/multiplane/harness.py b/hack/multiplane/harness.py index 6a7cf1d5..f6062f97 100755 --- a/hack/multiplane/harness.py +++ b/hack/multiplane/harness.py @@ -76,7 +76,8 @@ def device_dir(device=DEVICE): FINAL_STEPS = {'DeviceInstallation': ('disk-verified',), 'DeviceWipe': ('wipe', 'wipe-verified')} # Provider-project custody records, read with the provider's bootstrap credential. CUSTODY_KINDS = ('devicecustodies.fleet.datumapis.com', 'deviceinstallations.fleet.datumapis.com', 'devicewipes.fleet.datumapis.com', - 'devicerecoveries.fleet.datumapis.com', 'machineallocations.metal.datumapis.com') + 'devicerecoveries.fleet.datumapis.com', 'devicecommissionings.fleet.datumapis.com', 'devicecommissioningplans.fleet.datumapis.com', + 'devicecommissioningplanapprovals.fleet.datumapis.com', 'machineallocations.metal.datumapis.com') def now(): diff --git a/hack/multiplane/milo.py b/hack/multiplane/milo.py index 17da267f..75e655ce 100755 --- a/hack/multiplane/milo.py +++ b/hack/multiplane/milo.py @@ -91,10 +91,13 @@ def wait(fn,seconds,what): # reads custody and Devices only to skip taken capacity. rules+=[{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch','create','delete']},{'apiGroups':['metal.datumapis.com'],'resources':['machineallocations/status'],'verbs':['get','update']}, {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations'],'verbs':['get','list','watch','create']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices','devicecustodies'],'verbs':['get','list','watch']}] + # The coordinator rules mirror config/components/device-operations/roles/ + # coordinator.yaml: it lists and settles every registered operation kind. components={ 'coordinator':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list','watch']},{'apiGroups':['fleet.datumapis.com'],'resources':['devicecustodies'],'verbs':['get','list','watch','create','update','delete']}, - {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicerecoveries'],'verbs':['get','list','watch','delete']}, - {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status'],'verbs':['get','update']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations','devicewipes','devicerecoveries','devicecommissionings'],'verbs':['get','list','watch','delete']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['deviceinstallations/status','devicewipes/status','devicerecoveries/status','devicecommissionings/status'],'verbs':['get','update']}, + {'apiGroups':['fleet.datumapis.com'],'resources':['devicecommissioningplans','devicecommissioningplanapprovals'],'verbs':['get','list','watch']}, {'apiGroups':['metal.datumapis.com'],'resources':['machineallocations'],'verbs':['get','list','watch']}], 'release':[{'apiGroups':['fleet.datumapis.com'],'resources':['devicewipes'],'verbs':['get','create']}], 'discovery':[{'apiGroups':['fleet.datumapis.com'],'resources':['devices'],'verbs':['get','list']},{'apiGroups':['fleet.datumapis.com'],'resources':['devices/status'],'verbs':['get','update']}], diff --git a/hack/standalone-smoke.sh b/hack/standalone-smoke.sh index dfdd281b..c017cab7 100755 --- a/hack/standalone-smoke.sh +++ b/hack/standalone-smoke.sh @@ -52,7 +52,7 @@ for crd in installations machineallocations machinecapacities machineclasses mac exit 1 fi done -for crd in devices devicecustodies deviceinstallations devicewipes devicerecoveries; do +for crd in devices devicecustodies deviceinstallations devicewipes devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals; do if kubectl --context "$context" get crd "$crd.fleet.datumapis.com" >/dev/null 2>&1; then echo "fixed Fleet CRD $crd already exists; use a fresh dedicated kind cluster" >&2 exit 1 @@ -143,7 +143,7 @@ test "$(kubectl --context "$context" -n fleet-project-b get machine allocation - for project in fleet-project-a fleet-project-b; do subject="system:serviceaccount:$project:default" - for resource in devicecustodies deviceinstallations devicewipes devicerecoveries machineallocations; do + for resource in devicecustodies deviceinstallations devicewipes devicerecoveries devicecommissionings devicecommissioningplans devicecommissioningplanapprovals machineallocations; do for verb in get list watch create update patch delete; do if [ "$(kubectl --context "$context" auth can-i "$verb" "$resource" --as="$subject" -n fleet-provider)" != "no" ]; then echo "$subject unexpectedly has $verb access to $resource" >&2 diff --git a/internal/api/operations/v1alpha1/commissioning.go b/internal/api/operations/v1alpha1/commissioning.go new file mode 100644 index 00000000..6fbfad78 --- /dev/null +++ b/internal/api/operations/v1alpha1/commissioning.go @@ -0,0 +1,251 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" +) + +// DeviceCommissioningPlan says what commissioning must prove for the Devices +// its selector matches. Its spec is immutable; a new plan replaces it. A plan +// is qualified only while a DeviceCommissioningPlanApproval with its approval +// name, generation and digest exists and was created by someone other than +// the plan's creator. +type DeviceCommissioningPlan struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceCommissioningPlanSpec `json:"spec"` +} + +type DeviceCommissioningPlanSpec struct { + // Creator is the authenticated caller that wrote the plan. + Creator Creator `json:"creator"` + // DeviceSelector selects Devices by label. An empty selector matches + // nothing. + DeviceSelector metav1.LabelSelector `json:"deviceSelector"` + // Supersedes names plans that stop being current once this plan is + // qualified. + Supersedes []string `json:"supersedes,omitempty"` + // Content is what the site runs. A DeviceCommissioning carries an exact + // copy of it. + Content CommissioningPlanContent `json:"content"` + // EvidenceLifetime is how long a succeeded commissioning stays current. + EvidenceLifetime metav1.Duration `json:"evidenceLifetime"` +} + +// CommissioningPlanContent is the part of a plan the site runs. +type CommissioningPlanContent struct { + Inspection CommissioningInspection `json:"inspection"` + Firmware []FirmwareBaseline `json:"firmware,omitempty"` + BurnIn CommissioningBurnIn `json:"burnIn"` +} + +// CommissioningInspection is the hardware the server must report. CPU and +// memory must match exactly; disks and interfaces are minimums. Every +// reported component must be healthy. +type CommissioningInspection struct { + CPU InspectionCPU `json:"cpu"` + Memory InspectionValue `json:"memory"` + Disks InspectionDisks `json:"disks"` + Interfaces InspectionCount `json:"interfaces"` +} + +type InspectionCPU struct { + Architecture string `json:"architecture"` + Cores int64 `json:"cores"` +} + +type InspectionValue struct { + // Capacity is a Kubernetes quantity, such as 256Gi. + Capacity string `json:"capacity"` +} + +type InspectionDisks struct { + Count int64 `json:"count"` + MinCapacity string `json:"minCapacity"` +} + +type InspectionCount struct { + Count int64 `json:"count"` +} + +// FirmwareBaseline is the exact version one firmware component must report. +type FirmwareBaseline struct { + Component string `json:"component"` + Version string `json:"version"` +} + +// CommissioningBurnIn is the burn-in image, pinned by digest, and how long it +// runs. +type CommissioningBurnIn struct { + Image ImageInput `json:"image"` + Duration metav1.Duration `json:"duration"` +} + +// DeviceCommissioningPlanApproval qualifies the plan with the same name. Its +// spec is immutable; deleting it revokes the qualification. +type DeviceCommissioningPlanApproval struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceCommissioningPlanApprovalSpec `json:"spec"` +} + +type DeviceCommissioningPlanApprovalSpec struct { + // Creator is the authenticated approver. It must differ from the plan's + // creator. + Creator Creator `json:"creator"` + PlanRef PlanReference `json:"planRef"` +} + +// PlanReference names a plan and pins its content with its generation and +// the digest of its spec. +type PlanReference struct { + Name string `json:"name"` + Generation int64 `json:"generation"` + Digest string `json:"digest"` +} + +// ApprovedPlanReference is a plan reference and the approval that qualified +// it. The approval's name is derived from the plan's UID, so it pins the plan +// incarnation: a plan recreated under the same name has another approval +// name. +type ApprovedPlanReference struct { + PlanReference `json:",inline"` + Approval string `json:"approval"` +} + +// DeviceCommissioning runs a qualified plan on a Device that no customer +// holds. Staff create it with a serviceRequest. +type DeviceCommissioning struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec DeviceCommissioningSpec `json:"spec"` + Status OperationStatus `json:"status,omitempty"` +} + +type DeviceCommissioningSpec struct { + OperationEnvelope `json:",inline"` + Plan CommissioningPlanInput `json:"plan"` +} + +// CommissioningPlanInput names the plan and carries an exact copy of its +// content, so the site runs exactly what admission checked. +type CommissioningPlanInput struct { + ApprovedPlanReference `json:",inline"` + Content CommissioningPlanContent `json:"content"` +} + +// CommissioningEvidence is the result evidence of a DeviceCommissioning. It +// never carries a credential or BMC response content. +type CommissioningEvidence struct { + Plan ApprovedPlanReference `json:"plan"` + // Result is the proven verdict. A commissioning whose verdict is proven + // ends Succeeded whether the server passed or failed. + Result CommissioningResult `json:"result"` + // FailedPhase is the phase that failed, for a Failed result. + FailedPhase CommissioningPhase `json:"failedPhase,omitempty"` + // SerialNumber and SystemUUID are what the BMC reported. + SerialNumber string `json:"serialNumber,omitempty"` + SystemUUID string `json:"systemUUID,omitempty"` + BMCPublicKeySHA256 string `json:"bmcPublicKeySHA256,omitempty"` + Hardware *InspectedHardware `json:"hardware,omitempty"` + Firmware []FirmwareBaseline `json:"firmware,omitempty"` + BurnIn *BurnInEvidence `json:"burnIn,omitempty"` + Steps []StepEvidence `json:"steps,omitempty"` + // Mismatches lists what failed, for a Failed result. + Mismatches []string `json:"mismatches,omitempty"` +} + +// InspectedHardware is what inspection read, in the shape of MachineCapacity +// hardware. +type InspectedHardware struct { + CPU InspectedCPU `json:"cpu"` + Memory string `json:"memory"` + Disks []InspectedDisk `json:"disks,omitempty"` + Interfaces []InspectedInterface `json:"interfaces,omitempty"` +} + +type InspectedCPU struct { + Architecture string `json:"architecture,omitempty"` + Model string `json:"model,omitempty"` + Sockets int64 `json:"sockets,omitempty"` + Cores int64 `json:"cores,omitempty"` +} + +type InspectedDisk struct { + Name string `json:"name"` + Capacity string `json:"capacity"` +} + +type InspectedInterface struct { + Name string `json:"name"` + MACAddress string `json:"macAddress,omitempty"` + Speed string `json:"speed,omitempty"` +} + +// CommissioningResult is a commissioning's proven verdict. +type CommissioningResult string + +const ( + CommissioningPassed CommissioningResult = "Passed" + CommissioningFailed CommissioningResult = "Failed" +) + +// CommissioningPhase is one phase of a commissioning. +type CommissioningPhase string + +const ( + PhaseInspect CommissioningPhase = "Inspect" + PhaseFirmware CommissioningPhase = "Firmware" + PhaseBurnIn CommissioningPhase = "BurnIn" +) + +// BurnInResult is what the burn-in image reported. +type BurnInResult string + +const ( + BurnInPassed BurnInResult = "Passed" + BurnInFailed BurnInResult = "Failed" +) + +type BurnInEvidence struct { + Result BurnInResult `json:"result"` + StartedAt metav1.Time `json:"startedAt"` + CompletedAt metav1.Time `json:"completedAt"` +} + +type DeviceCommissioningPlanList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceCommissioningPlan `json:"items"` +} + +type DeviceCommissioningPlanApprovalList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceCommissioningPlanApproval `json:"items"` +} + +type DeviceCommissioningList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []DeviceCommissioning `json:"items"` +} + +func (in *DeviceCommissioning) Envelope() *OperationEnvelope { return &in.Spec.OperationEnvelope } +func (in *DeviceCommissioning) OperationStatus() *OperationStatus { return &in.Status } + +func (in *DeviceCommissioningPlan) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceCommissioningPlanList) DeepCopyObject() runtime.Object { + return deepCopy(in) +} +func (in *DeviceCommissioningPlanApproval) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceCommissioningPlanApprovalList) DeepCopyObject() runtime.Object { + return deepCopy(in) +} +func (in *DeviceCommissioning) DeepCopyObject() runtime.Object { return deepCopy(in) } +func (in *DeviceCommissioningList) DeepCopyObject() runtime.Object { return deepCopy(in) } + +func addCommissioning(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &DeviceCommissioningPlan{}, &DeviceCommissioningPlanList{}, &DeviceCommissioningPlanApproval{}, &DeviceCommissioningPlanApprovalList{}, &DeviceCommissioning{}, &DeviceCommissioningList{}) + return nil +} diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index 815171f7..ce72cb56 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -20,7 +20,10 @@ import ( var ( configRoot = filepath.Join("..", "..", "..", "..", "config") componentRoot = filepath.Join(configRoot, "components", "device-operations") - operationKinds = []string{"DeviceInstallation", "DeviceWipe", "DeviceRecovery"} + operationKinds = []string{"DeviceInstallation", "DeviceWipe", "DeviceRecovery", "DeviceCommissioning"} + // planKinds are staff records, not operations: an immutable spec with a + // creator, and no status. + planKinds = []string{"DeviceCommissioningPlan", "DeviceCommissioningPlanApproval"} ) func decodeAll[T any](t *testing.T, path string) []T { @@ -69,8 +72,8 @@ func loadCRDs(t *testing.T) map[string]*extensionsv1.CustomResourceDefinition { func TestCRDContract(t *testing.T) { crds := loadCRDs(t) - if len(crds) != 4 || crds["DeviceCustody"] == nil { - t.Fatalf("got %d CRDs, want DeviceCustody and three operation kinds", len(crds)) + if len(crds) != 1+len(operationKinds)+len(planKinds) || crds["DeviceCustody"] == nil { + t.Fatalf("got %d CRDs, want DeviceCustody, the operation kinds and the plan kinds", len(crds)) } for kind, crd := range crds { version := crd.Spec.Versions[0] @@ -86,6 +89,14 @@ func TestCRDContract(t *testing.T) { if version.Subresources != nil || len(properties["status"].Properties) != 0 { t.Fatal("DeviceCustody has no status") } + } else if slices.Contains(planKinds, kind) { + spec := properties["spec"] + if version.Subresources != nil || len(properties["status"].Properties) != 0 || !slices.Contains(spec.Required, "creator") { + t.Fatalf("%s is a record with a creator and no status", kind) + } + if len(spec.XValidations) == 0 || spec.XValidations[0].Rule != "self == oldSelf" { + t.Fatalf("%s spec must be immutable", kind) + } } else { if version.Subresources == nil || version.Subresources.Status == nil { t.Fatalf("%s status must be a subresource, written only by the coordinator", kind) @@ -188,15 +199,20 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { group := GroupVersion.Group + "/" read := []string{"get", "list", "watch"} want := map[string][]string{ - "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicerecoveries", read...)), - "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), - "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), - "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + "fleet.datumapis.com-device-operations-viewer": slices.Concat(p(group+"devicecustodies", read...), p(group+"deviceinstallations", read...), p(group+"devicewipes", read...), p(group+"devicerecoveries", read...), + p(group+"devicecommissionings", read...), p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)), + "fleet.datumapis.com-device-commissioning-operator": p(group+"devicecommissionings", "create"), + "fleet.datumapis.com-device-commissioning-plan-author": p(group+"devicecommissioningplans", "create", "delete"), + "fleet.datumapis.com-device-commissioning-plan-approver": p(group+"devicecommissioningplanapprovals", "create", "delete"), + "fleet.datumapis.com-device-recovery-operator": slices.Concat(p(group+"devicerecoveries", "create"), p("metal.datumapis.com/machineallocations", read...)), + "fleet.datumapis.com-device-installation-requester": slices.Concat(p(group+"deviceinstallations", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), + "fleet.datumapis.com-device-wipe-requester": slices.Concat(p(group+"devicewipes", "create", "get", "list", "watch"), p(group+"devicecustodies", read...)), } coordinator := slices.Concat(p(group+"devicecustodies", "get", "list", "watch", "create", "update", "delete"), p(group+"devices", read...), p("metal.datumapis.com/machineallocations", read...), p("metal.datumapis.com/machinecapacities", read...)) - for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries"} { + for _, plural := range []string{"deviceinstallations", "devicewipes", "devicerecoveries", "devicecommissionings"} { coordinator = slices.Concat(coordinator, p(group+plural, "get", "list", "watch", "delete", "updateStatus"), []string{group + plural + "/status.update"}) } + coordinator = slices.Concat(coordinator, p(group+"devicecommissioningplans", read...), p(group+"devicecommissioningplanapprovals", read...)) want["fleet.datumapis.com-device-coordinator"] = coordinator if len(roles) != len(want) { t.Fatalf("roles = %v", roles) @@ -213,9 +229,9 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { t.Fatalf("%s = %v, want %v", name, actual, expected) } inherits := len(current.Spec.Inherited) != 0 - if name == "fleet.datumapis.com-device-recovery-operator" { + if name == "fleet.datumapis.com-device-recovery-operator" || strings.HasPrefix(name, "fleet.datumapis.com-device-commissioning-") { if len(current.Spec.Inherited) != 1 || current.Spec.Inherited[0].Name != "fleet.datumapis.com-device-operations-viewer" { - t.Fatal("the recovery operator inherits only the viewer") + t.Fatalf("%s inherits only the viewer", name) } } else if inherits { t.Fatalf("%s must not inherit", name) @@ -234,9 +250,10 @@ func TestRolesKeepOneWriterAndKeepStaffFromCustomerSecrets(t *testing.T) { } } // Staff can never create provider or release kinds. - for _, staff := range []string{"fleet.datumapis.com-device-operations-viewer", "fleet.datumapis.com-device-recovery-operator"} { + staffCreates := []string{group + "devicerecoveries.create", group + "devicecommissionings.create", group + "devicecommissioningplans.create", group + "devicecommissioningplanapprovals.create"} + for _, staff := range []string{"fleet.datumapis.com-device-operations-viewer", "fleet.datumapis.com-device-recovery-operator", "fleet.datumapis.com-device-commissioning-operator", "fleet.datumapis.com-device-commissioning-plan-author", "fleet.datumapis.com-device-commissioning-plan-approver"} { for _, permission := range roles[staff].Spec.Included { - if strings.HasSuffix(permission, ".create") && permission != group+"devicerecoveries.create" { + if strings.HasSuffix(permission, ".create") && !slices.Contains(staffCreates, permission) { t.Fatalf("%s may create %s", staff, permission) } } @@ -306,3 +323,15 @@ func TestPhases(t *testing.T) { } } } + +// TestPlanAuthorsCannotApprove keeps the two-person rule in the roles: no +// role both writes plans and approves them. +func TestPlanAuthorsCannotApprove(t *testing.T) { + for _, r := range decodeDir[role](t, filepath.Join(componentRoot, "roles")) { + writes := slices.Contains(r.Spec.Included, GroupVersion.Group+"/devicecommissioningplans.create") + approves := slices.Contains(r.Spec.Included, GroupVersion.Group+"/devicecommissioningplanapprovals.create") + if writes && approves { + t.Fatalf("%s both writes and approves plans", r.Metadata.Name) + } + } +} diff --git a/internal/api/operations/v1alpha1/types.go b/internal/api/operations/v1alpha1/types.go index 704d277f..a5aaa47d 100644 --- a/internal/api/operations/v1alpha1/types.go +++ b/internal/api/operations/v1alpha1/types.go @@ -462,7 +462,7 @@ type DeviceRecoveryList struct { func addKnown(s *runtime.Scheme) error { s.AddKnownTypes(GroupVersion, &DeviceCustody{}, &DeviceCustodyList{}, &DeviceInstallation{}, &DeviceInstallationList{}, &DeviceWipe{}, &DeviceWipeList{}, &DeviceRecovery{}, &DeviceRecoveryList{}) metav1.AddToGroupVersion(s, GroupVersion) - return nil + return addCommissioning(s) } var AddToScheme = addKnown diff --git a/internal/custody/commissioning.go b/internal/custody/commissioning.go new file mode 100644 index 00000000..e168edbc --- /dev/null +++ b/internal/custody/commissioning.go @@ -0,0 +1,389 @@ +package custody + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "reflect" + "slices" + "strings" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// CommissioningOverhead is the time a commissioning gets for inspection and +// boots on top of its plan's burn-in duration. +const CommissioningOverhead = time.Hour + +// commissioningEvidenceLimit bounds commissioning evidence. It is larger than +// the other kinds' limit because it records inspected hardware and firmware. +const commissioningEvidenceLimit = 16 << 10 + +// Commissioning refusal and result reasons. +const ( + ReasonPlanNotQualified = "PlanNotQualified" + ReasonPlanNotCurrent = "PlanNotCurrent" + ReasonPlanMismatch = "PlanMismatch" + ReasonDeviceNotActive = "DeviceNotActive" +) + +// Reasons a Device has no current plan. +const ( + ReasonNoCurrentPlan = "NoCurrentPlan" + ReasonPlanAmbiguous = "PlanAmbiguous" +) + +// PlanDigest is the digest an approval must name: the digest of the plan's +// whole spec. +func PlanDigest(plan *ops.DeviceCommissioningPlan) (string, error) { + return SpecDigest(plan.Spec) +} + +// ApprovalName is the only name an approval of the plan may have. It is +// derived from the plan's UID, so an approval of a plan never qualifies +// another plan recreated under the same name, and an operation or evidence +// that names the approval pins the plan incarnation without holding its UID. +func ApprovalName(plan *ops.DeviceCommissioningPlan) string { + sum := sha256.Sum256([]byte("fleet.datumapis.com/plan-approval/" + string(plan.UID))) + return plan.Name + "-" + hex.EncodeToString(sum[:])[:16] +} + +// PlanReferenceOf is the reference to the plan's current content. +func PlanReferenceOf(plan *ops.DeviceCommissioningPlan) (ops.PlanReference, error) { + digest, err := PlanDigest(plan) + if err != nil { + return ops.PlanReference{}, err + } + return ops.PlanReference{Name: plan.Name, Generation: plan.Generation, Digest: digest}, nil +} + +// Pins reports whether the reference names exactly this plan incarnation and +// its current content. +func Pins(reference ops.ApprovedPlanReference, plan *ops.DeviceCommissioningPlan) (bool, error) { + current, err := PlanReferenceOf(plan) + if err != nil { + return false, err + } + return reference.PlanReference == current && reference.Approval == ApprovalName(plan), nil +} + +// Qualified reports whether the plan is qualified: an approval with the +// plan's approval name names its content, and a different person created it. +func Qualified(ctx context.Context, reader client.Reader, plan *ops.DeviceCommissioningPlan) (bool, string, error) { + approval := &ops.DeviceCommissioningPlanApproval{} + if err := reader.Get(ctx, client.ObjectKey{Namespace: plan.Namespace, Name: ApprovalName(plan)}, approval); apierrors.IsNotFound(err) { + return false, "the plan has no approval", nil + } else if err != nil { + return false, "", err + } + return qualifies(plan, approval) +} + +func qualifies(plan *ops.DeviceCommissioningPlan, approval *ops.DeviceCommissioningPlanApproval) (bool, string, error) { + current, err := PlanReferenceOf(plan) + if err != nil { + return false, "", err + } + reference := approval.Spec.PlanRef + switch { + case !approval.DeletionTimestamp.IsZero() || !plan.DeletionTimestamp.IsZero(): + return false, "the plan or its approval is being deleted", nil + case approval.Name != ApprovalName(plan) || reference.Name != plan.Name: + return false, "the approval is for another plan", nil + case reference != current: + return false, "the approval is for different plan content", nil + case !distinct(plan.Spec.Creator, approval.Spec.Creator): + return false, "the plan's author approved it", nil + } + return true, "", nil +} + +// distinct reports whether two creators are different people. Principals +// are identified by username, as Kubernetes RBAC identifies them, so both +// usernames must be set and differ ignoring case. A client certificate +// carries no UID, so a UID counts only when both creators have one, and then +// the UIDs must differ too. +func distinct(author, approver ops.Creator) bool { + if author.Username == "" || approver.Username == "" || strings.EqualFold(author.Username, approver.Username) { + return false + } + return author.UID == "" || approver.UID == "" || author.UID != approver.UID +} + +// CurrentPlan returns the Device's current plan: the one qualified plan whose +// selector matches the Device and that no other qualified plan matching the +// Device supersedes. With no such plan, or more than one, it returns nil and +// the reason. An error means the plans could not be read. +func CurrentPlan(ctx context.Context, reader client.Reader, device *inventory.Device) (*ops.DeviceCommissioningPlan, string, error) { + var plans ops.DeviceCommissioningPlanList + if err := reader.List(ctx, &plans, client.InNamespace(device.Namespace)); err != nil { + return nil, "", err + } + var approvals ops.DeviceCommissioningPlanApprovalList + if err := reader.List(ctx, &approvals, client.InNamespace(device.Namespace)); err != nil { + return nil, "", err + } + return currentPlan(plans.Items, approvals.Items, device) +} + +func currentPlan(plans []ops.DeviceCommissioningPlan, approvals []ops.DeviceCommissioningPlanApproval, device *inventory.Device) (*ops.DeviceCommissioningPlan, string, error) { + approvalFor := map[string]*ops.DeviceCommissioningPlanApproval{} + for index := range approvals { + approvalFor[approvals[index].Name] = &approvals[index] + } + var qualified []*ops.DeviceCommissioningPlan + for index := range plans { + plan := &plans[index] + approval := approvalFor[ApprovalName(plan)] + if approval == nil { + continue + } + ok, _, err := qualifies(plan, approval) + if err != nil { + return nil, "", err + } + if ok { + qualified = append(qualified, plan) + } + } + // A supersession applies only to the Devices the superseding plan + // selects, so only plans that match the Device count. + var selecting []*ops.DeviceCommissioningPlan + for _, plan := range qualified { + selector, err := metav1.LabelSelectorAsSelector(&plan.Spec.DeviceSelector) + if err != nil || selector.Empty() { + continue + } + if selector.Matches(labels.Set(device.Labels)) { + selecting = append(selecting, plan) + } + } + superseded := map[string]bool{} + for _, plan := range selecting { + for _, name := range plan.Spec.Supersedes { + if name != plan.Name { + superseded[name] = true + } + } + } + var matching []*ops.DeviceCommissioningPlan + for _, plan := range selecting { + if !superseded[plan.Name] { + matching = append(matching, plan) + } + } + switch { + case len(matching) == 0 && len(selecting) > 0: + // Every plan that applies is superseded by another that applies: + // plans that supersede each other. + return nil, ReasonPlanAmbiguous, nil + case len(matching) == 0: + return nil, ReasonNoCurrentPlan, nil + case len(matching) == 1: + return matching[0], "", nil + } + return nil, ReasonPlanAmbiguous, nil +} + +// DeviceCommissioningKind is the registry entry for DeviceCommissioning. +func DeviceCommissioningKind() Kind { + return Kind{ + GVK: gv.WithKind("DeviceCommissioning"), + New: func() ops.Operation { return &ops.DeviceCommissioning{} }, + NewList: func() client.ObjectList { return &ops.DeviceCommissioningList{} }, + Items: func(list client.ObjectList) []ops.Operation { + return items(list.(*ops.DeviceCommissioningList).Items) + }, + Digest: func(operation ops.Operation) (string, error) { + return SpecDigest(operation.(*ops.DeviceCommissioning).Spec) + }, + Naming: GeneratedName, + Deadline: CommissioningOverhead, + DeadlineFor: func(operation ops.Operation) time.Duration { + return CommissioningOverhead + operation.(*ops.DeviceCommissioning).Spec.Plan.Content.BurnIn.Duration.Duration + }, + Effectful: true, + BootInterface: func(ops.Operation) string { return CommissioningBootInterface }, + Check: checkCommissioning, + SnapshotExtra: func(admission *Admission) map[string]string { + return map[string]string{SnapshotSerialNumber: admission.Device.Spec.Identity.Serial} + }, + // A held commissioning is settled by a later one that succeeds. No + // Retry is needed: staff create the settling operation directly. + Settles: []SettleRule{{Held: "DeviceCommissioning"}}, + KeepsLatest: true, + Reasons: []Reason{ + {Name: ReasonPlanNotQualified, RaisedBy: RaisedByCoordinator}, + {Name: ReasonPlanNotCurrent, RaisedBy: RaisedByCoordinator}, + {Name: ReasonPlanMismatch, RaisedBy: RaisedByBoth}, + {Name: ReasonDeviceNotActive, RaisedBy: RaisedByCoordinator}, + {Name: ReasonBootInterfaceUnknown, RaisedBy: RaisedByCoordinator}, + {Name: ReasonTargetUnsupported, RaisedBy: RaisedByWorker}, + {Name: ReasonInputsUnreadable, RaisedBy: RaisedByWorker}, + }, + Evidence: StrictEvidence(commissioningEvidenceLimit, validateCommissioningEvidence), + EvidenceRequired: true, + } +} + +// SnapshotSerialNumber is the snapshot field that carries the Device's +// recorded serial number, which the worker compares with the BMC's. +const SnapshotSerialNumber = "serialNumber" + +// CommissioningBootInterface is the Device interface a commissioning boots +// from. Burn-in boots over the network, so the snapshot records its MAC. +const CommissioningBootInterface = "primary" + +func checkCommissioning(ctx context.Context, admission *Admission) *Refusal { + commissioning := admission.Operation.(*ops.DeviceCommissioning) + if inventory.LifecycleOf(admission.Device) != inventory.DeviceActive { + return refuse(ReasonDeviceNotActive, "the Device is %s", inventory.LifecycleOf(admission.Device)) + } + if !hasBootInterface(admission.Device) { + return refuse(ReasonBootInterfaceUnknown, "the Device records no interface %q with a MAC address", CommissioningBootInterface) + } + if admission.Reader == nil { + return refuse(ReasonPlanNotQualified, "the plan could not be read") + } + input := commissioning.Spec.Plan + plan := &ops.DeviceCommissioningPlan{} + if err := admission.Reader.Get(ctx, client.ObjectKey{Namespace: commissioning.Namespace, Name: input.Name}, plan); err != nil { + return refuse(ReasonPlanNotQualified, "plan %s could not be read", input.Name) + } + if input.Approval != ApprovalName(plan) { + return refuse(ReasonPlanNotQualified, "the operation names an approval of another plan %s", input.Name) + } + ok, why, err := Qualified(ctx, admission.Reader, plan) + if err != nil { + return refuse(ReasonPlanNotQualified, "the plan's approval could not be read") + } + if !ok { + return refuse(ReasonPlanNotQualified, "%s", why) + } + pinned, err := Pins(input.ApprovedPlanReference, plan) + if err != nil || !pinned || !reflect.DeepEqual(plan.Spec.Content, input.Content) { + return refuse(ReasonPlanMismatch, "the operation's plan is not the approved plan") + } + current, reason, err := CurrentPlan(ctx, admission.Reader, admission.Device) + switch { + case current == nil && reason == "": + return refuse(ReasonPlanNotCurrent, "the Device's current plan could not be read: %v", err) + case current == nil: + return refuse(ReasonPlanNotCurrent, "the Device has no current plan (%s)", reason) + case current.UID != plan.UID: + return refuse(ReasonPlanNotCurrent, "the Device's current plan is %s", current.Name) + } + return nil +} + +// CommissioningRules are the DeviceCommissioning rows of the operations +// table: staff, from holder None, or from Service only to settle a +// commissioning hold. +func CommissioningRules() []Rule { + return []Rule{ + {Kind: "DeviceCommissioning", Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderNone}}, + {Kind: "DeviceCommissioning", Creator: CreatorStaff, Authority: AuthorityService, Holders: []ops.HolderType{ops.HolderService}, Hold: HoldSettlesRequired}, + } +} + +func hasBootInterface(device *inventory.Device) bool { + for _, iface := range device.Spec.Interfaces { + if iface.Name == CommissioningBootInterface && iface.MACAddress != "" { + return true + } + } + return false +} + +// validateCommissioningEvidence accepts only evidence that proves its +// verdict. A Passed result records the identity the BMC reported, matching +// the admission snapshot, hardware that meets the plan, every firmware +// baseline at its version, and a passed burn-in that ran the plan's +// duration. A Failed result names the phase and what failed. +func validateCommissioningEvidence(operation ops.Operation, evidence *ops.CommissioningEvidence) error { + plan := operation.(*ops.DeviceCommissioning).Spec.Plan + switch { + case evidence.Plan != plan.ApprovedPlanReference: + return errors.New("the evidence names another plan") + case len(evidence.Firmware) > 32 || len(evidence.Mismatches) > 32: + return errors.New("evidence records at most 32 firmware components and 32 mismatches") + case evidence.Hardware != nil && (len(evidence.Hardware.Disks) > 64 || len(evidence.Hardware.Interfaces) > 64): + return errors.New("evidence records at most 64 disks and 64 interfaces") + } + if err := validateSteps(evidence.Steps); err != nil { + return err + } + switch evidence.Result { + case ops.CommissioningFailed: + if evidence.FailedPhase != ops.PhaseInspect && evidence.FailedPhase != ops.PhaseFirmware && evidence.FailedPhase != ops.PhaseBurnIn { + return errors.New("a failed commissioning names the phase that failed") + } + if len(evidence.Mismatches) == 0 { + return errors.New("a failed commissioning says what failed") + } + return nil + case ops.CommissioningPassed: + default: + return errors.New("the evidence records no result") + } + if evidence.FailedPhase != "" || len(evidence.Mismatches) != 0 { + return errors.New("a passed commissioning records no failure") + } + if evidence.SerialNumber == "" || evidence.SystemUUID == "" || evidence.BMCPublicKeySHA256 == "" { + return errors.New("a passed commissioning records the serial number, system UUID and BMC key it read") + } + // Delivery waits until status records the admission, so the snapshot is + // there by the time a result arrives. + snapshot := operation.OperationStatus().Snapshot + if snapshot == nil { + return errors.New("the admission snapshot is not recorded, so the identity cannot be checked") + } + if !strings.EqualFold(evidence.SystemUUID, snapshot.SystemUUID) || evidence.BMCPublicKeySHA256 != snapshot.BMCPublicKeySHA256 || + !strings.EqualFold(strings.TrimSpace(evidence.SerialNumber), strings.TrimSpace(snapshot.Extra[SnapshotSerialNumber])) { + return errors.New("the identity the commissioning read differs from the admission snapshot") + } + hw, want := evidence.Hardware, plan.Content.Inspection + if hw == nil { + return errors.New("a passed commissioning records the inspected hardware") + } + if hw.CPU.Architecture != want.CPU.Architecture || hw.CPU.Cores != want.CPU.Cores { + return errors.New("the inspected CPU does not meet the plan") + } + memory, err := resource.ParseQuantity(hw.Memory) + planned, perr := resource.ParseQuantity(want.Memory.Capacity) + if err != nil || perr != nil || memory.Cmp(planned) != 0 { + return errors.New("the inspected memory does not meet the plan") + } + minimum, err := resource.ParseQuantity(want.Disks.MinCapacity) + if err != nil { + return errors.New("the plan's minimum disk capacity does not parse") + } + var disks int64 + for _, disk := range hw.Disks { + if capacity, err := resource.ParseQuantity(disk.Capacity); err == nil && capacity.Cmp(minimum) >= 0 { + disks++ + } + } + if disks < want.Disks.Count || int64(len(hw.Interfaces)) < want.Interfaces.Count { + return errors.New("the inspected disks or interfaces do not meet the plan") + } + for _, baseline := range plan.Content.Firmware { + if !slices.Contains(evidence.Firmware, baseline) { + return fmt.Errorf("firmware %s is not recorded at version %s", baseline.Component, baseline.Version) + } + } + burnIn := evidence.BurnIn + if burnIn == nil || burnIn.Result != ops.BurnInPassed || burnIn.CompletedAt.Sub(burnIn.StartedAt.Time) < plan.Content.BurnIn.Duration.Duration { + return errors.New("a passed commissioning records a passed burn-in that ran the plan's duration") + } + return nil +} diff --git a/internal/custody/commissioning_test.go b/internal/custody/commissioning_test.go new file mode 100644 index 00000000..88448408 --- /dev/null +++ b/internal/custody/commissioning_test.go @@ -0,0 +1,516 @@ +package custody + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + ops "go.datum.net/fleet/internal/api/operations/v1alpha1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +const ( + planAuthor = "plan-author@example.com" + planApprover = "plan-approver@example.com" + modelLabel = "fleet.datumapis.com/hardware-model" + burnInDigest = "sha256:1111111111111111111111111111111111111111111111111111111111111111" +) + +func planContent(burnIn time.Duration) ops.CommissioningPlanContent { + return ops.CommissioningPlanContent{ + Inspection: ops.CommissioningInspection{CPU: ops.InspectionCPU{Architecture: "amd64", Cores: 2}, Memory: ops.InspectionValue{Capacity: "2Gi"}, + Disks: ops.InspectionDisks{Count: 1, MinCapacity: "2Gi"}, Interfaces: ops.InspectionCount{Count: 1}}, + Firmware: []ops.FirmwareBaseline{{Component: "BMC", Version: "1.0.0"}}, + BurnIn: ops.CommissioningBurnIn{Image: ops.ImageInput{Name: "burn-in", Digest: burnInDigest}, Duration: metav1.Duration{Duration: burnIn}}, + } +} + +// plan creates a plan for one hardware model. +func (e *env) plan(name, model, author string, supersedes ...string) *ops.DeviceCommissioningPlan { + e.t.Helper() + plan := &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceCommissioningPlanSpec{ + Creator: ops.Creator{Username: author, UID: author + "-uid"}, + DeviceSelector: metav1.LabelSelector{MatchLabels: map[string]string{modelLabel: model}}, + Supersedes: supersedes, + Content: planContent(10 * time.Minute), + EvidenceLifetime: metav1.Duration{Duration: 24 * time.Hour}, + }} + e.create(plan) + return plan +} + +// approve qualifies the plan as the approver. +func (e *env) approve(plan *ops.DeviceCommissioningPlan, approver string) *ops.DeviceCommissioningPlanApproval { + e.t.Helper() + approval := &ops.DeviceCommissioningPlanApproval{ObjectMeta: metav1.ObjectMeta{Name: ApprovalName(plan), Namespace: "default"}, Spec: ops.DeviceCommissioningPlanApprovalSpec{ + Creator: ops.Creator{Username: approver, UID: approver + "-uid"}, + PlanRef: e.reference(plan), + }} + e.create(approval) + return approval +} + +// model labels the Device with its hardware model. +func (e *env) model(device *inventory.Device, model string) { + e.t.Helper() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + e.t.Fatal(err) + } + key := device.Status.Discovery.TLS.PublicKeySHA256 + device.Labels = map[string]string{modelLabel: model} + if err := e.admin.Update(e.ctx, device); err != nil { + e.t.Fatal(err) + } + e.discover(device, key, e.clock.Now()) +} + +// reference is the reference to the plan's current content. +func (e *env) reference(plan *ops.DeviceCommissioningPlan) ops.PlanReference { + e.t.Helper() + reference, err := PlanReferenceOf(plan) + if err != nil { + e.t.Fatal(err) + } + return reference +} + +func (e *env) commission(device *inventory.Device, plan *ops.DeviceCommissioningPlan, content ops.CommissioningPlanContent) *ops.DeviceCommissioning { + e.t.Helper() + return e.commissionUnder(device, ops.ApprovedPlanReference{PlanReference: e.reference(plan), Approval: ApprovalName(plan)}, content) +} + +// commissionUnder commissions the Device under an exact plan reference. +func (e *env) commissionUnder(device *inventory.Device, reference ops.ApprovedPlanReference, content ops.CommissioningPlanContent) *ops.DeviceCommissioning { + e.t.Helper() + operation := &ops.DeviceCommissioning{ObjectMeta: metav1.ObjectMeta{GenerateName: device.Name + "-commission-", Namespace: "default"}, Spec: ops.DeviceCommissioningSpec{ + OperationEnvelope: envelope(device, staffUser, service("intake")), + Plan: ops.CommissioningPlanInput{ApprovedPlanReference: reference, Content: content}, + }} + e.create(operation) + return operation +} + +// commissioningEvidence is evidence the kind accepts for the operation: the +// identity admission recorded, hardware that meets planContent, and a +// burn-in as long as the plan's. +func (e *env) commissioningEvidence(operation *ops.DeviceCommissioning, result ops.CommissioningResult) string { + e.t.Helper() + snapshot := e.status(operation).Snapshot + started := metav1.NewTime(e.clock.Now()) + evidence := ops.CommissioningEvidence{Plan: operation.Spec.Plan.ApprovedPlanReference, Result: result, + SerialNumber: snapshot.Extra[SnapshotSerialNumber], SystemUUID: snapshot.SystemUUID, BMCPublicKeySHA256: snapshot.BMCPublicKeySHA256, + Hardware: &ops.InspectedHardware{CPU: ops.InspectedCPU{Architecture: "amd64", Cores: 2}, Memory: "2Gi", + Disks: []ops.InspectedDisk{{Name: "disk-0", Capacity: "2Gi"}}, Interfaces: []ops.InspectedInterface{{Name: "nic-0"}}}, + Firmware: []ops.FirmwareBaseline{{Component: "BMC", Version: "1.0.0"}}, + BurnIn: &ops.BurnInEvidence{Result: ops.BurnInPassed, StartedAt: started, CompletedAt: metav1.NewTime(started.Add(operation.Spec.Plan.Content.BurnIn.Duration.Duration))}} + if result == ops.CommissioningFailed { + evidence.FailedPhase, evidence.Mismatches = ops.PhaseBurnIn, []string{"memory test failed"} + evidence.BurnIn.Result = ops.BurnInFailed + } + data, err := json.Marshal(evidence) + if err != nil { + e.t.Fatal(err) + } + return string(data) +} + +func TestCommissioning(t *testing.T) { + root := startEnv(t) + n := 0 + next := func(t *testing.T, model string) (*env, *inventory.Device) { + e := root.sub(t) + n++ + name := fmt.Sprintf("commission-%d", n) + device := e.verified(name, uid(700+n), fmt.Sprintf("%064x", 1000+n)) + e.model(device, model) + return e, device + } + + t.Run("the CRDs refuse malformed plans and approvals", func(t *testing.T) { + e := root.sub(t) + valid := func(name string) *ops.DeviceCommissioningPlan { + return &ops.DeviceCommissioningPlan{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceCommissioningPlanSpec{ + Creator: ops.Creator{Username: planAuthor, UID: "u"}, DeviceSelector: metav1.LabelSelector{MatchLabels: map[string]string{modelLabel: "crd"}}, + Content: planContent(time.Hour), EvidenceLifetime: metav1.Duration{Duration: time.Hour}}} + } + for name, mutate := range map[string]func(*ops.DeviceCommissioningPlan){ + "empty-selector": func(p *ops.DeviceCommissioningPlan) { p.Spec.DeviceSelector = metav1.LabelSelector{} }, + "short-burn-in": func(p *ops.DeviceCommissioningPlan) { p.Spec.Content.BurnIn.Duration.Duration = time.Second }, + "long-burn-in": func(p *ops.DeviceCommissioningPlan) { p.Spec.Content.BurnIn.Duration.Duration = 25 * time.Hour }, + "long-lifetime": func(p *ops.DeviceCommissioningPlan) { p.Spec.EvidenceLifetime.Duration = 366 * 24 * time.Hour }, + "bad-digest": func(p *ops.DeviceCommissioningPlan) { p.Spec.Content.BurnIn.Image.Digest = "latest" }, + } { + plan := valid("crd-" + name) + mutate(plan) + if err := e.admin.Create(e.ctx, plan); !apierrors.IsInvalid(err) { + t.Fatalf("%s: create = %v, want Invalid", name, err) + } + } + plan := valid("crd-valid") + e.create(plan) + plan.Spec.Supersedes = []string{"crd-old"} + if err := e.admin.Update(e.ctx, plan); !apierrors.IsInvalid(err) { + t.Fatalf("plan update = %v, want Invalid", err) + } + for _, name := range []string{"crd-valid", "crd-other-0123456789abcdef", "crd-valid-0123456789abcde"} { + approval := &ops.DeviceCommissioningPlanApproval{ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "default"}, Spec: ops.DeviceCommissioningPlanApprovalSpec{ + Creator: ops.Creator{Username: planApprover, UID: "u"}, PlanRef: ops.PlanReference{Name: "crd-valid", Generation: 1, Digest: burnInDigest}}} + if err := e.admin.Create(e.ctx, approval); !apierrors.IsInvalid(err) { + t.Fatalf("an approval named %s: %v, want Invalid", name, err) + } + } + long := valid(strings.Repeat("p", 237)) + if err := e.admin.Create(e.ctx, long); !apierrors.IsInvalid(err) { + t.Fatalf("a plan name with no room for its approval's suffix: %v, want Invalid", err) + } + }) + + t.Run("a plan its author approved is not qualified", func(t *testing.T) { + e, device := next(t, "self-approved") + plan := e.plan("self-approved-v1", "self-approved", planAuthor) + e.approve(plan, planAuthor) + operation := e.commission(device, plan, plan.Spec.Content) + before := e.custody(device.Name).Spec.Fence + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonPlanNotQualified) + if custody := e.custody(device.Name); custody.Spec.Fence != before || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("a refusal changed custody: %+v", custody.Spec) + } + }) + + t.Run("an approver with the author's UID or another case of the username is the author", func(t *testing.T) { + for _, approver := range []ops.Creator{{Username: "other-name@example.com", UID: planAuthor + "-uid"}, {Username: strings.ToUpper(planAuthor), UID: "different-uid"}} { + e, device := next(t, "same-person") + plan := e.plan(fmt.Sprintf("same-person-%d", n), "same-person", planAuthor) + e.create(&ops.DeviceCommissioningPlanApproval{ObjectMeta: metav1.ObjectMeta{Name: ApprovalName(plan), Namespace: "default"}, Spec: ops.DeviceCommissioningPlanApprovalSpec{ + Creator: approver, PlanRef: e.reference(plan)}}) + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonPlanNotQualified) + // Remove the plan so the next iteration's Device has one current plan. + if err := e.admin.Delete(e.ctx, plan); err != nil { + t.Fatal(err) + } + } + }) + + t.Run("an unapproved plan and a plan approved under another digest are not qualified", func(t *testing.T) { + e, device := next(t, "unapproved") + plan := e.plan("unapproved-v1", "unapproved", planAuthor) + e.requirePhase(func() ops.Operation { + o := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + return o + }(), ops.PhaseFailed, ReasonPlanNotQualified) + approval := &ops.DeviceCommissioningPlanApproval{ObjectMeta: metav1.ObjectMeta{Name: ApprovalName(plan), Namespace: "default"}, Spec: ops.DeviceCommissioningPlanApprovalSpec{ + Creator: ops.Creator{Username: planApprover, UID: "x"}, PlanRef: ops.PlanReference{Name: plan.Name, Generation: plan.Generation, Digest: burnInDigest}}} + e.create(approval) + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonPlanNotQualified) + }) + + t.Run("a plan recreated under the same name inherits no approval", func(t *testing.T) { + e, device := next(t, "recreated") + plan := e.plan("recreated-v1", "recreated", planAuthor) + e.approve(plan, planApprover) + old := ops.ApprovedPlanReference{PlanReference: e.reference(plan), Approval: ApprovalName(plan)} + if err := e.admin.Delete(e.ctx, plan); err != nil { + t.Fatal(err) + } + again := e.plan("recreated-v1", "recreated", planAuthor) + if again.UID == plan.UID || e.reference(again) != old.PlanReference { + t.Fatalf("the recreated plan must differ only in its incarnation: %s %+v", again.UID, e.reference(again)) + } + if ApprovalName(again) == old.Approval { + t.Fatal("the recreated plan has the old plan's approval name") + } + // The old approval still exists, and qualifies neither the recreated + // plan nor a commissioning that names it. + if ok, _, err := Qualified(e.ctx, e.admin, again); err != nil || ok { + t.Fatalf("the recreated plan is qualified by the old approval: %v %v", ok, err) + } + for _, reference := range []ops.ApprovedPlanReference{old, {PlanReference: old.PlanReference, Approval: ApprovalName(again)}} { + operation := e.commissionUnder(device, reference, again.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonPlanNotQualified) + } + // Once the recreated plan is approved, a commissioning that names the + // old incarnation's approval is still refused, and only one naming the + // new approval pins the recreated plan. + e.approve(again, planApprover) + if ok, why, err := Qualified(e.ctx, e.admin, again); err != nil || !ok { + t.Fatalf("the re-approved plan is not qualified: %s %v", why, err) + } + if pinned, err := Pins(old, again); err != nil || pinned { + t.Fatalf("the old approval pins the recreated plan: %v %v", pinned, err) + } + if pinned, err := Pins(ops.ApprovedPlanReference{PlanReference: old.PlanReference, Approval: ApprovalName(again)}, again); err != nil || !pinned { + t.Fatalf("the new approval does not pin the recreated plan: %v %v", pinned, err) + } + before := e.custody(device.Name).Spec.Fence + operation := e.commissionUnder(device, old, again.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonPlanNotQualified) + if fence := e.custody(device.Name).Spec.Fence; fence != before { + t.Fatalf("a refused commissioning raised the fence from %d to %d", before, fence) + } + }) + + t.Run("copied content that differs from the plan is refused", func(t *testing.T) { + e, device := next(t, "mismatch") + plan := e.plan("mismatch-v1", "mismatch", planAuthor) + e.approve(plan, planApprover) + altered := planContent(time.Minute) + operation := e.commission(device, plan, altered) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonPlanMismatch) + }) + + t.Run("an inactive Device is refused", func(t *testing.T) { + e, device := next(t, "inactive") + plan := e.plan("inactive-v1", "inactive", planAuthor) + e.approve(plan, planApprover) + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + t.Fatal(err) + } + device.Spec.Lifecycle = inventory.DeviceDecommissioning + if err := e.admin.Update(e.ctx, device); err != nil { + t.Fatal(err) + } + e.discover(device, e.custodyKey(device), e.clock.Now()) + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonDeviceNotActive) + }) + + t.Run("a superseded plan is not current for the Devices the new plan selects", func(t *testing.T) { + e, device := next(t, "super") + other := root.sub(t) + n++ + bystander := other.verified("commission-bystander", uid(800), fmt.Sprintf("%064x", 800)) + other.model(bystander, "super-other") + old := e.plan("super-v1", "super", planAuthor) + e.approve(old, planApprover) + // v1 also selects the bystander's model through a broad selector. + broad := e.plan("broad-v1", "super-other", planAuthor) + e.approve(broad, planApprover) + replacement := e.plan("super-v2", "super", planAuthor, "super-v1", "broad-v1") + e.approve(replacement, planApprover) + operation := e.commission(device, old, old.Spec.Content) + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseFailed, ReasonPlanNotCurrent) + // The supersession reaches only Devices super-v2 selects. + current, reason, err := CurrentPlan(e.ctx, e.admin, bystander) + if err != nil || current == nil || current.Name != "broad-v1" { + t.Fatalf("bystander's current plan = %v, %s, %v (labels %v)", current, reason, err, bystander.Labels) + } + // Revoking super-v2 makes super-v1 current again. + if err := e.admin.Delete(e.ctx, &ops.DeviceCommissioningPlanApproval{ObjectMeta: metav1.ObjectMeta{Name: ApprovalName(replacement), Namespace: "default"}}); err != nil { + t.Fatal(err) + } + current, _, err = CurrentPlan(e.ctx, e.admin, device) + if err != nil || current == nil || current.Name != "super-v1" { + t.Fatalf("after revocation the current plan = %v, %v", current, err) + } + }) + + t.Run("two plans that apply leave no current plan", func(t *testing.T) { + e, device := next(t, "ambiguous") + for _, name := range []string{"ambiguous-a", "ambiguous-b"} { + e.approve(e.plan(name, "ambiguous", planAuthor), planApprover) + } + current, reason, err := CurrentPlan(e.ctx, e.admin, device) + if current != nil || reason != ReasonPlanAmbiguous || err != nil { + t.Fatalf("current = %v, reason %s", current, reason) + } + // Mutual supersession is ambiguous too, not a cycle that picks one. + e.approve(e.plan("cycle-a", "cycle", planAuthor, "cycle-b"), planApprover) + e.approve(e.plan("cycle-b", "cycle", planAuthor, "cycle-a"), planApprover) + e.model(device, "cycle") + if current, reason, err := CurrentPlan(e.ctx, e.admin, device); current != nil || reason != ReasonPlanAmbiguous || err != nil { + t.Fatalf("a supersession cycle gave %v, %s", current, reason) + } + }) + + t.Run("a proven verdict succeeds and returns the Device to None", func(t *testing.T) { + for _, result := range []ops.CommissioningResult{ops.CommissioningPassed, ops.CommissioningFailed} { + model := "verdict-" + strings.ToLower(string(result)) + e, device := next(t, model) + plan := e.plan(model+"-v1", model, planAuthor) + e.approve(plan, planApprover) + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + status := e.requirePhase(operation, ops.PhaseAdmitted, "") + if got := status.Deadline.Sub(status.AdmittedAt.Time); got != CommissioningOverhead+10*time.Minute { + t.Fatalf("deadline is %s after admission", got) + } + if holder := e.custody(device.Name).Spec.Holder.Type; holder != ops.HolderService { + t.Fatalf("holder = %s, want Service", holder) + } + if err := e.result(device.Name, ops.PhaseSucceeded, e.commissioningEvidence(operation, result)); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(operation, ops.PhaseSucceeded, "") + if custody := e.custody(device.Name); custody.Spec.Holder.Type != ops.HolderNone || custody.Spec.RecoveryHold != nil { + t.Fatalf("custody after a %s verdict: %+v", result, custody.Spec) + } + } + }) + + t.Run("evidence that does not prove its verdict proves nothing", func(t *testing.T) { + for name, mutate := range map[string]func(*ops.CommissioningEvidence){ + "no hardware": func(v *ops.CommissioningEvidence) { v.Hardware = nil }, + "no serial": func(v *ops.CommissioningEvidence) { v.SerialNumber = "" }, + "another serial": func(v *ops.CommissioningEvidence) { v.SerialNumber = "serial-other" }, + "another key": func(v *ops.CommissioningEvidence) { v.BMCPublicKeySHA256 = strings.Repeat("0", 64) }, + "too few cores": func(v *ops.CommissioningEvidence) { v.Hardware.CPU.Cores = 1 }, + "other memory": func(v *ops.CommissioningEvidence) { v.Hardware.Memory = "4Gi" }, + "small disk": func(v *ops.CommissioningEvidence) { v.Hardware.Disks[0].Capacity = "1Gi" }, + "missing firmware": func(v *ops.CommissioningEvidence) { v.Firmware = nil }, + "short burn-in": func(v *ops.CommissioningEvidence) { v.BurnIn.CompletedAt = v.BurnIn.StartedAt }, + "failed burn-in passed": func(v *ops.CommissioningEvidence) { v.BurnIn.Result = ops.BurnInFailed }, + "another plan": func(v *ops.CommissioningEvidence) { v.Plan.Digest = burnInDigest }, + "failed without phase": func(v *ops.CommissioningEvidence) { v.Result = ops.CommissioningFailed; v.Mismatches = []string{"x"} }, + "failed without mismatch": func(v *ops.CommissioningEvidence) { + v.Result, v.FailedPhase = ops.CommissioningFailed, ops.PhaseInspect + }, + } { + model := "proof-" + strings.ReplaceAll(name, " ", "-") + e, device := next(t, model) + plan := e.plan(model+"-v1", model, planAuthor) + e.approve(plan, planApprover) + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + var evidence ops.CommissioningEvidence + if err := json.Unmarshal([]byte(e.commissioningEvidence(operation, ops.CommissioningPassed)), &evidence); err != nil { + t.Fatal(err) + } + mutate(&evidence) + data, _ := json.Marshal(evidence) + if err := e.result(device.Name, ops.PhaseSucceeded, string(data)); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + if status := e.status(operation); status.Phase != ops.PhaseOutcomeUnknown || status.Reason != ReasonInvalidEvidence { + t.Fatalf("%s: %s %s (%s)", name, status.Phase, status.Reason, status.Message) + } + } + }) + + t.Run("a later commissioning settles a commissioning hold", func(t *testing.T) { + e, device := next(t, "hold") + plan := e.plan("hold-v1", "hold", planAuthor) + e.approve(plan, planApprover) + first := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.clock.Advance(CommissioningOverhead + 10*time.Minute + DefaultSkewMargin + time.Second) + e.discover(device, e.custodyKey(device), e.clock.Now()) + e.settle(device.Name) + e.requirePhase(first, ops.PhaseOutcomeUnknown, ReasonDeadlineExceeded) + if custody := e.custody(device.Name); custody.Spec.RecoveryHold == nil || custody.Spec.Holder.Type != ops.HolderService { + t.Fatalf("custody after the deadline: %+v", custody.Spec) + } + // Staff operations expire five minutes after they are created, by + // the API server's clock, so bring the coordinator's clock back. + e.clock.Advance(-(CommissioningOverhead + 10*time.Minute + DefaultSkewMargin + time.Second)) + e.discover(device, e.custodyKey(device), e.clock.Now()) + second := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.requirePhase(second, ops.PhaseAdmitted, "") + if err := e.result(device.Name, ops.PhaseSucceeded, e.commissioningEvidence(second, ops.CommissioningPassed)); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + if custody := e.custody(device.Name); custody.Spec.RecoveryHold != nil || custody.Spec.Holder.Type != ops.HolderNone { + t.Fatalf("custody after the settling commissioning: %+v", custody.Spec) + } + }) + + t.Run("retention keeps each Device's latest succeeded commissioning", func(t *testing.T) { + e, device := next(t, "retain") + plan := e.plan("retain-v1", "retain", planAuthor) + e.approve(plan, planApprover) + var runs []*ops.DeviceCommissioning + for range 2 { + operation := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + if err := e.result(device.Name, ops.PhaseSucceeded, e.commissioningEvidence(operation, ops.CommissioningPassed)); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + runs = append(runs, operation) + e.clock.Advance(time.Minute) + } + e.clock.Advance(DefaultRetention + time.Hour) + if _, err := e.coord.SweepRetention(e.ctx); err != nil { + t.Fatal(err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(runs[0]), runs[0]); !apierrors.IsNotFound(err) { + t.Fatalf("the older commissioning was kept: %v", err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(runs[1]), runs[1]); err != nil { + t.Fatalf("the latest commissioning was deleted: %v", err) + } + // Once the Device is gone, its latest is evidence nobody reads. + if err := e.admin.Delete(e.ctx, device); err != nil { + t.Fatal(err) + } + if _, err := e.coord.SweepRetention(e.ctx); err != nil { + t.Fatal(err) + } + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(runs[1]), runs[1]); !apierrors.IsNotFound(err) { + t.Fatalf("a deleted Device's commissioning was kept: %v", err) + } + }) + + t.Run("the latest success is per Device incarnation", func(t *testing.T) { + older := &ops.DeviceCommissioning{ObjectMeta: metav1.ObjectMeta{Name: "a", Labels: map[string]string{ops.LabelDeviceUID: "first"}}, Spec: ops.DeviceCommissioningSpec{OperationEnvelope: ops.OperationEnvelope{DeviceRef: ops.DeviceReference{Name: "server"}}}, + Status: ops.OperationStatus{Phase: ops.PhaseSucceeded, FinishedAt: &metav1.Time{Time: time.Now()}}} + newer := older.DeepCopyObject().(*ops.DeviceCommissioning) + newer.Name, newer.Labels[ops.LabelDeviceUID] = "b", "second" + newer.Status.FinishedAt = &metav1.Time{Time: time.Now().Add(-time.Hour)} + latest := LatestSucceeded([]ops.Operation{older, newer}) + if len(latest) != 2 || latest[DeviceIncarnation{Name: "server", UID: "second"}].GetName() != "b" { + t.Fatalf("latest = %v", latest) + } + }) +} + +// custodyKey is the BMC key discovery last recorded for the Device. +func (e *env) custodyKey(device *inventory.Device) string { + e.t.Helper() + if err := e.admin.Get(e.ctx, client.ObjectKeyFromObject(device), device); err != nil { + e.t.Fatal(err) + } + return device.Status.Discovery.TLS.PublicKeySHA256 +} + +// An author and approver are told apart by username, as Kubernetes RBAC +// identifies principals. A UID counts only when both creators carry one. +func TestPlanApproverIsAnotherPrincipal(t *testing.T) { + for _, tc := range []struct { + name string + author, approver ops.Creator + want bool + }{ + {"different usernames and UIDs", ops.Creator{Username: "author@example.com", UID: "a"}, ops.Creator{Username: "approver@example.com", UID: "b"}, true}, + {"different usernames without UIDs", ops.Creator{Username: "author"}, ops.Creator{Username: "approver"}, true}, + {"different usernames, one UID", ops.Creator{Username: "author", UID: "a"}, ops.Creator{Username: "approver"}, true}, + {"the same username without UIDs", ops.Creator{Username: "author"}, ops.Creator{Username: "author"}, false}, + {"the same username in another case", ops.Creator{Username: "author"}, ops.Creator{Username: "AUTHOR", UID: "b"}, false}, + {"the same UID under another username", ops.Creator{Username: "author", UID: "a"}, ops.Creator{Username: "approver", UID: "a"}, false}, + {"an approver without a username", ops.Creator{Username: "author"}, ops.Creator{UID: "b"}, false}, + {"an author without a username", ops.Creator{UID: "a"}, ops.Creator{Username: "approver"}, false}, + } { + if got := distinct(tc.author, tc.approver); got != tc.want { + t.Errorf("%s: distinct = %v, want %v", tc.name, got, tc.want) + } + } +} diff --git a/internal/custody/coordinator.go b/internal/custody/coordinator.go index 35d2f548..5196014b 100644 --- a/internal/custody/coordinator.go +++ b/internal/custody/coordinator.go @@ -941,12 +941,16 @@ func (c *Coordinator) admitOne(ctx context.Context, custody *ops.DeviceCustody, return Outcome{}, err } spec.Fence = max(spec.Fence, seen) + 1 + deadline := kind.Deadline + if kind.DeadlineFor != nil { + deadline = kind.DeadlineFor(operation) + } active := &ops.ActiveOperation{ OperationReference: ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName()}, Fence: spec.Fence, Phase: ops.PhaseAdmitted, AdmittedAt: metav1.NewTime(now), - Deadline: metav1.NewTime(now.Add(kind.Deadline)), + Deadline: metav1.NewTime(now.Add(deadline)), InputDigest: digest, Snapshot: snapshot(kind, operation, device, d.extra), Creator: operation.Envelope().Creator, diff --git a/internal/custody/coordinator_roles_test.go b/internal/custody/coordinator_roles_test.go new file mode 100644 index 00000000..df577d99 --- /dev/null +++ b/internal/custody/coordinator_roles_test.go @@ -0,0 +1,78 @@ +package custody + +import ( + "bytes" + "io" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apimachinery/pkg/util/yaml" +) + +// plural is the resource name of a kind, as its CRD declares it. +func plural(kind string) string { + name := strings.ToLower(kind) + if strings.HasSuffix(name, "y") { + return strings.TrimSuffix(name, "y") + "ies" + } + return name + "s" +} + +// TestEveryCoordinatorRoleCoversEveryKind fails when a registered kind is +// missing from the coordinator role of a mode. The coordinator lists every +// registered kind, so a missing grant stops every admission in that mode. +func TestEveryCoordinatorRoleCoversEveryKind(t *testing.T) { + registry, err := DefaultRegistry() + if err != nil { + t.Fatal(err) + } + var plurals []string + for _, kind := range registry.Kinds() { + plurals = append(plurals, plural(kind.GVK.Kind)) + } + plurals = append(plurals, "devicecommissioningplans", "devicecommissioningplanapprovals") + + data, err := os.ReadFile(filepath.Join("..", "..", "config", "standalone", "rbac.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + granted := map[string]bool{} + for { + var role rbacv1.Role + if err := decoder.Decode(&role); err == io.EOF { + break + } else if err != nil { + t.Fatal(err) + } + if role.Kind != "Role" || role.Name != "fleet-custody-coordinator" { + continue + } + for _, rule := range role.Rules { + if slices.Contains(rule.Verbs, "list") { + for _, resource := range rule.Resources { + granted[resource] = true + } + } + } + } + milo, err := os.ReadFile(filepath.Join("..", "..", "hack", "multiplane", "milo.py")) + if err != nil { + t.Fatal(err) + } + coordinator := string(milo) + coordinator = coordinator[strings.Index(coordinator, "'coordinator':["):] + coordinator = coordinator[:strings.Index(coordinator, "'release':")] + for _, resource := range plurals { + if !granted[resource] { + t.Errorf("the standalone coordinator role cannot list %s", resource) + } + if !strings.Contains(coordinator, "'"+resource+"'") { + t.Errorf("the multi-plane coordinator role cannot list %s", resource) + } + } +} diff --git a/internal/custody/creatorwebhook/handler.go b/internal/custody/creatorwebhook/handler.go index 21f2bcbf..4164c418 100644 --- a/internal/custody/creatorwebhook/handler.go +++ b/internal/custody/creatorwebhook/handler.go @@ -27,7 +27,7 @@ import ( const Path = "/validate-operation-creator" // Resources are the operation plurals whose creator the webhook governs. -var Resources = []string{"deviceinstallations", "devicewipes", "devicerecoveries"} +var Resources = []string{"deviceinstallations", "devicewipes", "devicerecoveries", "devicecommissionings", "devicecommissioningplans", "devicecommissioningplanapprovals"} // Handler admits creates whose creator is the caller and updates that leave // the creator unchanged. diff --git a/internal/custody/creatorwebhook/packaged_test.go b/internal/custody/creatorwebhook/packaged_test.go new file mode 100644 index 00000000..39cc4634 --- /dev/null +++ b/internal/custody/creatorwebhook/packaged_test.go @@ -0,0 +1,70 @@ +package creatorwebhook + +import ( + "bytes" + "os" + "path/filepath" + "slices" + "testing" + + admissionregistrationv1 "k8s.io/api/admissionregistration/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/yaml" +) + +// TestPackagedResourcesMatch keeps the webhook's resource list, the packaged +// webhook registration and the standalone creator policy in step. A kind +// added to one and not the others would leave its creator unchecked in that +// mode. +func TestPackagedResourcesMatch(t *testing.T) { + root := filepath.Join("..", "..", "..") + want := slices.Sorted(slices.Values(Resources)) + + data, err := os.ReadFile(filepath.Join(root, "config", "components", "device-operations", "webhook.yaml")) + if err != nil { + t.Fatal(err) + } + webhooks := &admissionregistrationv1.ValidatingWebhookConfiguration{} + if err := yaml.UnmarshalStrict(data, webhooks); err != nil { + t.Fatal(err) + } + var registered []string + for _, webhook := range webhooks.Webhooks { + for _, rule := range webhook.Rules { + registered = append(registered, rule.Resources...) + } + } + if got := slices.Sorted(slices.Values(registered)); !slices.Equal(got, want) { + t.Fatalf("webhook.yaml registers %v, the webhook governs %v", got, want) + } + + data, err = os.ReadFile(filepath.Join(root, "config", "standalone", "site.yaml")) + if err != nil { + t.Fatal(err) + } + var policies int + for _, document := range bytes.Split(data, []byte("\n---\n")) { + var meta metav1.TypeMeta + if err := yaml.Unmarshal(document, &meta); err != nil { + t.Fatal(err) + } + if meta.Kind != "ValidatingAdmissionPolicy" { + continue + } + policy := &admissionregistrationv1.ValidatingAdmissionPolicy{} + if err := yaml.UnmarshalStrict(document, policy); err != nil { + t.Fatal(err) + } + policies++ + var matched []string + for _, rule := range policy.Spec.MatchConstraints.ResourceRules { + matched = append(matched, rule.Resources...) + } + if got := slices.Sorted(slices.Values(matched)); !slices.Equal(got, want) { + t.Fatalf("the standalone creator policy matches %v, the webhook governs %v", got, want) + } + } + if policies != 1 { + t.Fatalf("the standalone site must package one creator policy, found %d", policies) + } +} diff --git a/internal/custody/kinds.go b/internal/custody/kinds.go index 19ab1a19..36aa7aa0 100644 --- a/internal/custody/kinds.go +++ b/internal/custody/kinds.go @@ -328,12 +328,12 @@ func applyRecovery(ctx context.Context, apply *ApplyContext) (*ops.DeviceCustody // for them. func DefaultRegistry() (*Registry, error) { registry := NewRegistry() - for _, kind := range []Kind{DeviceInstallationKind(), DeviceWipeKind(), DeviceRecoveryKind()} { + for _, kind := range []Kind{DeviceInstallationKind(), DeviceWipeKind(), DeviceRecoveryKind(), DeviceCommissioningKind()} { if err := registry.Register(kind); err != nil { return nil, err } } - for _, rule := range DefaultRules() { + for _, rule := range append(DefaultRules(), CommissioningRules()...) { if err := registry.AddRule(rule); err != nil { return nil, err } diff --git a/internal/custody/registry.go b/internal/custody/registry.go index f45a9f96..944db7f8 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -59,6 +59,14 @@ type Kind struct { Name func(ops.Operation) string // Deadline is how long the site may work on an admitted operation. Deadline time.Duration + // DeadlineFor, when set, replaces Deadline with one derived from the + // operation's own inputs, such as a commissioning plan's burn-in + // duration. + DeadlineFor func(ops.Operation) time.Duration + // KeepsLatest means retention keeps each Device's latest succeeded + // operation of this kind, because it is evidence another reader needs, + // such as the capacity projector reading the latest commissioning. + KeepsLatest bool // Effectful kinds can reach the server. A non-effectful kind, such as // DeviceRecovery, that passes its deadline ends Failed: nothing it does // can leave the server in an unknown state. diff --git a/internal/custody/retention.go b/internal/custody/retention.go index 0300132b..61b24a7f 100644 --- a/internal/custody/retention.go +++ b/internal/custody/retention.go @@ -13,7 +13,8 @@ import ( // Config.Retention ago. An operation custody still names, as active or as // its recovery hold, is kept, and so is a succeeded retirement until // inventory retires the Device. Platform audit records keep the history after -// that. +// that. A kind that KeepsLatest keeps each existing Device's latest succeeded +// operation. func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { cfg := c.config() cutoff := c.now().Add(-cfg.Retention) @@ -38,9 +39,23 @@ func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { if err := c.Client.List(ctx, list, client.InNamespace(cfg.Namespace)); err != nil { return deleted, err } - for _, operation := range kind.Items(list) { + operations := kind.Items(list) + latest := map[string]bool{} + if kind.KeepsLatest { + // Only the current incarnation's latest is evidence anyone reads. + for reference, operation := range LatestSucceeded(operations) { + device, err := c.device(ctx, reference.Name) + if err != nil { + return deleted, err + } + if device != nil && string(device.UID) == reference.UID { + latest[operation.GetName()] = true + } + } + } + for _, operation := range operations { status := operation.OperationStatus() - if !status.Phase.Ended() || status.FinishedAt == nil || !status.FinishedAt.Time.Before(cutoff) || referenced[ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName()}] { + if !status.Phase.Ended() || status.FinishedAt == nil || !status.FinishedAt.Time.Before(cutoff) || referenced[ops.OperationReference{Kind: kind.GVK.Kind, Name: operation.GetName()}] || latest[operation.GetName()] { continue } // A succeeded retirement is the only record of it until @@ -63,3 +78,40 @@ func (c *Coordinator) SweepRetention(ctx context.Context) (int, error) { } return deleted, nil } + +// DeviceIncarnation is one Device incarnation: its name and the UID the +// operation's ops.LabelDeviceUID label records. +type DeviceIncarnation struct { + Name string + UID string +} + +// LatestSucceeded returns, for each Device incarnation, the succeeded +// operation that finished last. Ties break on the higher fence, then the +// name, so every reader picks the same one. +func LatestSucceeded(operations []ops.Operation) map[DeviceIncarnation]ops.Operation { + out := map[DeviceIncarnation]ops.Operation{} + for _, operation := range operations { + status := operation.OperationStatus() + if status.Phase != ops.PhaseSucceeded || status.FinishedAt == nil { + continue + } + device := DeviceIncarnation{Name: operation.Envelope().DeviceRef.Name, UID: operation.GetLabels()[ops.LabelDeviceUID]} + current, ok := out[device] + if !ok || later(operation, current) { + out[device] = operation + } + } + return out +} + +func later(a, b ops.Operation) bool { + at, bt := a.OperationStatus().FinishedAt.Time, b.OperationStatus().FinishedAt.Time + switch { + case !at.Equal(bt): + return at.After(bt) + case a.OperationStatus().Fence != b.OperationStatus().Fence: + return a.OperationStatus().Fence > b.OperationStatus().Fence + } + return a.GetName() > b.GetName() +} From f7c5d21a5b1fe58f8fb0461220397036821614d2 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 11:28:29 -0600 Subject: [PATCH 2/3] fix(custody): Settle holds only on a pass A Failed commissioning verdict skipped the identity check, so a verdict about another server could end Succeeded and clear a commissioning hold left by a run cut off mid-flash or mid-burn-in. Every result now records the serial number, system UUID and BMC key the admission snapshot holds. A kind may also decide from a success's evidence whether it settles the hold it was admitted to settle; a commissioning settles one only with a Passed verdict. Live results and rebuild apply the same rule. Co-Authored-By: Claude Opus 5.5 --- docs/development/device-custody.md | 40 +++++++++++------ internal/custody/commissioning.go | 54 ++++++++++++++--------- internal/custody/commissioning_test.go | 59 ++++++++++++++++++++++++++ internal/custody/rebuild.go | 13 ++++-- internal/custody/registry.go | 11 +++++ internal/custody/results.go | 2 +- 6 files changed, 141 insertions(+), 38 deletions(-) diff --git a/docs/development/device-custody.md b/docs/development/device-custody.md index 6a105b56..e4783c87 100644 --- a/docs/development/device-custody.md +++ b/docs/development/device-custody.md @@ -583,7 +583,9 @@ Each value is configurable. - A result whose evidence does not match the kind's schema proves nothing, and ends `OutcomeUnknown` with `InvalidEvidence`. - A settling operation records the hold it settles. If it succeeds, the hold - is cleared. If it also ends unknown, its hold replaces the old one. + is cleared, unless its kind settles only on some results: a commissioning + settles only with a `Passed` verdict. If it also ends unknown, its hold + replaces the old one. - A `DeviceRecovery` is admitted like any operation and raises the fence. The coordinator applies it only after every site serving the Device confirms that every worker below that fence stopped. If no site @@ -626,8 +628,8 @@ Each value is configurable. it, so one without an admission record was never admitted and is not held. - An operation that ended `OutcomeUnknown` is held again unless something later settled it: a succeeded operation with a higher fence whose kind - settles the held kind, or a succeeded recovery that cleared that exact - hold. + settles the held kind with the evidence it recorded, or a succeeded + recovery that cleared that exact hold. - If several operations would be held, the one with the highest fence is held and custody stays `Unverified`, so a `Resolve` must decide and the hold is never dropped. @@ -858,8 +860,15 @@ which a test pins, because the coordinator lists every registered kind. differ ignoring case. A client certificate carries no UID, so UIDs are compared only when both creators have one, and then they must differ. A plan re-created under the same name has another approval name, so it inherits no approval, and no commissioning - under the old plan is admitted under it. No role both writes and approves - plans, which a test pins. + under the old plan is admitted under it. +- **Two people in IAM.** The username comparison is only the last check. The + rule it backs is an IAM rule: the plan author and plan approver roles are + never bound to the same principal, nor to groups that share a member, and + no role grants both. Fleet does not own IAM bindings, so it cannot refuse + such a binding when it is made; the role descriptions state the rule for + whoever binds them. A test pins what Fleet packages: no role, counting the + roles it inherits, both writes and approves plans, and no packaged + PolicyBinding grants one subject both. - **Residual window.** Admission reads the plan and its approval before the custody update, which re-checks only the Device. A plan revoked in between can still be admitted once. No capacity projector reads commissioning yet, @@ -881,17 +890,22 @@ which a test pins, because the coordinator lists every registered kind. content, generation or digest that differs from the plan (`PlanMismatch`), and a plan that is not the Device's current plan (`PlanNotCurrent`). - **Results.** A proven verdict ends `Succeeded` with result `Passed` or - `Failed` in its evidence. A `Passed` result must record the serial number, - system UUID and BMC key the admission snapshot holds, hardware that meets - the plan, every firmware baseline at its version, and a passed burn-in at - least as long as the plan's. A `Failed` result must name the phase and what - failed. Other evidence proves nothing, and the operation ends - `OutcomeUnknown`. Evidence is limited to 16 KiB. + `Failed` in its evidence. Every result must record the serial number, + system UUID and BMC key the admission snapshot holds, so no verdict is + about another server. A `Passed` result must also record hardware that + meets the plan, every firmware baseline at its version, and a passed + burn-in at least as long as the plan's. A `Failed` result must name the + phase and what failed. Other evidence proves nothing, and the operation + ends `OutcomeUnknown`. Evidence is limited to 16 KiB. - **Retention.** Each existing Device incarnation's latest succeeded commissioning is kept past retention. Once the Device is deleted or re-created, the old incarnation's record ages out normally. -- **Holds.** A later commissioning that ends `Succeeded` settles a - commissioning hold. It needs no `Retry`. +- **Holds.** Only a later commissioning that ends `Succeeded` with a + `Passed` result settles a commissioning hold. A `Failed` verdict proves the + server unfit, not that an earlier run cut off mid-flash or mid-burn-in + left it as the plan says, so the hold and the `Service` holder stay. + Rebuild applies the same rule to the evidence the operation recorded. It + needs no `Retry`. The boot interface is fixed at `primary`, like the allocator's in every mode. diff --git a/internal/custody/commissioning.go b/internal/custody/commissioning.go index e168edbc..11981215 100644 --- a/internal/custody/commissioning.go +++ b/internal/custody/commissioning.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "encoding/json" "errors" "fmt" "reflect" @@ -217,9 +218,13 @@ func DeviceCommissioningKind() Kind { SnapshotExtra: func(admission *Admission) map[string]string { return map[string]string{SnapshotSerialNumber: admission.Device.Spec.Identity.Serial} }, - // A held commissioning is settled by a later one that succeeds. No - // Retry is needed: staff create the settling operation directly. + // A held commissioning is settled by a later one that passes. A + // Failed verdict proves the server is not fit, not that an earlier + // run cut off mid-flash or mid-burn-in left it as the plan says, so + // it leaves the hold. No Retry is needed: staff create the settling + // operation directly. Settles: []SettleRule{{Held: "DeviceCommissioning"}}, + SettlesWith: commissioningPassed, KeepsLatest: true, Reasons: []Reason{ {Name: ReasonPlanNotQualified, RaisedBy: RaisedByCoordinator}, @@ -304,11 +309,19 @@ func hasBootInterface(device *inventory.Device) bool { return false } +// commissioningPassed reports whether validated evidence records a Passed +// result. Only such a success settles a commissioning hold. +func commissioningPassed(evidence []byte) bool { + var value ops.CommissioningEvidence + return json.Unmarshal(evidence, &value) == nil && value.Result == ops.CommissioningPassed +} + // validateCommissioningEvidence accepts only evidence that proves its -// verdict. A Passed result records the identity the BMC reported, matching -// the admission snapshot, hardware that meets the plan, every firmware -// baseline at its version, and a passed burn-in that ran the plan's -// duration. A Failed result names the phase and what failed. +// verdict. Every result records the identity the BMC reported, matching the +// admission snapshot, so no verdict is about another server. A Passed +// result also records hardware that meets the plan, every firmware baseline +// at its version, and a passed burn-in that ran the plan's duration. A +// Failed result names the phase and what failed. func validateCommissioningEvidence(operation ops.Operation, evidence *ops.CommissioningEvidence) error { plan := operation.(*ops.DeviceCommissioning).Spec.Plan switch { @@ -322,24 +335,11 @@ func validateCommissioningEvidence(operation ops.Operation, evidence *ops.Commis if err := validateSteps(evidence.Steps); err != nil { return err } - switch evidence.Result { - case ops.CommissioningFailed: - if evidence.FailedPhase != ops.PhaseInspect && evidence.FailedPhase != ops.PhaseFirmware && evidence.FailedPhase != ops.PhaseBurnIn { - return errors.New("a failed commissioning names the phase that failed") - } - if len(evidence.Mismatches) == 0 { - return errors.New("a failed commissioning says what failed") - } - return nil - case ops.CommissioningPassed: - default: + if evidence.Result != ops.CommissioningPassed && evidence.Result != ops.CommissioningFailed { return errors.New("the evidence records no result") } - if evidence.FailedPhase != "" || len(evidence.Mismatches) != 0 { - return errors.New("a passed commissioning records no failure") - } if evidence.SerialNumber == "" || evidence.SystemUUID == "" || evidence.BMCPublicKeySHA256 == "" { - return errors.New("a passed commissioning records the serial number, system UUID and BMC key it read") + return errors.New("a commissioning records the serial number, system UUID and BMC key it read") } // Delivery waits until status records the admission, so the snapshot is // there by the time a result arrives. @@ -351,6 +351,18 @@ func validateCommissioningEvidence(operation ops.Operation, evidence *ops.Commis !strings.EqualFold(strings.TrimSpace(evidence.SerialNumber), strings.TrimSpace(snapshot.Extra[SnapshotSerialNumber])) { return errors.New("the identity the commissioning read differs from the admission snapshot") } + if evidence.Result == ops.CommissioningFailed { + if evidence.FailedPhase != ops.PhaseInspect && evidence.FailedPhase != ops.PhaseFirmware && evidence.FailedPhase != ops.PhaseBurnIn { + return errors.New("a failed commissioning names the phase that failed") + } + if len(evidence.Mismatches) == 0 { + return errors.New("a failed commissioning says what failed") + } + return nil + } + if evidence.FailedPhase != "" || len(evidence.Mismatches) != 0 { + return errors.New("a passed commissioning records no failure") + } hw, want := evidence.Hardware, plan.Content.Inspection if hw == nil { return errors.New("a passed commissioning records the inspected hardware") diff --git a/internal/custody/commissioning_test.go b/internal/custody/commissioning_test.go index 88448408..33b50ccf 100644 --- a/internal/custody/commissioning_test.go +++ b/internal/custody/commissioning_test.go @@ -381,6 +381,20 @@ func TestCommissioning(t *testing.T) { "failed without mismatch": func(v *ops.CommissioningEvidence) { v.Result, v.FailedPhase = ops.CommissioningFailed, ops.PhaseInspect }, + // A Failed verdict is about this server only if it proves the + // same identity a Passed one must. + "failed without serial": func(v *ops.CommissioningEvidence) { + v.Result, v.FailedPhase, v.Mismatches, v.SerialNumber = ops.CommissioningFailed, ops.PhaseInspect, []string{"x"}, "" + }, + "failed with another serial": func(v *ops.CommissioningEvidence) { + v.Result, v.FailedPhase, v.Mismatches, v.SerialNumber = ops.CommissioningFailed, ops.PhaseInspect, []string{"x"}, "serial-other" + }, + "failed with another system uuid": func(v *ops.CommissioningEvidence) { + v.Result, v.FailedPhase, v.Mismatches, v.SystemUUID = ops.CommissioningFailed, ops.PhaseBurnIn, []string{"x"}, "00000000-0000-0000-0000-000000000000" + }, + "failed with another key": func(v *ops.CommissioningEvidence) { + v.Result, v.FailedPhase, v.Mismatches, v.BMCPublicKeySHA256 = ops.CommissioningFailed, ops.PhaseFirmware, []string{"x"}, strings.Repeat("0", 64) + }, } { model := "proof-" + strings.ReplaceAll(name, " ", "-") e, device := next(t, model) @@ -433,6 +447,51 @@ func TestCommissioning(t *testing.T) { } }) + t.Run("a Failed verdict does not settle a commissioning hold", func(t *testing.T) { + e, device := next(t, "failhold") + plan := e.plan("failhold-v1", "failhold", planAuthor) + e.approve(plan, planApprover) + first := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.clock.Advance(CommissioningOverhead + 10*time.Minute + DefaultSkewMargin + time.Second) + e.discover(device, e.custodyKey(device), e.clock.Now()) + e.settle(device.Name) + e.requirePhase(first, ops.PhaseOutcomeUnknown, ReasonDeadlineExceeded) + e.clock.Advance(-(CommissioningOverhead + 10*time.Minute + DefaultSkewMargin + time.Second)) + e.discover(device, e.custodyKey(device), e.clock.Now()) + requireHeld := func(when string) { + t.Helper() + custody := e.custody(device.Name) + if hold := custody.Spec.RecoveryHold; hold == nil || hold.Name != first.Name || custody.Spec.Holder.Type != ops.HolderService { + t.Fatalf("custody %s: %+v", when, custody.Spec) + } + } + second := e.commission(device, plan, plan.Spec.Content) + e.settle(device.Name) + e.requirePhase(second, ops.PhaseAdmitted, "") + if err := e.result(device.Name, ops.PhaseSucceeded, e.commissioningEvidence(second, ops.CommissioningFailed)); err != nil { + t.Fatal(err) + } + e.settle(device.Name) + e.requirePhase(second, ops.PhaseSucceeded, "") + requireHeld("after a Failed verdict") + + // Rebuild reads the same rule from the recorded evidence: the Failed + // verdict's higher fence does not settle the earlier unknown run. + custody := e.custody(device.Name) + fence := custody.Spec.Fence + custody.Finalizers = nil + if err := e.admin.Update(e.ctx, custody); err != nil { + t.Fatal(err) + } + if err := e.admin.Delete(e.ctx, custody); err != nil { + t.Fatal(err) + } + e.sites.report(device.Name, fence) + e.settle(device.Name) + requireHeld("after rebuild") + }) + t.Run("retention keeps each Device's latest succeeded commissioning", func(t *testing.T) { e, device := next(t, "retain") plan := e.plan("retain-v1", "retain", planAuthor) diff --git a/internal/custody/rebuild.go b/internal/custody/rebuild.go index 4cb27864..cba40d6d 100644 --- a/internal/custody/rebuild.go +++ b/internal/custody/rebuild.go @@ -103,8 +103,8 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) } } // settled reports whether a later success settled an unknown outcome: - // an operation whose kind settles the held kind, or a recovery that - // cleared that exact hold. + // an operation whose kind settles the held kind with the evidence it + // recorded, or a recovery that cleared that exact hold. settled := func(held found) bool { fence := admissionFence(held.operation) for _, other := range all { @@ -121,7 +121,7 @@ func (c *Coordinator) rebuiltSpec(ctx context.Context, device *inventory.Device) return true } } - if admissionFence(other.operation) > fence && slices.ContainsFunc(other.kind.Settles, func(rule SettleRule) bool { return rule.Held == held.kind.GVK.Kind }) { + if admissionFence(other.operation) > fence && slices.ContainsFunc(other.kind.Settles, func(rule SettleRule) bool { return rule.Held == held.kind.GVK.Kind }) && other.kind.settlesWith(rawBytes(status.Evidence)) { return true } } @@ -244,3 +244,10 @@ func rawEvidence(value any) (*runtime.RawExtension, error) { func rawExtension(data []byte) *runtime.RawExtension { return &runtime.RawExtension{Raw: append([]byte(nil), data...)} } + +func rawBytes(extension *runtime.RawExtension) []byte { + if extension == nil { + return nil + } + return extension.Raw +} diff --git a/internal/custody/registry.go b/internal/custody/registry.go index 944db7f8..6e0c1e43 100644 --- a/internal/custody/registry.go +++ b/internal/custody/registry.go @@ -94,6 +94,11 @@ type Kind struct { // empty: a kind whose holds only a DeviceRecovery settles, such as power, // settles no hold itself. Settles []SettleRule + // SettlesWith, when set, decides from a success's canonical evidence + // whether it settles the hold it was admitted to settle. A success it + // rejects ends Succeeded and leaves the hold in place. Nil means every + // success settles. + SettlesWith func(evidence []byte) bool // Retryable means a DeviceRecovery with Retry applies to this kind's // holds: it lets the held operation's requester create one settling // operation. @@ -128,6 +133,12 @@ type Kind struct { Clears func(ops.Operation) *ops.HeldOperationReference } +// settlesWith reports whether a success with this evidence settles the hold +// it was admitted to settle. +func (k *Kind) settlesWith(evidence []byte) bool { + return k.SettlesWith == nil || k.SettlesWith(evidence) +} + func (k *Kind) checksDiscovery(operation ops.Operation) bool { return k.SkipsDiscovery == nil || !k.SkipsDiscovery(operation) } diff --git a/internal/custody/results.go b/internal/custody/results.go index d5062bb9..9673bddc 100644 --- a/internal/custody/results.go +++ b/internal/custody/results.go @@ -184,7 +184,7 @@ func (c *Coordinator) AcceptResult(ctx context.Context, result SiteResult) error case ops.PhaseFailed: c.finishActive(custody, *active, ops.PhaseFailed, result.Reason, result.Message, evidence) case ops.PhaseSucceeded: - if hold := spec.RecoveryHold; hold != nil && active.Settles != nil && *active.Settles == heldReference(*hold) { + if hold := spec.RecoveryHold; hold != nil && active.Settles != nil && *active.Settles == heldReference(*hold) && kind.settlesWith(evidence) { spec.RecoveryHold = nil } c.finishActive(custody, *active, ops.PhaseSucceeded, result.Reason, result.Message, evidence) From c2cc6b69202e7d1f8e71180910f5eb039a795b84 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Sat, 28 Nov 2026 11:28:29 -0600 Subject: [PATCH 3/3] docs(custody): State the two-person IAM rule The username comparison at admission was the only stated guard on plan separation. State the IAM rule it backs: the author and approver roles are never bound to one principal or to groups that share a member. Fleet does not own IAM bindings, so the rule is documented on both roles, and the packaged-IAM test now follows inherited roles and refuses any packaged PolicyBinding that grants one subject both. Co-Authored-By: Claude Opus 5.5 --- .../device-commissioning-plan-approver.yaml | 2 +- .../device-commissioning-plan-author.yaml | 2 +- .../api/operations/v1alpha1/config_test.go | 124 +++++++++++++++++- 3 files changed, 119 insertions(+), 9 deletions(-) diff --git a/config/components/device-operations/roles/device-commissioning-plan-approver.yaml b/config/components/device-operations/roles/device-commissioning-plan-approver.yaml index b4a9c013..7c25b4d6 100644 --- a/config/components/device-operations/roles/device-commissioning-plan-approver.yaml +++ b/config/components/device-operations/roles/device-commissioning-plan-approver.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-commissioning-plan-approver annotations: kubernetes.io/display-name: Fleet Device Commissioning Plan Approver - kubernetes.io/description: Approve another person's commissioning plan, or revoke an approval. + kubernetes.io/description: Approve another person's commissioning plan, or revoke an approval. Never bind this role and the plan author role to the same principal, or to groups that share a member. spec: launchStage: Alpha inheritedRoles: diff --git a/config/components/device-operations/roles/device-commissioning-plan-author.yaml b/config/components/device-operations/roles/device-commissioning-plan-author.yaml index ec4f503f..2bb58563 100644 --- a/config/components/device-operations/roles/device-commissioning-plan-author.yaml +++ b/config/components/device-operations/roles/device-commissioning-plan-author.yaml @@ -4,7 +4,7 @@ metadata: name: fleet.datumapis.com-device-commissioning-plan-author annotations: kubernetes.io/display-name: Fleet Device Commissioning Plan Author - kubernetes.io/description: Write and delete commissioning plans. An author cannot approve a plan they wrote. + kubernetes.io/description: Write and delete commissioning plans. An author cannot approve a plan they wrote. Never bind this role and the plan approver role to the same principal, or to groups that share a member. spec: launchStage: Alpha inheritedRoles: diff --git a/internal/api/operations/v1alpha1/config_test.go b/internal/api/operations/v1alpha1/config_test.go index ce72cb56..b989f9df 100644 --- a/internal/api/operations/v1alpha1/config_test.go +++ b/internal/api/operations/v1alpha1/config_test.go @@ -324,14 +324,124 @@ func TestPhases(t *testing.T) { } } -// TestPlanAuthorsCannotApprove keeps the two-person rule in the roles: no -// role both writes plans and approves them. +// TestPlanAuthorsCannotApprove keeps the two-person rule in the packaged +// IAM: no role, counting the roles it inherits, both writes plans and +// approves them, and no packaged PolicyBinding binds the author and approver +// roles to one subject. Bindings an operator makes are outside the package; +// device-custody.md states the rule they must follow. func TestPlanAuthorsCannotApprove(t *testing.T) { - for _, r := range decodeDir[role](t, filepath.Join(componentRoot, "roles")) { - writes := slices.Contains(r.Spec.Included, GroupVersion.Group+"/devicecommissioningplans.create") - approves := slices.Contains(r.Spec.Included, GroupVersion.Group+"/devicecommissioningplanapprovals.create") - if writes && approves { - t.Fatalf("%s both writes and approves plans", r.Metadata.Name) + roles := decodeDir[role](t, filepath.Join(componentRoot, "roles")) + if name := writesAndApproves(roles); name != "" { + t.Fatalf("%s both writes and approves plans", name) + } + // A role that only inherits both is caught too. + combined := role{} + combined.Metadata.Name = "combined" + combined.Spec.Inherited = []struct{ Name string }{{Name: planAuthorRole}, {Name: planApproverRole}} + if writesAndApproves(append(slices.Clone(roles), combined)) != "combined" { + t.Fatal("a role inheriting the author and approver roles was not caught") + } + var bindings []policyBinding + if err := filepath.WalkDir(configRoot, func(path string, entry fs.DirEntry, err error) error { + if err != nil || entry.IsDir() || (filepath.Ext(path) != ".yaml" && filepath.Ext(path) != ".yml") { + return err + } + for _, binding := range decodeAll[policyBinding](t, path) { + if binding.Kind == "PolicyBinding" { + bindings = append(bindings, binding) + } + } + return nil + }); err != nil { + t.Fatal(err) + } + if subject := boundToBoth(roles, bindings); subject != "" { + t.Fatalf("a packaged PolicyBinding grants %s both plan roles", subject) + } + same := policyBinding{Kind: "PolicyBinding"} + same.Spec.RoleRef.Name = planAuthorRole + same.Spec.Subjects = []struct{ Kind, Name string }{{Kind: "User", Name: "someone@example.com"}} + other := same + other.Spec.RoleRef.Name = planApproverRole + if boundToBoth(roles, []policyBinding{same, other}) == "" { + t.Fatal("bindings granting one subject both plan roles were not caught") + } +} + +const ( + planAuthorRole = "fleet.datumapis.com-device-commissioning-plan-author" + planApproverRole = "fleet.datumapis.com-device-commissioning-plan-approver" +) + +type policyBinding struct { + Kind string `json:"kind"` + Spec struct { + RoleRef struct{ Name string } `json:"roleRef"` + Subjects []struct{ Kind, Name string } `json:"subjects"` + } `json:"spec"` +} + +// effective returns the permissions a role grants with the roles it +// inherits. +func effective(roles []role, name string) map[string]bool { + byName := map[string]role{} + for _, r := range roles { + byName[r.Metadata.Name] = r + } + out, seen := map[string]bool{}, map[string]bool{} + var walk func(string) + walk = func(name string) { + if seen[name] { + return + } + seen[name] = true + r := byName[name] + for _, permission := range r.Spec.Included { + out[permission] = true + } + for _, inherited := range r.Spec.Inherited { + walk(inherited.Name) + } + } + walk(name) + return out +} + +var ( + writePlan = GroupVersion.Group + "/devicecommissioningplans.create" + approvePlan = GroupVersion.Group + "/devicecommissioningplanapprovals.create" +) + +// writesAndApproves names a role that both writes and approves plans. +func writesAndApproves(roles []role) string { + for _, r := range roles { + if granted := effective(roles, r.Metadata.Name); granted[writePlan] && granted[approvePlan] { + return r.Metadata.Name + } + } + return "" +} + +// boundToBoth names a subject the bindings grant both plan writing and +// plan approval. +func boundToBoth(roles []role, bindings []policyBinding) string { + granted := map[string]map[string]bool{} + for _, binding := range bindings { + permissions := effective(roles, binding.Spec.RoleRef.Name) + for _, subject := range binding.Spec.Subjects { + key := subject.Kind + "/" + strings.ToLower(subject.Name) + if granted[key] == nil { + granted[key] = map[string]bool{} + } + for permission := range permissions { + granted[key][permission] = true + } + } + } + for subject, permissions := range granted { + if permissions[writePlan] && permissions[approvePlan] { + return subject } } + return "" }