diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 83fdfdb0..84fbc4ce 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,10 @@ jobs: with: {go-version-file: go.mod, cache: true} - uses: imranismail/setup-kustomize@v2 with: {kustomize-version: 5.8.1} + # Runs the manager's multi-project end-to-end test against real API + # servers; without these assets it is skipped. + - name: Install envtest assets + run: echo "KUBEBUILDER_ASSETS=$(go run sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.25.2 use 1.37.0 -p path)" >> "$GITHUB_ENV" - run: go test ./... - run: go test -race ./... - run: go vet ./... @@ -22,6 +26,7 @@ jobs: - run: kustomize build config/milo >/dev/null - run: kustomize build config/overlays/management-plane >/dev/null - run: kustomize build config/overlays/synthetic-staging >/dev/null + - run: kustomize build config/inventory-observer >/dev/null - run: ./hack/validate-synthetic-staging-render.sh - run: ./hack/validate-overlay-isolation.sh - run: ./hack/test-overlay-isolation.sh diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2ada75ca..03828158 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -64,6 +64,7 @@ jobs: images: | - { path: config/base/manager, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/overlays/synthetic-staging, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } + - { path: config/inventory-observer, name: ghcr.io/datum-cloud/fleet, tag: "${{ needs.publish-container-image.outputs.tag }}" } - { path: config/components/consumer-ui-plugin, name: ghcr.io/datum-cloud/fleet-consumer-ui-plugin, tag: "${{ needs.publish-consumer-ui-plugin-image.outputs.tag }}" } - { path: config/components/provider-ui-plugin, name: ghcr.io/datum-cloud/fleet-provider-ui-plugin, tag: "${{ needs.publish-provider-ui-plugin-image.outputs.tag }}" } secrets: inherit diff --git a/build/manager.Dockerfile b/build/manager.Dockerfile index 626e0127..2efa97f4 100644 --- a/build/manager.Dockerfile +++ b/build/manager.Dockerfile @@ -7,10 +7,12 @@ COPY cmd/ ./cmd/ COPY internal/ ./internal/ RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-manager ./cmd/fleet-manager \ && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-simulator ./cmd/fleet-simulator \ - && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-dhcp-sync ./cmd/fleet-dhcp-sync \ + && CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-inventory-observer ./cmd/fleet-inventory-observer FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/fleet-manager /fleet-manager COPY --from=build /out/fleet-simulator /fleet-simulator COPY --from=build /out/fleet-dhcp-sync /fleet-dhcp-sync +COPY --from=build /out/fleet-inventory-observer /fleet-inventory-observer ENTRYPOINT ["/fleet-manager"] diff --git a/cmd/fleet-inventory-observer/main.go b/cmd/fleet-inventory-observer/main.go new file mode 100644 index 00000000..b0e110bd --- /dev/null +++ b/cmd/fleet-inventory-observer/main.go @@ -0,0 +1,92 @@ +// fleet-inventory-observer refreshes InventoryObservation status from NetBox +// once and exits. It reads NetBox with GET requests only and writes only the +// status subresource of existing observations in one namespace. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "log/slog" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventoryv1 "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/inventoryobserver" + "go.datum.net/fleet/internal/netbox" +) + +func main() { + var namespace, origin, tokenFile string + var timeout time.Duration + flag.StringVar(&namespace, "namespace", os.Getenv("POD_NAMESPACE"), "namespace holding InventoryObservations") + flag.StringVar(&origin, "netbox-url", os.Getenv("NETBOX_URL"), "NetBox origin, https://host[:port]") + flag.StringVar(&tokenFile, "netbox-token-file", "", "file holding a read-only NetBox API token") + flag.DurationVar(&timeout, "timeout", 2*time.Minute, "deadline for the whole refresh") + flag.Parse() + logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + if err := run(ctx, logger, namespace, origin, tokenFile); err != nil { + logger.Error("inventory observation refresh incomplete", "error", err) + os.Exit(1) + } +} + +func run(ctx context.Context, logger *slog.Logger, namespace, origin, tokenFile string) error { + if namespace == "" || origin == "" || tokenFile == "" { + return errors.New("--namespace, --netbox-url, and --netbox-token-file are required") + } + source, err := netbox.NewClient(origin, func() (string, error) { + data, err := os.ReadFile(tokenFile) + return string(data), err + }, &http.Client{Timeout: 30 * time.Second}) + if err != nil { + return err + } + scheme := runtime.NewScheme() + if err := inventoryv1.AddToScheme(scheme); err != nil { + return err + } + config, err := ctrl.GetConfig() + if err != nil { + return err + } + kube, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + return err + } + observer := &inventoryobserver.Observer{Client: kube, Namespace: namespace, NetBox: source} + results, err := observer.RefreshAll(ctx) + if err != nil { + return err + } + failed := 0 + for _, result := range results { + attrs := []any{"observation", result.Name, "reason", result.Reason} + if result.WriteErr != nil { + attrs = append(attrs, "writeError", result.WriteErr.Error()) + } + if result.Succeeded() { + logger.Info("observation refreshed", attrs...) + continue + } + failed++ + logger.Warn("observation not refreshed", append(attrs, "message", result.Message)...) + } + logger.Info("refresh finished", "observations", len(results), "notRefreshed", failed) + if failed > 0 { + return fmt.Errorf("%d of %d observations were not refreshed", failed, len(results)) + } + return nil +} diff --git a/config/README.md b/config/README.md index 07e34cda..7215c50b 100644 --- a/config/README.md +++ b/config/README.md @@ -18,6 +18,13 @@ API servers and must be reconciled independently. | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | +`config/inventory-observer` is an opt-in root for the Fleet management cluster. +It holds the observed-only `InventoryObservation` CRD and a NetBox observer +CronJob with namespace-scoped status-only RBAC. The environment supplies the +`fleet-inventory-observer` ConfigMap (`netboxURL`) and the +`fleet-inventory-observer-netbox` Secret (`token`). Neither production root +references it. See [Observational inventory import](../docs/operations/inventory-observation.md). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. diff --git a/config/inventory-observer/crd.yaml b/config/inventory-observer/crd.yaml new file mode 100644 index 00000000..26eb3a41 --- /dev/null +++ b/config/inventory-observer/crd.yaml @@ -0,0 +1,57 @@ +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + name: inventoryobservations.fleet.datumapis.com +spec: + group: fleet.datumapis.com + names: {kind: InventoryObservation, listKind: InventoryObservationList, plural: inventoryobservations, singular: inventoryobservation, shortNames: [invobs]} + scope: Namespaced + versions: + - name: v1alpha1 + served: true + storage: true + subresources: {status: {}} + additionalPrinterColumns: + - {name: System, type: string, jsonPath: .spec.source.system} + - {name: ID, type: integer, jsonPath: .spec.source.id} + - {name: Name, type: string, jsonPath: .status.facts.name} + - {name: Observed, type: string, jsonPath: '.status.conditions[?(@.type=="Observed")].status'} + - {name: Reason, type: string, jsonPath: '.status.conditions[?(@.type=="Observed")].reason'} + - {name: Observed At, type: date, jsonPath: .status.observedAt} + - {name: Trust, type: string, priority: 1, jsonPath: .status.trustProfile} + schema: + openAPIV3Schema: + type: object + required: [spec] + properties: + apiVersion: {type: string} + kind: {type: string} + metadata: {type: object} + spec: + type: object + required: [source] + x-kubernetes-validations: + - rule: self.source == oldSelf.source + message: the observed source identity is immutable; create a new observation instead + properties: + source: + type: object + required: [system, kind, id] + properties: + system: {type: string, enum: [NetBox]} + kind: {type: string, enum: [Device]} + id: {type: integer, format: int64, minimum: 1} + expectedName: {type: string, minLength: 1, maxLength: 253} + status: + type: object + properties: + observedGeneration: {type: integer, format: int64} + trustProfile: {type: string, enum: [ObservedOnly-v1]} + lastAttemptTime: {type: string, format: date-time} + observedAt: {type: string, format: date-time} + sourceUpdatedAt: {type: string, format: date-time} + factsDigest: {type: string} + facts: {type: object, x-kubernetes-preserve-unknown-fields: true} + conditions: + type: array + items: {type: object, x-kubernetes-preserve-unknown-fields: true} diff --git a/config/inventory-observer/cronjob.yaml b/config/inventory-observer/cronjob.yaml new file mode 100644 index 00000000..a61cf037 --- /dev/null +++ b/config/inventory-observer/cronjob.yaml @@ -0,0 +1,77 @@ +apiVersion: batch/v1 +kind: CronJob +metadata: + name: fleet-inventory-observer + namespace: fleet-system + labels: + app.kubernetes.io/name: fleet-inventory-observer + app.kubernetes.io/component: inventory-observer +spec: + schedule: "*/15 * * * *" + concurrencyPolicy: Forbid + startingDeadlineSeconds: 600 + successfulJobsHistoryLimit: 1 + failedJobsHistoryLimit: 3 + jobTemplate: + spec: + backoffLimit: 0 + activeDeadlineSeconds: 300 + ttlSecondsAfterFinished: 86400 + template: + metadata: + labels: + app.kubernetes.io/name: fleet-inventory-observer + app.kubernetes.io/component: inventory-observer + spec: + serviceAccountName: fleet-inventory-observer + restartPolicy: Never + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + seccompProfile: + type: RuntimeDefault + containers: + - name: observer + image: ghcr.io/datum-cloud/fleet:latest + imagePullPolicy: IfNotPresent + command: [/fleet-inventory-observer] + args: + - --namespace=$(POD_NAMESPACE) + - --netbox-url=$(NETBOX_URL) + - --netbox-token-file=/var/run/fleet/netbox/token + - --timeout=4m + env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: NETBOX_URL + valueFrom: + configMapKeyRef: + name: fleet-inventory-observer + key: netboxURL + resources: + requests: + cpu: 10m + memory: 32Mi + limits: + memory: 128Mi + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + volumeMounts: + - name: netbox-token + mountPath: /var/run/fleet/netbox + readOnly: true + volumes: + - name: netbox-token + secret: + secretName: fleet-inventory-observer-netbox + defaultMode: 0440 + items: + - key: token + path: token diff --git a/config/inventory-observer/kustomization.yaml b/config/inventory-observer/kustomization.yaml new file mode 100644 index 00000000..ca87b5dc --- /dev/null +++ b/config/inventory-observer/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - crd.yaml + - rbac.yaml + - cronjob.yaml diff --git a/config/inventory-observer/rbac.yaml b/config/inventory-observer/rbac.yaml new file mode 100644 index 00000000..ebbcf2ca --- /dev/null +++ b/config/inventory-observer/rbac.yaml @@ -0,0 +1,32 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-inventory-observer + namespace: fleet-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-inventory-observer + namespace: fleet-system +rules: + - apiGroups: [fleet.datumapis.com] + resources: [inventoryobservations] + verbs: [get, list] + - apiGroups: [fleet.datumapis.com] + resources: [inventoryobservations/status] + verbs: [update] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-inventory-observer + namespace: fleet-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-inventory-observer +subjects: + - kind: ServiceAccount + name: fleet-inventory-observer + namespace: fleet-system diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 4d305dfe..036423a8 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -59,7 +59,7 @@ processes or service-catalog entries. | --- | --- | --- | | `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six alpha CRDs at `v1alpha1`. Production admission and real providers remain incomplete. | | `provider.metal.datumapis.com` | Proposed `MachineOffering` owns installation/management capability policy; `MachineOfferingAssignment` controls acquisition access. MachineClass becomes only a one-hop published consumer view; MachineProfile remains immutable requirements in Metal. | Proposed target design, not implemented by the six alpha CRDs above. | -| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs; no physical inventory CRDs or real provider executor are implemented here. | +| `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. `InventoryObservation` holds observed-only evidence read from an external inventory system. | Proposed inventory APIs; no physical inventory CRDs or real provider executor are implemented here. `InventoryObservation` is an implemented alpha CRD in the opt-in [observer root](../operations/inventory-observation.md), outside the production roots; nothing consumes it. | | `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | Architecture decision only on the current main implementation: no coordination CRD or cell controller is packaged. Replaces the earlier prototype name `internal.fleet.datumapis.com`. | MachineCapacity and MachineAllocation belong to the Metal allocation contract diff --git a/docs/development/README.md b/docs/development/README.md index 3eb2fe48..6b0444f1 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -45,7 +45,8 @@ Milo IAM, service, and quota boundaries; packaging is not runtime readiness. The allocation APIs now use `metal.datumapis.com/v1alpha1`. Milo registers the Bare Metal service as `metal`; entitlement and location-availability readers use -that reference. Physical Device references use `fleet.datumapis.com`. The +that reference. Physical Device references use `fleet.datumapis.com`; that group +implements only the observed-only `InventoryObservation` kind today. The [API architecture](../architecture/README.md) documents the proposed coordination group, control-plane placement, and rollout constraints. Group renaming does not migrate stored allocations or establish live acceptance. @@ -587,6 +588,21 @@ The persisted schema and HTTP endpoints are internal alpha interfaces. No compatibility promise exists yet. The process fails closed if retained state is corrupt or uses an unsupported schema version. +## Inventory observation + +`internal/api/inventory/v1alpha1` defines `InventoryObservation`. +`internal/netbox` is a read-only NetBox client, and `internal/inventoryobserver` +refreshes observation status from it. `cmd/fleet-inventory-observer` runs one +refresh and exits. `config/inventory-observer` packages the CRD, a +namespace-scoped Role that grants only `get`/`list` on observations and `update` +on their status, and a CronJob. No production root includes it, and no +controller reads observations. Unit tests cover NetBox decoding and transport +limits, identity guards, retained facts on failure, write conflicts, write +scope, CRD validation, and RBAC scope. With `KUBEBUILDER_ASSETS` set, an +envtest test runs the observer as its packaged service account against a real +API server. No test runs against a live NetBox. See +[Observational inventory import](../operations/inventory-observation.md). + ## Build, test, and run Run the implemented checks from the repository root: diff --git a/docs/operations/README.md b/docs/operations/README.md index ed23e838..320baa71 100644 --- a/docs/operations/README.md +++ b/docs/operations/README.md @@ -17,6 +17,7 @@ integrations. Real provider support and live Milo acceptance tests are incomplet | Exercise Milo, Karmada and cell-local PXE end to end with one command | [Multi-plane acceptance](multiplane.md) (`task multiplane:acceptance`) | Native project routing, federation delivery/reflection, partition, [Kubernetes site execution](site-execution.md) (Flux-owned shared services, kro-created per-operation Jobs) with worker Pod/Job interruption, delivery and reflection faults, wrong location, cleanup and reuse; every service [installed by per-cluster Flux](gitops.md) from a source built from the checkout; production authority unqualified | | Drive the same pipeline through Redfish instead of libvirt | [Redfish-mode acceptance](redfish-lab.md) (`task multiplane:redfish-acceptance`) | Redfish executor discovery, one-time PXE/disk boot overrides, power, lost-response recovery and a booted wipe cleanup, against the unmodified DMTF Redfish Interface Emulator with a lab-only libvirt adapter and two persistent lab VMs; synthetic credentials and networking; not physical BMC or hardware qualification | | Publish physical-side DHCP reservations for network boot | [Boot network](boot-network.md) | Per-asset BMC endpoints and provisioning attachments, a reservation feed that exists only while a boot is admitted, served and withdrawn evidence from the DHCP owner's Kea synchronizer; unit tested, not exercised at a site | +| Import NetBox device records as observed-only evidence | [Observational inventory import](inventory-observation.md) | Allowlisted NetBox facts in `InventoryObservation` status with retained facts on failure and identity guards; no Device, capacity, or hardware effect; unit tested | | Render deployment bundles and supply environment inputs | [Deployment manifests](../../config/README.md) | Packaging and security boundaries, not runtime readiness | | Exercise Milo-routed synthetic staging | [Synthetic staging configuration](../../config/README.md#environment-owned-inputs) | Restricted synthetic publication and lifecycle behavior, not production authority | | Validate Milo acceptance packaging and evidence | [Milo acceptance harness](../../test/acceptance/milo/README.md) | Fail-closed preflight and sanitized evidence; live acceptance remains blocked | diff --git a/docs/operations/inventory-observation.md b/docs/operations/inventory-observation.md new file mode 100644 index 00000000..35cfd26f --- /dev/null +++ b/docs/operations/inventory-observation.md @@ -0,0 +1,168 @@ +# Observational inventory import from NetBox + +[Operations guide](README.md) · [Architecture](../architecture/README.md) · +[Implementation status](../development/README.md) + +Operators already record racks, chassis, serials, ports, cabling, and management +addresses in NetBox. Fleet needs to read those records about real hardware +before it can plan, enroll, or offer that hardware. The importer must not +provision anything, publish capacity, or take ownership in the process. + +The `InventoryObservation` kind in `fleet.datumapis.com/v1alpha1` and the +`fleet-inventory-observer` command do this. An operator names one NetBox device. +The observer copies an allowlisted set of that device's recorded facts into the +observation's status. The status carries the source revision, the time it was +read, a content digest, and the `ObservedOnly-v1` trust profile. + +## Status + +| Aspect | State | +| --- | --- | +| CRD, Go types, observer command, NetBox client, CronJob and RBAC root | Implemented in `config/inventory-observer` and `cmd/fleet-inventory-observer`. | +| Tests | Unit tests cover NetBox decoding, auth schemes, pagination, redirects, failure mapping, identity guards, retained facts, write conflicts, write scope, CRD validation, and RBAC scope. An envtest test runs the observer as its packaged service account against a real API server. It checks that the packaged Role allows status writes only, that `spec.source` is immutable, that stale writes conflict, and that the trust profile cannot be raised. No test runs against a live NetBox. | +| Production roots | Not included. `config/milo`, `config/overlays/management-plane`, and `config/overlays/synthetic-staging` do not reference it. An environment opts in by reconciling `config/inventory-observer`. | +| Hardware qualification | None. Facts are operator-entered records, not observed hardware. | + +## What an observation is and is not + +An observation is attributable evidence about one source object. It is **not** +a `Device`, a `DeviceClaim`, a `MachineCapacity`, a plan, or an ownership +transition. This follows the inventory principle that discovery creates +observed-only evidence. No Fleet controller reads observations. Creating, +refreshing, or deleting one does not: + +- publish supply or make capacity allocatable; +- reserve rack space, ports, or power; +- authorize power, boot, wipe, credential, or network changes; or +- change any record in NetBox. + +`MachineCapacity.spec.deviceRef` still names a Device record. The proposed +`Device` kind is not implemented. A later, explicit registration step may link an +observation to a Device. Until then the two stay separate identities. + +## Writers + +| Surface | Sole writer | +| --- | --- | +| `spec.source` (system, kind, NetBox ID, optional expected name) | Operator, usually through GitOps. Immutable after creation. | +| `status` | `fleet-inventory-observer`. It needs `get`/`list` on observations and `update` on their status, and nothing else. | +| NetBox | Unchanged. The observer sends only `GET` requests. | + +The observer never creates or deletes observations, and it never edits their +spec, labels, or annotations. To retarget an observation, create a new one; the +CRD rejects changes to `spec.source`. + +## Example + +```yaml +apiVersion: fleet.datumapis.com/v1alpha1 +kind: InventoryObservation +metadata: + name: netbox-device-1234 + namespace: fleet-system +spec: + source: + system: NetBox + kind: Device + id: 1234 + expectedName: server-01.rack-01.example +``` + +After a refresh, `kubectl get inventoryobservations -n fleet-system` shows the +recorded name, whether the last refresh succeeded and why, and when the facts +were read. `status.facts` holds: + +- the name, manufacturer, model, serial, asset tag, role, and NetBox status; +- the site slug, rack, position, and face; +- each interface's name, type, recorded speed, enabled and management flags, + LAG, normalized MAC addresses, and recorded cable peers; and +- the primary IPv4, primary IPv6, and out-of-band addresses as recorded. + +## Refresh semantics + +| Situation | `Observed` condition | Facts | +| --- | --- | --- | +| Device read and identity matches | `True`, `Observed` | Replaced; `observedAt`, `sourceUpdatedAt`, and `factsDigest` updated | +| NetBox unreachable, timed out, malformed, or inconsistent during pagination | `False`, `SourceUnavailable` | Previous facts retained, unchanged | +| Credential rejected (HTTP 401/403) | `False`, `SourceUnauthorized` | Retained | +| Device ID not found | `False`, `SourceObjectMissing` | Retained | +| Name differs from `expectedName`, or the serial differs from the previously observed serial | `False`, `IdentityMismatch` | Not updated | + +A failed refresh never reports success, and it never clears or overwrites the +facts from the last successful read. Consumers must compare `observedAt` with +their own freshness requirement; an old `True` condition is still old evidence. +A changed serial on the same NetBox ID is reported as a mismatch rather than +accepted as an update, because replaced hardware is a new asset identity. To +record it, create a new observation. The observer updates status with the +listed `resourceVersion`, so a concurrent change makes its write fail. The next +run retries. + +## Source handling + +- **Allowlist only.** Custom fields, comments, config contexts, local context + data, tags, and tenant data are never decoded or stored. NetBox custom fields + can hold credentials. +- **Identity.** The NetBox numeric ID is the source key. Device names can + change, so `expectedName` is a guard, not the key. +- **Units.** `speedKbps` is the source value unchanged. NetBox defines interface + speed in kbps, but values are operator-entered and not checked against links. +- **MAC addresses.** The pre-4.2 `mac_address`, `primary_mac_address`, and + `mac_addresses` fields are merged, parsed, lowercased, and deduplicated. Values + that do not parse are dropped. +- **Transport.** The origin must be HTTPS; plain HTTP is allowed only on + loopback, for tests. Redirects are not followed. The client computes its own + pagination offsets and never follows server-supplied `next` URLs, so the token + goes only to the configured origin. Response bodies are capped at 4 MiB and + interface lists at 2,000 entries. +- **Credentials.** Tokens prefixed `nbt_` (NetBox 4.5+ v2 tokens) use the + `Bearer` scheme; others use `Token`. The token file is re-read on every + request, so a rotated Secret applies without a restart. An empty token is + never sent. After the first 401 or 403 in a run, the observer stops + contacting the source and marks the remaining observations + `SourceUnauthorized`. Sources often ban addresses that repeat failed + authentication, and a ban would also block other clients sharing the same + egress address. + +## Deploying the observer root + +`config/inventory-observer` contains the cluster-scoped CRD and the following in +`fleet-system`: a ServiceAccount, a Role and RoleBinding, and a CronJob that +runs every 15 minutes with `concurrencyPolicy: Forbid`. The publish workflow +pins the CronJob image to the same build as the manager. The environment +supplies: + +| Input | Key | Content | +| --- | --- | --- | +| ConfigMap `fleet-inventory-observer` | `netboxURL` | NetBox origin, for example `https://netbox.example` | +| Secret `fleet-inventory-observer-netbox` | `token` | A read-only NetBox API token, delivered by the environment's secret manager | + +Apply observations after the CRD is established, for example from a separate +reconciliation that depends on this root. A Job exits non-zero when any +observation was not refreshed, so failed Jobs show stale or mismatched +evidence. The CronJob needs egress to the NetBox origin and the Kubernetes API. + +Run one refresh locally against a disposable cluster: + +```sh +go run ./cmd/fleet-inventory-observer \ + --namespace fleet-system \ + --netbox-url https://netbox.example \ + --netbox-token-file /path/outside/the/repository/token +``` + +It uses the current kubeconfig context. Keep the token file outside the +repository. + +## Deferred decisions + +- Where operator-only inventory finally lives: this root keeps observations on + the management cluster. The inventory proposal places physical inventory in an + operator project, which requires Milo registration and IAM. +- Registration from an observation into a `Device`, and any link to + `MachineCapacity`. Both need the explicit, separately authorized transition + described by the inventory proposal. +- Hardware facts (CPU, memory, disks). NetBox records for compute nodes often + lack them; they belong to a qualified collector such as Redfish inventory, + not to NetBox import. +- Bulk selection, for example every device in a rack. Each observation is + explicit today so that importing cannot widen silently. diff --git a/internal/api/inventory/v1alpha1/crd_test.go b/internal/api/inventory/v1alpha1/crd_test.go new file mode 100644 index 00000000..aa5c24ad --- /dev/null +++ b/internal/api/inventory/v1alpha1/crd_test.go @@ -0,0 +1,175 @@ +package v1alpha1 + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "testing" + + rbacv1 "k8s.io/api/rbac/v1" + "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + crdvalidation "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/validation" + structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema" + "k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel" + "k8s.io/apiextensions-apiserver/pkg/apiserver/validation" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/validation/field" + "k8s.io/apimachinery/pkg/util/yaml" + celconfig "k8s.io/apiserver/pkg/apis/cel" +) + +var observerRoot = filepath.Join("..", "..", "..", "..", "config", "inventory-observer") + +func loadDocuments(t *testing.T, name string) []*unstructured.Unstructured { + t.Helper() + data, err := os.ReadFile(filepath.Join(observerRoot, name)) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + var out []*unstructured.Unstructured + for { + var object map[string]any + if err := decoder.Decode(&object); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + if object != nil { + out = append(out, &unstructured.Unstructured{Object: object}) + } + } +} + +func loadCRD(t *testing.T) *extensionsv1.CustomResourceDefinition { + t.Helper() + documents := loadDocuments(t, "crd.yaml") + if len(documents) != 1 { + t.Fatalf("got %d documents in crd.yaml, want 1", len(documents)) + } + var crd extensionsv1.CustomResourceDefinition + if err := runtime.DefaultUnstructuredConverter.FromUnstructured(documents[0].Object, &crd); err != nil { + t.Fatal(err) + } + return &crd +} + +func TestObservationCRDMatchesGoIdentityAndPassesDefinitionValidation(t *testing.T) { + crd := loadCRD(t) + if crd.Spec.Group != GroupVersion.Group || crd.Name != "inventoryobservations."+GroupVersion.Group || crd.Spec.Names.Kind != "InventoryObservation" || crd.Spec.Scope != extensionsv1.NamespaceScoped { + t.Fatalf("CRD identity = %s %s %s", crd.Name, crd.Spec.Names.Kind, crd.Spec.Scope) + } + if len(crd.Spec.Versions) != 1 || crd.Spec.Versions[0].Name != GroupVersion.Version || crd.Spec.Versions[0].Subresources == nil || crd.Spec.Versions[0].Subresources.Status == nil { + t.Fatal("CRD must serve exactly v1alpha1 with a status subresource") + } + if _, ok := crd.Annotations["discovery.miloapis.com/parent-contexts"]; ok { + t.Fatal("observation CRD must not be exposed through Milo project discovery") + } + defaulted := crd.DeepCopy() + extensionsv1.SetObjectDefaults_CustomResourceDefinition(defaulted) + defaulted.Status.StoredVersions = []string{GroupVersion.Version} + var internal apiextensions.CustomResourceDefinition + if err := extensionsv1.Convert_v1_CustomResourceDefinition_To_apiextensions_CustomResourceDefinition(defaulted, &internal, nil); err != nil { + t.Fatal(err) + } + if errs := crdvalidation.ValidateCustomResourceDefinition(context.Background(), &internal); len(errs) > 0 { + t.Fatal(errs.ToAggregate()) + } +} + +func validate(t *testing.T, object, old map[string]any) field.ErrorList { + t.Helper() + crd := loadCRD(t) + var schema apiextensions.JSONSchemaProps + if err := extensionsv1.Convert_v1_JSONSchemaProps_To_apiextensions_JSONSchemaProps(crd.Spec.Versions[0].Schema.OpenAPIV3Schema, &schema, nil); err != nil { + t.Fatal(err) + } + validator, _, err := validation.NewSchemaValidator(&schema) + if err != nil { + t.Fatal(err) + } + errs := validation.ValidateCustomResource(nil, object, validator) + structural, err := structuralschema.NewStructural(&schema) + if err != nil { + t.Fatal(err) + } + celErrs, _ := cel.NewValidator(structural, true, celconfig.PerCallLimit).Validate(context.Background(), nil, structural, object, old, celconfig.RuntimeCELCostBudget) + return append(errs, celErrs...) +} + +func observationObject(source map[string]any) map[string]any { + return map[string]any{"apiVersion": GroupVersion.String(), "kind": "InventoryObservation", "metadata": map[string]any{"name": "server-01"}, "spec": map[string]any{"source": source}} +} + +func TestObservationSourceIsValidatedAndImmutable(t *testing.T) { + valid := observationObject(map[string]any{"system": "NetBox", "kind": "Device", "id": int64(1234), "expectedName": "server-01.example"}) + if errs := validate(t, valid, nil); len(errs) > 0 { + t.Fatalf("valid observation rejected: %v", errs) + } + for name, source := range map[string]map[string]any{ + "unknown system": {"system": "Spreadsheet", "kind": "Device", "id": int64(1)}, + "unknown kind": {"system": "NetBox", "kind": "Cable", "id": int64(1)}, + "zero id": {"system": "NetBox", "kind": "Device", "id": int64(0)}, + "missing id": {"system": "NetBox", "kind": "Device"}, + } { + if errs := validate(t, observationObject(source), nil); len(errs) == 0 { + t.Errorf("%s accepted", name) + } + } + for name, source := range map[string]map[string]any{ + "retarget id": {"system": "NetBox", "kind": "Device", "id": int64(1235), "expectedName": "server-01.example"}, + "change name": {"system": "NetBox", "kind": "Device", "id": int64(1234), "expectedName": "server-02.example"}, + "drop name guard": {"system": "NetBox", "kind": "Device", "id": int64(1234)}, + } { + if errs := validate(t, observationObject(source), valid); len(errs) == 0 { + t.Errorf("%s accepted as an update", name) + } + } +} + +func TestObservationStatusAcceptsOnlyObservedOnlyTrust(t *testing.T) { + object := observationObject(map[string]any{"system": "NetBox", "kind": "Device", "id": int64(1)}) + object["status"] = map[string]any{"trustProfile": "ServerWitnessedBMC-v1"} + if errs := validate(t, object, nil); len(errs) == 0 { + t.Fatal("observer status claimed a stronger trust profile") + } +} + +func TestObserverRoleCanOnlyReadObservationsAndWriteTheirStatus(t *testing.T) { + var roles []rbacv1.Role + for _, document := range loadDocuments(t, "rbac.yaml") { + switch document.GetKind() { + case "ClusterRole", "ClusterRoleBinding": + t.Fatalf("observer must not hold cluster-wide RBAC: %s", document.GetName()) + case "Role": + var role rbacv1.Role + if err := runtime.DefaultUnstructuredConverter.FromUnstructured(document.Object, &role); err != nil { + t.Fatal(err) + } + roles = append(roles, role) + } + } + if len(roles) != 1 { + t.Fatalf("got %d Roles, want 1", len(roles)) + } + allowed := map[string]map[string]bool{ + "inventoryobservations": {"get": true, "list": true}, + "inventoryobservations/status": {"update": true}, + } + for _, rule := range roles[0].Rules { + if len(rule.APIGroups) != 1 || rule.APIGroups[0] != GroupVersion.Group || len(rule.ResourceNames) != 0 || len(rule.NonResourceURLs) != 0 { + t.Fatalf("unexpected rule scope: %+v", rule) + } + for _, resource := range rule.Resources { + for _, verb := range rule.Verbs { + if !allowed[resource][verb] { + t.Fatalf("observer Role grants %s on %s", verb, resource) + } + } + } + } +} diff --git a/internal/api/inventory/v1alpha1/types.go b/internal/api/inventory/v1alpha1/types.go new file mode 100644 index 00000000..d13c26c7 --- /dev/null +++ b/internal/api/inventory/v1alpha1/types.go @@ -0,0 +1,160 @@ +// Package v1alpha1 holds the observation-only inventory API in +// fleet.datumapis.com. An InventoryObservation records what an external +// inventory system reports about one physical asset. It is evidence, not a +// Device, MachineCapacity, or plan: nothing in Fleet reads it to publish supply, +// authorize hardware effects, or admit an allocation. +package v1alpha1 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var GroupVersion = schema.GroupVersion{Group: "fleet.datumapis.com", Version: "v1alpha1"} + +const ( + // SourceSystemNetBox is the only implemented external inventory system. + SourceSystemNetBox = "NetBox" + // SourceKindDevice selects a NetBox dcim device. + SourceKindDevice = "Device" + + // TrustProfileObservedOnly marks facts as attributable but unverified. It + // grants no trusted binding, free capacity, ownership, preparation, or effect. + TrustProfileObservedOnly = "ObservedOnly-v1" + + // ConditionObserved is True only when the latest refresh read the exact + // source object and its identity matched the spec. + ConditionObserved = "Observed" + + ReasonObserved = "Observed" + ReasonSourceUnavailable = "SourceUnavailable" + ReasonSourceUnauthorized = "SourceUnauthorized" + ReasonSourceObjectMissing = "SourceObjectMissing" + ReasonIdentityMismatch = "IdentityMismatch" + ReasonUnsupportedSource = "UnsupportedSource" +) + +// InventoryObservationSpec names one external object to observe. An operator +// writes it; the observer never edits spec, creates, or deletes observations. +type InventoryObservationSpec struct { + Source ObservationSource `json:"source"` +} + +// ObservationSource is immutable: retargeting an observation would let facts +// from one asset be read as another's. Create a new observation instead. +type ObservationSource struct { + System string `json:"system"` + Kind string `json:"kind"` + // ID is the stable object identifier in the source system. + ID int64 `json:"id"` + // ExpectedName guards against a mistyped ID. When set, a source object with + // a different name is reported as IdentityMismatch and its facts are not kept. + ExpectedName string `json:"expectedName,omitempty"` +} + +// InventoryObservationStatus is written only by the observer. +type InventoryObservationStatus struct { + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + TrustProfile string `json:"trustProfile,omitempty"` + LastAttemptTime *metav1.Time `json:"lastAttemptTime,omitempty"` + // ObservedAt is when the facts below were last read successfully. Facts are + // retained when a later refresh fails; the Observed condition reports that. + ObservedAt *metav1.Time `json:"observedAt,omitempty"` + SourceUpdatedAt *metav1.Time `json:"sourceUpdatedAt,omitempty"` + FactsDigest string `json:"factsDigest,omitempty"` + Facts *ObservedDeviceFacts `json:"facts,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// ObservedDeviceFacts is an allowlist of source fields. Custom fields, comments, +// config contexts, and any other free-form source data are never copied. +type ObservedDeviceFacts struct { + Name string `json:"name,omitempty"` + Manufacturer string `json:"manufacturer,omitempty"` + Model string `json:"model,omitempty"` + Serial string `json:"serial,omitempty"` + AssetTag string `json:"assetTag,omitempty"` + Role string `json:"role,omitempty"` + Status string `json:"status,omitempty"` + Placement ObservedPlacement `json:"placement,omitempty"` + Interfaces []ObservedInterface `json:"interfaces,omitempty"` + Addresses []ObservedAddress `json:"addresses,omitempty"` +} + +type ObservedPlacement struct { + Site string `json:"site,omitempty"` + Rack string `json:"rack,omitempty"` + Position string `json:"position,omitempty"` + Face string `json:"face,omitempty"` +} + +type ObservedInterface struct { + Name string `json:"name"` + Type string `json:"type,omitempty"` + // SpeedKbps is the source value unchanged. NetBox defines it in kbps; it is + // operator-entered and is not verified against the link. + SpeedKbps int64 `json:"speedKbps,omitempty"` + Enabled bool `json:"enabled"` + ManagementOnly bool `json:"managementOnly,omitempty"` + LAG string `json:"lag,omitempty"` + MACAddresses []string `json:"macAddresses,omitempty"` + Peers []ObservedPeer `json:"peers,omitempty"` +} + +// ObservedPeer is the recorded far end of a cable, not a verified path. +type ObservedPeer struct { + Kind string `json:"kind,omitempty"` + Device string `json:"device,omitempty"` + Port string `json:"port,omitempty"` +} + +// ObservedAddress is an address recorded in the source. Networking and IPAM +// remain the owners of address allocation; this is not an assignment. +type ObservedAddress struct { + Role string `json:"role"` + Address string `json:"address"` +} + +type InventoryObservation struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec InventoryObservationSpec `json:"spec"` + Status InventoryObservationStatus `json:"status,omitempty"` +} + +type InventoryObservationList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []InventoryObservation `json:"items"` +} + +func addKnown(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &InventoryObservation{}, &InventoryObservationList{}) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} + +var AddToScheme = addKnown + +func (in *InventoryObservation) DeepCopyObject() runtime.Object { + out := new(InventoryObservation) + deepCopy(in, out) + return out +} + +func (in *InventoryObservation) DeepCopy() *InventoryObservation { + out := new(InventoryObservation) + deepCopy(in, out) + return out +} + +func (in *InventoryObservationList) DeepCopyObject() runtime.Object { + out := new(InventoryObservationList) + deepCopy(in, out) + return out +} + +func deepCopy[T any](in *T, out *T) { b, _ := json.Marshal(in); _ = json.Unmarshal(b, out) } diff --git a/internal/inventoryobserver/envtest_test.go b/internal/inventoryobserver/envtest_test.go new file mode 100644 index 00000000..d09f5ef9 --- /dev/null +++ b/internal/inventoryobserver/envtest_test.go @@ -0,0 +1,165 @@ +package inventoryobserver + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "testing" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/util/yaml" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" + + inventoryv1 "go.datum.net/fleet/internal/api/inventory/v1alpha1" +) + +var observerRoot = filepath.Join("..", "..", "config", "inventory-observer") + +// TestObserverAgainstAPIServer runs the observer as its packaged service +// account against a real API server: the CRD's validation, the status +// subresource, and the packaged Role all apply as they would in a cluster. +func TestObserverAgainstAPIServer(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS is not set") + } + env := &envtest.Environment{CRDInstallOptions: envtest.CRDInstallOptions{Paths: []string{filepath.Join(observerRoot, "crd.yaml")}}, ErrorIfCRDPathMissing: true} + cfg, err := env.Start() + if err != nil { + t.Fatalf("start envtest: %v", err) + } + t.Cleanup(func() { _ = env.Stop() }) + + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{clientgoscheme.AddToScheme, inventoryv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + ctx := context.Background() + admin, err := client.New(cfg, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + for _, name := range []string{namespace, "other"} { + if err := admin.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: name}}); err != nil { + t.Fatal(err) + } + } + for _, object := range packagedRBAC(t) { + if err := admin.Create(ctx, object); err != nil { + t.Fatalf("create %s %s: %v", object.GetKind(), object.GetName(), err) + } + } + if err := admin.Create(ctx, observation("server-01", 1234, "server-01.rack-01.example")); err != nil { + t.Fatal(err) + } + other := observation("elsewhere", 1234, "") + other.Namespace = "other" + if err := admin.Create(ctx, other); err != nil { + t.Fatal(err) + } + + user, err := env.AddUser(envtest.User{Name: "system:serviceaccount:fleet-system:fleet-inventory-observer"}, nil) + if err != nil { + t.Fatal(err) + } + observerClient, err := client.New(user.Config(), client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + + results, err := (&Observer{Client: observerClient, Namespace: namespace, NetBox: syntheticSource()}).RefreshAll(ctx) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 || !results[0].Succeeded() { + t.Fatalf("results = %+v", results) + } + stored := get(t, admin, "server-01") + if stored.Status.Facts == nil || stored.Status.Facts.Serial != "SYNTHETIC-0001" || stored.Status.TrustProfile != inventoryv1.TrustProfileObservedOnly { + t.Fatalf("status not persisted: %+v", stored.Status) + } + + t.Run("observer cannot create, delete, or edit spec", func(t *testing.T) { + if err := observerClient.Create(ctx, observation("created-by-observer", 1, "")); !apierrors.IsForbidden(err) { + t.Errorf("create err = %v, want Forbidden", err) + } + if err := observerClient.Delete(ctx, stored.DeepCopy()); !apierrors.IsForbidden(err) { + t.Errorf("delete err = %v, want Forbidden", err) + } + edited := stored.DeepCopy() + edited.Labels = map[string]string{"example": "observer"} + if err := observerClient.Update(ctx, edited); !apierrors.IsForbidden(err) { + t.Errorf("spec/metadata update err = %v, want Forbidden", err) + } + }) + + t.Run("observer cannot read outside its namespace or other kinds", func(t *testing.T) { + var list inventoryv1.InventoryObservationList + if err := observerClient.List(ctx, &list, client.InNamespace("other")); !apierrors.IsForbidden(err) { + t.Errorf("list other namespace err = %v, want Forbidden", err) + } + var secrets corev1.SecretList + if err := observerClient.List(ctx, &secrets, client.InNamespace(namespace)); !apierrors.IsForbidden(err) { + t.Errorf("list secrets err = %v, want Forbidden", err) + } + }) + + t.Run("source identity is immutable", func(t *testing.T) { + retarget := get(t, admin, "server-01") + retarget.Spec.Source.ID = 1235 + if err := admin.Update(ctx, retarget); !apierrors.IsInvalid(err) { + t.Errorf("retarget err = %v, want Invalid", err) + } + }) + + t.Run("status write with a stale resourceVersion conflicts", func(t *testing.T) { + stale := get(t, admin, "server-01") + fresh := stale.DeepCopy() + fresh.Labels = map[string]string{"example": "concurrent"} + if err := admin.Update(ctx, fresh); err != nil { + t.Fatal(err) + } + result := (&Observer{Client: observerClient, Namespace: namespace, NetBox: syntheticSource()}).refresh(ctx, stale) + if !apierrors.IsConflict(result.WriteErr) { + t.Errorf("stale status write err = %v, want Conflict", result.WriteErr) + } + }) + + t.Run("status cannot claim a stronger trust profile", func(t *testing.T) { + current := get(t, admin, "server-01") + current.Status.TrustProfile = "ServerWitnessedBMC-v1" + if err := observerClient.Status().Update(ctx, current); !apierrors.IsInvalid(err) { + t.Errorf("trust escalation err = %v, want Invalid", err) + } + }) +} + +func packagedRBAC(t *testing.T) []*unstructured.Unstructured { + t.Helper() + data, err := os.ReadFile(filepath.Join(observerRoot, "rbac.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + var out []*unstructured.Unstructured + for { + var object map[string]any + if err := decoder.Decode(&object); err == io.EOF { + return out + } else if err != nil { + t.Fatal(err) + } + if object != nil { + out = append(out, &unstructured.Unstructured{Object: object}) + } + } +} diff --git a/internal/inventoryobserver/observer.go b/internal/inventoryobserver/observer.go new file mode 100644 index 00000000..704c716b --- /dev/null +++ b/internal/inventoryobserver/observer.go @@ -0,0 +1,295 @@ +// Package inventoryobserver refreshes InventoryObservation status from an +// external inventory system. It is the sole status writer for those objects. It +// never creates, deletes, or edits the spec of any object, and it writes no +// other kind: observations confer no supply, trust, or authority on hardware. +package inventoryobserver + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net" + "sort" + "strconv" + "strings" + "time" + + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + + inventoryv1 "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/netbox" +) + +// Source is the read-only subset of the NetBox client the observer uses. +type Source interface { + Device(ctx context.Context, id int64) (*netbox.Device, error) + Interfaces(ctx context.Context, deviceID int64) ([]netbox.Interface, error) +} + +type Observer struct { + Client client.Client + Namespace string + NetBox Source + Now func() time.Time + + // rejected stops contact with the source for the rest of a run after it + // rejects the credential. Sources commonly ban clients that repeat failed + // authentication, and a ban would also block every other client sharing + // the observer's egress address. + rejected bool +} + +// Result reports one observation's refresh. Reason is the Observed condition +// reason written; WriteErr is set when that status could not be persisted. +type Result struct { + Name string + Reason string + Message string + WriteErr error +} + +// Succeeded reports whether the observation now holds a current, matching read. +func (r Result) Succeeded() bool { return r.WriteErr == nil && r.Reason == inventoryv1.ReasonObserved } + +// RefreshAll refreshes every NetBox observation in the namespace. A failure for +// one observation is recorded in its status and does not stop the others. +func (o *Observer) RefreshAll(ctx context.Context) ([]Result, error) { + if o.Client == nil || o.NetBox == nil || o.Namespace == "" { + return nil, errors.New("observer requires a client, a source, and a namespace") + } + var list inventoryv1.InventoryObservationList + if err := o.Client.List(ctx, &list, client.InNamespace(o.Namespace)); err != nil { + return nil, fmt.Errorf("list inventory observations: %w", err) + } + sort.Slice(list.Items, func(i, j int) bool { return list.Items[i].Name < list.Items[j].Name }) + o.rejected = false + results := make([]Result, 0, len(list.Items)) + for i := range list.Items { + results = append(results, o.refresh(ctx, &list.Items[i])) + } + return results, nil +} + +func (o *Observer) now() time.Time { + if o.Now != nil { + return o.Now().UTC() + } + return time.Now().UTC() +} + +func (o *Observer) refresh(ctx context.Context, observation *inventoryv1.InventoryObservation) Result { + now := metav1.NewTime(o.now().Truncate(time.Second)) + status := observation.DeepCopy().Status + status.TrustProfile = inventoryv1.TrustProfileObservedOnly + status.ObservedGeneration = observation.Generation + status.LastAttemptTime = &now + + reason, message := o.observe(ctx, observation, &status, now) + apimeta.SetStatusCondition(&status.Conditions, metav1.Condition{ + Type: inventoryv1.ConditionObserved, + Status: conditionStatus(reason == inventoryv1.ReasonObserved), + Reason: reason, + Message: message, + ObservedGeneration: observation.Generation, + LastTransitionTime: now, + }) + observation.Status = status + result := Result{Name: observation.Name, Reason: reason, Message: message} + // Update carries the listed resourceVersion: a concurrent spec or status + // change makes this write fail instead of overwriting newer state. + if err := o.Client.Status().Update(ctx, observation); err != nil { + result.WriteErr = err + } + return result +} + +func (o *Observer) observe(ctx context.Context, observation *inventoryv1.InventoryObservation, status *inventoryv1.InventoryObservationStatus, now metav1.Time) (string, string) { + source := observation.Spec.Source + if source.System != inventoryv1.SourceSystemNetBox || source.Kind != inventoryv1.SourceKindDevice { + return inventoryv1.ReasonUnsupportedSource, fmt.Sprintf("source %s/%s is not supported by this observer", source.System, source.Kind) + } + if o.rejected { + return inventoryv1.ReasonSourceUnauthorized, "source not contacted: it rejected the observer credential earlier in this run; previously observed facts are retained" + } + device, err := o.NetBox.Device(ctx, source.ID) + if err != nil { + return o.sourceFailure(err) + } + if source.ExpectedName != "" && device.Name != source.ExpectedName { + return inventoryv1.ReasonIdentityMismatch, fmt.Sprintf("source object %d is named %q, expected %q; facts were not updated", source.ID, device.Name, source.ExpectedName) + } + if previous := status.Facts; previous != nil && previous.Serial != "" && device.Serial != previous.Serial { + return inventoryv1.ReasonIdentityMismatch, fmt.Sprintf("source object %d now reports a different serial than previously observed; facts were not updated, create a new observation for replaced hardware", source.ID) + } + interfaces, err := o.NetBox.Interfaces(ctx, source.ID) + if err != nil { + return o.sourceFailure(err) + } + facts := Normalize(device, interfaces) + digest, err := Digest(facts) + if err != nil { + return inventoryv1.ReasonSourceUnavailable, "normalize source facts: " + err.Error() + } + status.Facts = facts + status.FactsDigest = digest + status.ObservedAt = &now + status.SourceUpdatedAt = nil + if device.LastUpdated != nil { + updated := metav1.NewTime(device.LastUpdated.UTC()) + status.SourceUpdatedAt = &updated + } + return inventoryv1.ReasonObserved, "read the source object; facts are observed, not verified" +} + +func (o *Observer) sourceFailure(err error) (string, string) { + if errors.Is(err, netbox.ErrUnauthorized) { + o.rejected = true + } + switch { + case errors.Is(err, netbox.ErrNotFound): + return inventoryv1.ReasonSourceObjectMissing, "source object was not found; previously observed facts are retained" + case errors.Is(err, netbox.ErrUnauthorized): + return inventoryv1.ReasonSourceUnauthorized, "source rejected the observer credential; previously observed facts are retained" + default: + return inventoryv1.ReasonSourceUnavailable, "source read failed; previously observed facts are retained: " + err.Error() + } +} + +func conditionStatus(ok bool) metav1.ConditionStatus { + if ok { + return metav1.ConditionTrue + } + return metav1.ConditionFalse +} + +// Normalize converts allowlisted NetBox fields into deterministic facts. +func Normalize(device *netbox.Device, interfaces []netbox.Interface) *inventoryv1.ObservedDeviceFacts { + facts := &inventoryv1.ObservedDeviceFacts{ + Name: device.Name, + Manufacturer: device.DeviceType.Manufacturer.Name, + Model: device.DeviceType.Model, + Serial: strings.TrimSpace(device.Serial), + Role: nameOf(device.Role), + Status: valueOf(device.Status), + Placement: inventoryv1.ObservedPlacement{ + Site: slugOf(device.Site), + Rack: nameOf(device.Rack), + Face: valueOf(device.Face), + }, + } + if device.AssetTag != nil { + facts.AssetTag = strings.TrimSpace(*device.AssetTag) + } + if device.Position != nil { + facts.Placement.Position = strconv.FormatFloat(*device.Position, 'f', -1, 64) + } + addAddress := func(role string, value string) { + if value != "" { + facts.Addresses = append(facts.Addresses, inventoryv1.ObservedAddress{Role: role, Address: value}) + } + } + if device.PrimaryIP4 != nil { + addAddress("PrimaryIPv4", device.PrimaryIP4.Address) + } + if device.PrimaryIP6 != nil { + addAddress("PrimaryIPv6", device.PrimaryIP6.Address) + } + if device.OOBIP != nil { + addAddress("OutOfBand", device.OOBIP.Address) + } + for _, source := range interfaces { + observed := inventoryv1.ObservedInterface{ + Name: source.Name, + Type: valueOf(source.Type), + Enabled: source.Enabled, + ManagementOnly: source.MgmtOnly, + LAG: nameOf(source.LAG), + MACAddresses: macAddresses(source), + } + if source.Speed != nil { + observed.SpeedKbps = *source.Speed + } + for _, peer := range source.LinkPeers { + port := peer.Name + if port == "" { + port = peer.Display + } + observed.Peers = append(observed.Peers, inventoryv1.ObservedPeer{Kind: source.LinkPeersType, Device: nameOf(peer.Device), Port: port}) + } + sort.Slice(observed.Peers, func(i, j int) bool { + if observed.Peers[i].Device != observed.Peers[j].Device { + return observed.Peers[i].Device < observed.Peers[j].Device + } + return observed.Peers[i].Port < observed.Peers[j].Port + }) + facts.Interfaces = append(facts.Interfaces, observed) + } + sort.Slice(facts.Interfaces, func(i, j int) bool { return facts.Interfaces[i].Name < facts.Interfaces[j].Name }) + return facts +} + +func macAddresses(source netbox.Interface) []string { + seen := map[string]bool{} + add := func(value string) { + if parsed, err := net.ParseMAC(strings.TrimSpace(value)); err == nil && len(parsed) == 6 { + seen[parsed.String()] = true + } + } + if source.MACAddress != nil { + add(*source.MACAddress) + } + if source.PrimaryMAC != nil { + add(source.PrimaryMAC.MACAddress) + } + for _, entry := range source.MACAddresses { + add(entry.MACAddress) + } + out := make([]string, 0, len(seen)) + for value := range seen { + out = append(out, value) + } + sort.Strings(out) + if len(out) == 0 { + return nil + } + return out +} + +// Digest is a stable content digest of normalized facts. +func Digest(facts *inventoryv1.ObservedDeviceFacts) (string, error) { + encoded, err := json.Marshal(facts) + if err != nil { + return "", err + } + sum := sha256.Sum256(encoded) + return "sha256:" + hex.EncodeToString(sum[:]), nil +} + +func nameOf(ref *netbox.Ref) string { + if ref == nil { + return "" + } + return ref.Name +} + +func slugOf(ref *netbox.Ref) string { + if ref == nil { + return "" + } + if ref.Slug != "" { + return ref.Slug + } + return ref.Name +} + +func valueOf(ref *netbox.Ref) string { + if ref == nil { + return "" + } + return ref.Value +} diff --git a/internal/inventoryobserver/observer_test.go b/internal/inventoryobserver/observer_test.go new file mode 100644 index 00000000..80bc363a --- /dev/null +++ b/internal/inventoryobserver/observer_test.go @@ -0,0 +1,397 @@ +package inventoryobserver + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync" + "testing" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + inventoryv1 "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.datum.net/fleet/internal/netbox" +) + +const namespace = "fleet-system" + +type stubSource struct { + mu sync.Mutex + devices map[int64]*netbox.Device + interfaces map[int64][]netbox.Interface + deviceErr error + ifaceErr error + calls int +} + +func (s *stubSource) Device(_ context.Context, id int64) (*netbox.Device, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.calls++ + if s.deviceErr != nil { + return nil, s.deviceErr + } + device, ok := s.devices[id] + if !ok { + return nil, netbox.ErrNotFound + } + copied := *device + return &copied, nil +} + +func (s *stubSource) Interfaces(_ context.Context, id int64) ([]netbox.Interface, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.ifaceErr != nil { + return nil, s.ifaceErr + } + return s.interfaces[id], nil +} + +func ptr[T any](v T) *T { return &v } + +func syntheticSource() *stubSource { + updated := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + device := &netbox.Device{ID: 1234, Name: "server-01.rack-01.example", Serial: "SYNTHETIC-0001", Position: ptr(12.0), LastUpdated: &updated} + device.DeviceType.Model = "Example 1U" + device.DeviceType.Manufacturer = netbox.Ref{Name: "Example Vendor"} + device.Role = &netbox.Ref{Name: "Compute"} + device.Site = &netbox.Ref{Name: "Example Site", Slug: "example-site"} + device.Rack = &netbox.Ref{Name: "rack-01.example"} + device.Face = &netbox.Ref{Value: "front"} + device.Status = &netbox.Ref{Value: "active"} + device.PrimaryIP4 = &netbox.IPRef{Address: "192.0.2.10/28"} + var iface netbox.Interface + _ = json.Unmarshal([]byte(`{"name":"eth1","type":{"value":"25gbase-x-sfp28"},"speed":25000000,"enabled":true,"lag":{"name":"bond0"}, + "mac_address":"00:00:5E:00:53:01","mac_addresses":[{"mac_address":"00:00:5e:00:53:01"},{"mac_address":"00:00:5e:00:53:02"},{"mac_address":"not-a-mac"}], + "link_peers_type":"dcim.interface","link_peers":[{"name":"Ethernet1/1","device":{"name":"switch-02.example"}},{"name":"Ethernet1/1","device":{"name":"switch-01.example"}}]}`), &iface) + mgmt := netbox.Interface{Name: "bmc0", Enabled: true} + return &stubSource{devices: map[int64]*netbox.Device{1234: device}, interfaces: map[int64][]netbox.Interface{1234: {iface, mgmt}}} +} + +func observation(name string, id int64, expectedName string) *inventoryv1.InventoryObservation { + return &inventoryv1.InventoryObservation{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace, Generation: 1}, + Spec: inventoryv1.InventoryObservationSpec{Source: inventoryv1.ObservationSource{System: inventoryv1.SourceSystemNetBox, Kind: inventoryv1.SourceKindDevice, ID: id, ExpectedName: expectedName}}, + } +} + +type recorder struct { + mu sync.Mutex + writes []string +} + +func (r *recorder) add(op string, obj client.Object) { + r.mu.Lock() + defer r.mu.Unlock() + r.writes = append(r.writes, op+" "+obj.GetName()) +} + +func newClient(t *testing.T, rec *recorder, funcs interceptor.Funcs, objects ...client.Object) client.Client { + t.Helper() + scheme := runtime.NewScheme() + if err := inventoryv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + base := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&inventoryv1.InventoryObservation{}).WithObjects(objects...).Build() + record := interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + rec.add("create", obj) + return c.Create(ctx, obj, opts...) + }, + Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + rec.add("update", obj) + return c.Update(ctx, obj, opts...) + }, + Patch: func(ctx context.Context, c client.WithWatch, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { + rec.add("patch", obj) + return c.Patch(ctx, obj, patch, opts...) + }, + Delete: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.DeleteOption) error { + rec.add("delete", obj) + return c.Delete(ctx, obj, opts...) + }, + SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + rec.add(sub+"-update", obj) + if funcs.SubResourceUpdate != nil { + return funcs.SubResourceUpdate(ctx, c, sub, obj, opts...) + } + return c.SubResource(sub).Update(ctx, obj, opts...) + }, + } + return interceptor.NewClient(base, record) +} + +func get(t *testing.T, c client.Client, name string) *inventoryv1.InventoryObservation { + t.Helper() + var out inventoryv1.InventoryObservation + if err := c.Get(context.Background(), client.ObjectKey{Namespace: namespace, Name: name}, &out); err != nil { + t.Fatal(err) + } + return &out +} + +func observed(t *testing.T, obs *inventoryv1.InventoryObservation) *metav1.Condition { + t.Helper() + condition := apimeta.FindStatusCondition(obs.Status.Conditions, inventoryv1.ConditionObserved) + if condition == nil { + t.Fatal("Observed condition missing") + } + return condition +} + +func clock(at time.Time) func() time.Time { return func() time.Time { return at } } + +func TestRefreshRecordsObservedOnlyFactsAndWritesOnlyStatus(t *testing.T) { + rec := &recorder{} + c := newClient(t, rec, interceptor.Funcs{}, observation("server-01", 1234, "server-01.rack-01.example")) + now := time.Date(2026, 2, 3, 4, 5, 6, 0, time.UTC) + results, err := (&Observer{Client: c, Namespace: namespace, NetBox: syntheticSource(), Now: clock(now)}).RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 || !results[0].Succeeded() { + t.Fatalf("results = %+v", results) + } + if strings.Join(rec.writes, ",") != "status-update server-01" { + t.Fatalf("observer writes = %v, want only one status update", rec.writes) + } + obs := get(t, c, "server-01") + if condition := observed(t, obs); condition.Status != metav1.ConditionTrue || condition.ObservedGeneration != 1 { + t.Fatalf("condition = %+v", condition) + } + if obs.Status.TrustProfile != inventoryv1.TrustProfileObservedOnly || !obs.Status.ObservedAt.Time.Equal(now) || obs.Status.SourceUpdatedAt == nil || !strings.HasPrefix(obs.Status.FactsDigest, "sha256:") { + t.Fatalf("status = %+v", obs.Status) + } + facts := obs.Status.Facts + if facts.Serial != "SYNTHETIC-0001" || facts.Placement.Site != "example-site" || facts.Placement.Position != "12" || facts.Manufacturer != "Example Vendor" { + t.Fatalf("facts = %+v", facts) + } + if len(facts.Interfaces) != 2 || facts.Interfaces[0].Name != "bmc0" { + t.Fatalf("interfaces not sorted: %+v", facts.Interfaces) + } + eth := facts.Interfaces[1] + if eth.SpeedKbps != 25000000 || eth.LAG != "bond0" || strings.Join(eth.MACAddresses, ",") != "00:00:5e:00:53:01,00:00:5e:00:53:02" { + t.Fatalf("interface = %+v", eth) + } + if len(eth.Peers) != 2 || eth.Peers[0].Device != "switch-01.example" || eth.Peers[0].Kind != "dcim.interface" { + t.Fatalf("peers = %+v", eth.Peers) + } + if len(facts.Addresses) != 1 || facts.Addresses[0].Role != "PrimaryIPv4" { + t.Fatalf("addresses = %+v", facts.Addresses) + } + if obs.Spec.Source.ID != 1234 || obs.Spec.Source.ExpectedName != "server-01.rack-01.example" { + t.Fatalf("spec changed: %+v", obs.Spec) + } +} + +func TestRefreshIsDeterministic(t *testing.T) { + c := newClient(t, &recorder{}, interceptor.Funcs{}, observation("server-01", 1234, "")) + observer := &Observer{Client: c, Namespace: namespace, NetBox: syntheticSource(), Now: clock(time.Unix(100, 0))} + if _, err := observer.RefreshAll(context.Background()); err != nil { + t.Fatal(err) + } + first := get(t, c, "server-01").Status.FactsDigest + observer.Now = clock(time.Unix(200, 0)) + if _, err := observer.RefreshAll(context.Background()); err != nil { + t.Fatal(err) + } + obs := get(t, c, "server-01") + if obs.Status.FactsDigest != first || !obs.Status.ObservedAt.Time.Equal(time.Unix(200, 0)) { + t.Fatalf("digest %s -> %s, observedAt %v", first, obs.Status.FactsDigest, obs.Status.ObservedAt) + } +} + +func TestSourceFailuresRetainPreviousFactsAndNeverReportObserved(t *testing.T) { + for name, tc := range map[string]struct { + deviceErr, ifaceErr error + reason string + }{ + "unavailable": {deviceErr: netbox.ErrUnavailable, reason: inventoryv1.ReasonSourceUnavailable}, + "unauthorized": {deviceErr: netbox.ErrUnauthorized, reason: inventoryv1.ReasonSourceUnauthorized}, + "missing": {deviceErr: netbox.ErrNotFound, reason: inventoryv1.ReasonSourceObjectMissing}, + "interfaces failed": {ifaceErr: errors.New("synthetic timeout"), reason: inventoryv1.ReasonSourceUnavailable}, + } { + t.Run(name, func(t *testing.T) { + c := newClient(t, &recorder{}, interceptor.Funcs{}, observation("server-01", 1234, "")) + source := syntheticSource() + observer := &Observer{Client: c, Namespace: namespace, NetBox: source, Now: clock(time.Unix(100, 0))} + if _, err := observer.RefreshAll(context.Background()); err != nil { + t.Fatal(err) + } + before := get(t, c, "server-01").Status + source.deviceErr, source.ifaceErr = tc.deviceErr, tc.ifaceErr + observer.Now = clock(time.Unix(200, 0)) + results, err := observer.RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if results[0].Succeeded() || results[0].Reason != tc.reason { + t.Fatalf("result = %+v", results[0]) + } + after := get(t, c, "server-01") + if condition := observed(t, after); condition.Status != metav1.ConditionFalse || condition.Reason != tc.reason { + t.Fatalf("condition = %+v", condition) + } + if after.Status.FactsDigest != before.FactsDigest || !after.Status.ObservedAt.Equal(before.ObservedAt) || !after.Status.LastAttemptTime.Time.Equal(time.Unix(200, 0)) { + t.Fatalf("failure changed retained facts or attempt time: %+v", after.Status) + } + }) + } +} + +func TestExpectedNameMismatchDoesNotRecordFacts(t *testing.T) { + c := newClient(t, &recorder{}, interceptor.Funcs{}, observation("server-01", 1234, "server-02.rack-01.example")) + results, err := (&Observer{Client: c, Namespace: namespace, NetBox: syntheticSource()}).RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if results[0].Reason != inventoryv1.ReasonIdentityMismatch { + t.Fatalf("result = %+v", results[0]) + } + if obs := get(t, c, "server-01"); obs.Status.Facts != nil || obs.Status.ObservedAt != nil { + t.Fatalf("mismatched object recorded facts: %+v", obs.Status) + } +} + +func TestSerialChangeIsIdentityMismatchNotAnUpdate(t *testing.T) { + c := newClient(t, &recorder{}, interceptor.Funcs{}, observation("server-01", 1234, "")) + source := syntheticSource() + observer := &Observer{Client: c, Namespace: namespace, NetBox: source} + if _, err := observer.RefreshAll(context.Background()); err != nil { + t.Fatal(err) + } + source.devices[1234].Serial = "SYNTHETIC-0002" + results, err := observer.RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if results[0].Reason != inventoryv1.ReasonIdentityMismatch { + t.Fatalf("result = %+v", results[0]) + } + if got := get(t, c, "server-01").Status.Facts.Serial; got != "SYNTHETIC-0001" { + t.Fatalf("serial replaced with %q", got) + } +} + +func TestConflictingStatusWriteDoesNotOverwriteNewerState(t *testing.T) { + conflict := interceptor.Funcs{SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, opts ...client.SubResourceUpdateOption) error { + return apierrors.NewConflict(schema.GroupResource{Group: inventoryv1.GroupVersion.Group, Resource: "inventoryobservations"}, obj.GetName(), errors.New("synthetic concurrent write")) + }} + c := newClient(t, &recorder{}, conflict, observation("server-01", 1234, "")) + results, err := (&Observer{Client: c, Namespace: namespace, NetBox: syntheticSource()}).RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if results[0].Succeeded() || !apierrors.IsConflict(results[0].WriteErr) { + t.Fatalf("result = %+v", results[0]) + } + if obs := get(t, c, "server-01"); obs.Status.Facts != nil { + t.Fatal("conflicting write was persisted") + } +} + +func TestStaleResourceVersionIsRejected(t *testing.T) { + c := newClient(t, &recorder{}, interceptor.Funcs{}, observation("server-01", 1234, "")) + stale := get(t, c, "server-01") + fresh := stale.DeepCopy() + fresh.Labels = map[string]string{"example": "concurrent"} + if err := c.Update(context.Background(), fresh); err != nil { + t.Fatal(err) + } + result := (&Observer{Client: c, Namespace: namespace, NetBox: syntheticSource()}).refresh(context.Background(), stale) + if !apierrors.IsConflict(result.WriteErr) { + t.Fatalf("stale write err = %v, want conflict", result.WriteErr) + } +} + +func TestOneFailureDoesNotBlockOtherObservations(t *testing.T) { + c := newClient(t, &recorder{}, interceptor.Funcs{}, observation("a-missing", 999, ""), observation("b-present", 1234, "")) + results, err := (&Observer{Client: c, Namespace: namespace, NetBox: syntheticSource()}).RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(results) != 2 || results[0].Reason != inventoryv1.ReasonSourceObjectMissing || !results[1].Succeeded() { + t.Fatalf("results = %+v", results) + } +} + +func TestOtherNamespacesAreIgnored(t *testing.T) { + other := observation("elsewhere", 1234, "") + other.Namespace = "other" + rec := &recorder{} + c := newClient(t, rec, interceptor.Funcs{}, other) + source := syntheticSource() + results, err := (&Observer{Client: c, Namespace: namespace, NetBox: source}).RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if len(results) != 0 || len(rec.writes) != 0 || source.calls != 0 { + t.Fatalf("results=%v writes=%v calls=%d", results, rec.writes, source.calls) + } +} + +func TestUnsupportedSourceDoesNotReadNetBox(t *testing.T) { + obs := observation("server-01", 1234, "") + obs.Spec.Source.Kind = "Rack" + source := syntheticSource() + c := newClient(t, &recorder{}, interceptor.Funcs{}, obs) + results, err := (&Observer{Client: c, Namespace: namespace, NetBox: source}).RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if results[0].Reason != inventoryv1.ReasonUnsupportedSource || source.calls != 0 { + t.Fatalf("result=%+v calls=%d", results[0], source.calls) + } +} + +func TestFactsNeverCarryFreeFormSourceData(t *testing.T) { + var device netbox.Device + raw := `{"id":1,"name":"server-01","serial":"SYNTHETIC-0001","custom_fields":{"oob_password":"synthetic-sentinel"},"comments":"synthetic-sentinel","config_context":{"k":"synthetic-sentinel"},"local_context_data":{"k":"synthetic-sentinel"}}` + if err := json.Unmarshal([]byte(raw), &device); err != nil { + t.Fatal(err) + } + encoded, err := json.Marshal(Normalize(&device, nil)) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), "synthetic-sentinel") { + t.Fatalf("free-form source data leaked into facts: %s", encoded) + } +} + +func TestRejectedCredentialStopsContactForTheRestOfTheRun(t *testing.T) { + c := newClient(t, &recorder{}, interceptor.Funcs{}, observation("a", 1234, ""), observation("b", 1234, ""), observation("c", 1234, "")) + source := syntheticSource() + source.deviceErr = netbox.ErrUnauthorized + observer := &Observer{Client: c, Namespace: namespace, NetBox: source} + results, err := observer.RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if source.calls != 1 { + t.Fatalf("source contacted %d times after rejecting the credential, want 1", source.calls) + } + for _, result := range results { + if result.Reason != inventoryv1.ReasonSourceUnauthorized || result.WriteErr != nil { + t.Fatalf("result = %+v", result) + } + } + source.deviceErr = nil + results, err = observer.RefreshAll(context.Background()) + if err != nil { + t.Fatal(err) + } + if source.calls != 4 || !results[0].Succeeded() || !results[2].Succeeded() { + t.Fatalf("next run did not retry: calls=%d results=%+v", source.calls, results) + } +} diff --git a/internal/netbox/client.go b/internal/netbox/client.go new file mode 100644 index 00000000..c3f6349f --- /dev/null +++ b/internal/netbox/client.go @@ -0,0 +1,229 @@ +// Package netbox is a read-only NetBox REST client for the inventory observer. +// It issues GET requests only, decodes an allowlist of device and interface +// fields, and never follows server-supplied URLs, so the API token is sent only +// to the configured origin. +package netbox + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +var ( + ErrNotFound = errors.New("netbox object not found") + ErrUnauthorized = errors.New("netbox rejected the credential") + ErrUnavailable = errors.New("netbox unavailable") +) + +const ( + maxBodyBytes = 4 << 20 + pageSize = 200 + maxInterfaces = 2000 +) + +// Client reads one NetBox origin. Token is called for every request so a +// rotated credential file takes effect without restarting the process. +type Client struct { + base *url.URL + token func() (string, error) + http *http.Client +} + +// NewClient validates the origin. HTTPS is required except for loopback hosts, +// which exist only for tests and local development. +func NewClient(origin string, token func() (string, error), httpClient *http.Client) (*Client, error) { + parsed, err := url.Parse(strings.TrimSpace(origin)) + if err != nil || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { + return nil, fmt.Errorf("netbox origin must be an absolute URL without credentials, query, or fragment") + } + if parsed.Scheme != "https" && !(parsed.Scheme == "http" && loopback(parsed.Hostname())) { + return nil, fmt.Errorf("netbox origin must use https") + } + parsed.Path = strings.TrimSuffix(strings.TrimSuffix(parsed.Path, "/"), "/api") + if token == nil { + return nil, fmt.Errorf("netbox token source is required") + } + if httpClient == nil { + httpClient = &http.Client{Timeout: 30 * time.Second} + } + copied := *httpClient + copied.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &Client{base: parsed, token: token, http: &copied}, nil +} + +func loopback(host string) bool { + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +// Ref is a nested NetBox object or choice reference. +type Ref struct { + Name string `json:"name"` + Slug string `json:"slug"` + Value string `json:"value"` +} + +// IPRef is a nested NetBox IP address reference. +type IPRef struct { + Address string `json:"address"` +} + +// Device is the allowlisted subset of a NetBox dcim device. +type Device struct { + ID int64 `json:"id"` + Name string `json:"name"` + Serial string `json:"serial"` + AssetTag *string `json:"asset_tag"` + Position *float64 `json:"position"` + DeviceType struct { + Model string `json:"model"` + Manufacturer Ref `json:"manufacturer"` + } `json:"device_type"` + Role *Ref `json:"role"` + Site *Ref `json:"site"` + Rack *Ref `json:"rack"` + Face *Ref `json:"face"` + Status *Ref `json:"status"` + PrimaryIP4 *IPRef `json:"primary_ip4"` + PrimaryIP6 *IPRef `json:"primary_ip6"` + OOBIP *IPRef `json:"oob_ip"` + LastUpdated *time.Time `json:"last_updated"` +} + +// Interface is the allowlisted subset of a NetBox dcim interface. +type Interface struct { + ID int64 `json:"id"` + Name string `json:"name"` + Type *Ref `json:"type"` + Speed *int64 `json:"speed"` + Enabled bool `json:"enabled"` + MgmtOnly bool `json:"mgmt_only"` + LAG *Ref `json:"lag"` + // MACAddress is the pre-4.2 field; MACAddresses and PrimaryMAC replace it. + MACAddress *string `json:"mac_address"` + MACAddresses []struct { + MACAddress string `json:"mac_address"` + } `json:"mac_addresses"` + PrimaryMAC *struct { + MACAddress string `json:"mac_address"` + } `json:"primary_mac_address"` + LinkPeersType string `json:"link_peers_type"` + LinkPeers []struct { + Name string `json:"name"` + Display string `json:"display"` + Device *Ref `json:"device"` + } `json:"link_peers"` +} + +// Device reads one device by its stable NetBox ID. +func (c *Client) Device(ctx context.Context, id int64) (*Device, error) { + if id <= 0 { + return nil, fmt.Errorf("netbox device id must be positive") + } + var device Device + if err := c.get(ctx, "dcim/devices/"+strconv.FormatInt(id, 10)+"/", nil, &device); err != nil { + return nil, err + } + if device.ID != id { + return nil, fmt.Errorf("%w: response names device %d, requested %d", ErrUnavailable, device.ID, id) + } + return &device, nil +} + +// Interfaces reads every interface of one device using offset pagination it +// computes itself; the response's next URL is never followed. +func (c *Client) Interfaces(ctx context.Context, deviceID int64) ([]Interface, error) { + var out []Interface + for offset := 0; ; offset += pageSize { + var page struct { + Count int `json:"count"` + Results []Interface `json:"results"` + } + query := url.Values{"device_id": {strconv.FormatInt(deviceID, 10)}, "limit": {strconv.Itoa(pageSize)}, "offset": {strconv.Itoa(offset)}, "ordering": {"name"}} + if err := c.get(ctx, "dcim/interfaces/", query, &page); err != nil { + return nil, err + } + if page.Count > maxInterfaces { + return nil, fmt.Errorf("%w: device reports %d interfaces, above the %d limit", ErrUnavailable, page.Count, maxInterfaces) + } + out = append(out, page.Results...) + if len(page.Results) == 0 || len(out) >= page.Count { + if len(out) != page.Count { + return nil, fmt.Errorf("%w: interface count changed during pagination", ErrUnavailable) + } + return out, nil + } + } +} + +func (c *Client) get(ctx context.Context, path string, query url.Values, into any) error { + token, err := c.token() + if err != nil { + return fmt.Errorf("read netbox token: %w", err) + } + token = strings.TrimSpace(token) + if token == "" { + return fmt.Errorf("%w: empty token", ErrUnauthorized) + } + target := *c.base + target.Path = target.Path + "/api/" + path + target.RawQuery = query.Encode() + request, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil) + if err != nil { + return err + } + scheme := "Token" + if strings.HasPrefix(token, "nbt_") { + scheme = "Bearer" + } + request.Header.Set("Authorization", scheme+" "+token) + request.Header.Set("Accept", "application/json") + response, err := c.http.Do(request) + if err != nil { + return fmt.Errorf("%w: %s %s: %v", ErrUnavailable, request.Method, target.Path, redactedError(err)) + } + defer response.Body.Close() + switch { + case response.StatusCode == http.StatusOK: + case response.StatusCode == http.StatusNotFound: + return ErrNotFound + case response.StatusCode == http.StatusUnauthorized || response.StatusCode == http.StatusForbidden: + return ErrUnauthorized + default: + return fmt.Errorf("%w: %s returned HTTP %d", ErrUnavailable, target.Path, response.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(response.Body, maxBodyBytes+1)) + if err != nil { + return fmt.Errorf("%w: read %s: %v", ErrUnavailable, target.Path, err) + } + if len(body) > maxBodyBytes { + return fmt.Errorf("%w: %s response exceeds %d bytes", ErrUnavailable, target.Path, maxBodyBytes) + } + if err := json.Unmarshal(body, into); err != nil { + return fmt.Errorf("%w: decode %s: %v", ErrUnavailable, target.Path, err) + } + return nil +} + +// redactedError drops the URL from transport errors; the query and path are +// already reported by the caller and the URL never carries the token, but this +// keeps logs stable across retries. +func redactedError(err error) error { + var urlErr *url.Error + if errors.As(err, &urlErr) { + return urlErr.Err + } + return err +} diff --git a/internal/netbox/client_test.go b/internal/netbox/client_test.go new file mode 100644 index 00000000..1000160f --- /dev/null +++ b/internal/netbox/client_test.go @@ -0,0 +1,191 @@ +package netbox + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" +) + +const syntheticDevice = `{ + "id": 1234, + "name": "server-01.rack-01.example", + "serial": "SYNTHETIC-0001", + "asset_tag": null, + "position": 12.0, + "device_type": {"model": "Example 1U", "manufacturer": {"name": "Example Vendor", "slug": "example-vendor"}}, + "role": {"name": "Compute", "slug": "compute"}, + "site": {"name": "Example Site", "slug": "example-site"}, + "rack": {"name": "rack-01.example"}, + "face": {"value": "front", "label": "Front"}, + "status": {"value": "active", "label": "Active"}, + "primary_ip4": {"address": "192.0.2.10/28"}, + "primary_ip6": null, + "oob_ip": {"address": "192.0.2.100/27"}, + "last_updated": "2026-01-02T03:04:05.123456Z", + "custom_fields": {"oob_password": "synthetic-not-a-secret"}, + "comments": "synthetic comment", + "config_context": {"secret": "synthetic-context"} +}` + +type fakeNetBox struct { + mu sync.Mutex + interfaces int + auth []string + methods []string + status int + pageShrink bool +} + +func (f *fakeNetBox) ServeHTTP(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + f.auth = append(f.auth, r.Header.Get("Authorization")) + f.methods = append(f.methods, r.Method) + status := f.status + f.mu.Unlock() + if status != 0 { + w.WriteHeader(status) + return + } + switch { + case r.URL.Path == "/api/dcim/devices/1234/": + _, _ = w.Write([]byte(syntheticDevice)) + case r.URL.Path == "/api/dcim/devices/77/": + _, _ = w.Write([]byte(`{"id": 78, "name": "wrong"}`)) + case r.URL.Path == "/api/dcim/interfaces/": + offset, _ := strconv.Atoi(r.URL.Query().Get("offset")) + limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) + count := f.interfaces + var items []string + for i := offset; i < count && i < offset+limit; i++ { + items = append(items, fmt.Sprintf(`{"id": %d, "name": "eth%03d", "enabled": true, "next": "https://elsewhere.example/steal"}`, i+1, i)) + } + if f.pageShrink && offset > 0 { + count-- + } + fmt.Fprintf(w, `{"count": %d, "next": "https://elsewhere.example/api/dcim/interfaces/?offset=%d", "results": [%s]}`, count, offset+limit, strings.Join(items, ",")) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +func newTestClient(t *testing.T, handler http.Handler, token string) *Client { + t.Helper() + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + client, err := NewClient(server.URL+"/api/", func() (string, error) { return token, nil }, server.Client()) + if err != nil { + t.Fatal(err) + } + return client +} + +func TestDeviceDecodesOnlyAllowlistedFields(t *testing.T) { + fake := &fakeNetBox{} + device, err := newTestClient(t, fake, "synthetic-legacy-token\n").Device(context.Background(), 1234) + if err != nil { + t.Fatal(err) + } + if device.Name != "server-01.rack-01.example" || device.Serial != "SYNTHETIC-0001" || device.OOBIP.Address != "192.0.2.100/27" || *device.Position != 12 { + t.Fatalf("unexpected device: %+v", device) + } + if got := fake.auth[0]; got != "Token synthetic-legacy-token" { + t.Fatalf("legacy token scheme = %q", got) + } +} + +func TestV2TokenUsesBearerScheme(t *testing.T) { + fake := &fakeNetBox{} + if _, err := newTestClient(t, fake, "nbt_synthetic.value").Device(context.Background(), 1234); err != nil { + t.Fatal(err) + } + if got := fake.auth[0]; got != "Bearer nbt_synthetic.value" { + t.Fatalf("v2 token scheme = %q", got) + } +} + +func TestInterfacesPaginateWithoutFollowingServerURLs(t *testing.T) { + fake := &fakeNetBox{interfaces: pageSize + 5} + interfaces, err := newTestClient(t, fake, "synthetic").Interfaces(context.Background(), 1234) + if err != nil { + t.Fatal(err) + } + if len(interfaces) != pageSize+5 { + t.Fatalf("got %d interfaces", len(interfaces)) + } + for _, method := range fake.methods { + if method != http.MethodGet { + t.Fatalf("client issued %s", method) + } + } +} + +func TestInterfaceCountChangeDuringPaginationIsUnavailable(t *testing.T) { + fake := &fakeNetBox{interfaces: pageSize + 5, pageShrink: true} + if _, err := newTestClient(t, fake, "synthetic").Interfaces(context.Background(), 1234); !errors.Is(err, ErrUnavailable) { + t.Fatalf("err = %v, want ErrUnavailable", err) + } +} + +func TestStatusMapping(t *testing.T) { + for status, want := range map[int]error{ + http.StatusNotFound: ErrNotFound, + http.StatusUnauthorized: ErrUnauthorized, + http.StatusForbidden: ErrUnauthorized, + http.StatusInternalServerError: ErrUnavailable, + http.StatusFound: ErrUnavailable, + } { + fake := &fakeNetBox{status: status} + if _, err := newTestClient(t, fake, "synthetic").Device(context.Background(), 1234); !errors.Is(err, want) { + t.Errorf("HTTP %d: err = %v, want %v", status, err, want) + } + } +} + +func TestMismatchedDeviceIDIsRejected(t *testing.T) { + if _, err := newTestClient(t, &fakeNetBox{}, "synthetic").Device(context.Background(), 77); !errors.Is(err, ErrUnavailable) { + t.Fatalf("err = %v, want ErrUnavailable", err) + } +} + +func TestEmptyTokenIsNotSent(t *testing.T) { + fake := &fakeNetBox{} + if _, err := newTestClient(t, fake, " \n").Device(context.Background(), 1234); !errors.Is(err, ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized", err) + } + if len(fake.auth) != 0 { + t.Fatal("request sent without a credential") + } +} + +func TestOriginValidation(t *testing.T) { + token := func() (string, error) { return "synthetic", nil } + for _, origin := range []string{"http://netbox.example", "https://user:pass@netbox.example", "https://netbox.example/?q=1", "netbox.example", "ftp://netbox.example"} { + if _, err := NewClient(origin, token, nil); err == nil { + t.Errorf("origin %q accepted", origin) + } + } + for _, origin := range []string{"https://netbox.example", "https://netbox.example/api", "http://127.0.0.1:8080", "http://localhost:8080/"} { + if _, err := NewClient(origin, token, nil); err != nil { + t.Errorf("origin %q rejected: %v", origin, err) + } + } +} + +func TestRedirectIsNotFollowed(t *testing.T) { + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("redirect target received %s with Authorization %q", r.URL.Path, r.Header.Get("Authorization")) + })) + defer target.Close() + redirector := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL+r.URL.Path, http.StatusTemporaryRedirect) + }) + if _, err := newTestClient(t, redirector, "synthetic").Device(context.Background(), 1234); !errors.Is(err, ErrUnavailable) { + t.Fatalf("err = %v, want ErrUnavailable", err) + } +}