diff --git a/.github/workflows/publish-device-hardware-publisher.yml b/.github/workflows/publish-device-hardware-publisher.yml new file mode 100644 index 00000000..87355cae --- /dev/null +++ b/.github/workflows/publish-device-hardware-publisher.yml @@ -0,0 +1,32 @@ +name: Publish Fleet Device hardware publisher + +on: + push: + release: + types: [published] + workflow_dispatch: + +jobs: + validate-device-hardware-publisher: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-go@v6 + with: + go-version-file: go.mod + cache: true + - run: go test -count=1 -race ./internal/devicehardwarepublisher ./internal/devicehardwaremetrics ./internal/hardwaremetrics ./cmd/fleet-device-hardware-publisher + - run: go vet ./internal/devicehardwarepublisher ./internal/devicehardwaremetrics ./cmd/fleet-device-hardware-publisher + publish-device-hardware-publisher-image: + needs: validate-device-hardware-publisher + permissions: + id-token: write + contents: read + packages: write + uses: datum-cloud/actions/.github/workflows/publish-docker.yaml@v1.27.1 + with: + image-name: fleet-device-hardware-publisher + dockerfile-path: build/device-hardware-publisher.Dockerfile + platforms: linux/amd64,linux/arm64 diff --git a/README.md b/README.md index fa27d2ff..aa900bac 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,20 @@ The [Bare Metal CLI enhancement](docs/enhancements/metal-cli/README.md) proposes `datumctl metal` discovery, machine management, and safe recovery workflows. The [BMC hardware telemetry enhancement](docs/enhancements/hardware-telemetry/README.md) -proposes operator and tenant hardware metrics collected from server BMCs. +proposes operator and tenant hardware metrics collected from server BMCs. The +[inventory-owner Device projection](docs/enhancements/hardware-telemetry/device-owner-integration.md) +provides a tested library for routing qualified readings to the current owning +Project regardless of allocation or custody. An [independent publisher](docs/enhancements/hardware-telemetry/device-owner-publisher.md) +adds authenticated inventory reads and qualified source ingestion with synthetic +tests; it is not deployed. Metal consumer metrics retain separate activation/release gates. + +Control-plane [resource metadata](docs/enhancements/hardware-telemetry/resource-metadata.md) +is a separate feed: Fleet defines +`ResourceMetricsPolicy` objects for resource-metrics to evaluate against inventory +objects. Those policies do not generate sensor samples or become an authority +dependency of the sensor publisher. Shared telemetry retains ingestion, storage, +federation, and customer query/export authorization for both feeds. See the +[telemetry ownership boundary](docs/enhancements/hardware-telemetry/README.md#telemetry-ownership-boundary). Contributors should also read the [repository guidance](AGENTS.md) and [implementation roadmap](docs/development/roadmap.md). diff --git a/build/device-hardware-publisher.Dockerfile b/build/device-hardware-publisher.Dockerfile new file mode 100644 index 00000000..36f15c03 --- /dev/null +++ b/build/device-hardware-publisher.Dockerfile @@ -0,0 +1,13 @@ +FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 AS build +ARG TARGETOS TARGETARCH +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ +RUN CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build -trimpath -ldflags='-s -w' -o /out/fleet-device-hardware-publisher ./cmd/fleet-device-hardware-publisher + +FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab +COPY --from=build /out/fleet-device-hardware-publisher /fleet-device-hardware-publisher +EXPOSE 9090 +ENTRYPOINT ["/fleet-device-hardware-publisher"] diff --git a/cmd/fleet-device-hardware-publisher/main.go b/cmd/fleet-device-hardware-publisher/main.go new file mode 100644 index 00000000..bf3bce61 --- /dev/null +++ b/cmd/fleet-device-hardware-publisher/main.go @@ -0,0 +1,39 @@ +package main + +import ( + "flag" + "fmt" + "net" + "net/http" + "os" + "strconv" + "time" + + "go.datum.net/fleet/internal/devicehardwarepublisher" +) + +func run(args []string) error { + flags := flag.NewFlagSet("fleet-device-hardware-publisher", flag.ContinueOnError) + config := flags.String("config", "", "required protected publisher JSON configuration") + listen := flags.String("listen-address", ":9090", "internal metrics listen address") + if e := flags.Parse(args); e != nil { + return e + } + _, port, e := net.SplitHostPort(*listen) + portNumber, portErr := strconv.Atoi(port) + if e != nil || portErr != nil || portNumber < 1 || portNumber > 65535 || *config == "" || flags.NArg() != 0 { + return fmt.Errorf("--config and a valid --listen-address are required") + } + p, e := devicehardwarepublisher.New(*config) + if e != nil { + return e + } + server := &http.Server{Addr: *listen, Handler: p, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 35 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 8192} + return server.ListenAndServe() +} +func main() { + if e := run(os.Args[1:]); e != nil { + fmt.Fprintln(os.Stderr, "publisher stopped:", e) + os.Exit(1) + } +} diff --git a/cmd/fleet-device-hardware-publisher/main_test.go b/cmd/fleet-device-hardware-publisher/main_test.go new file mode 100644 index 00000000..c947ea5a --- /dev/null +++ b/cmd/fleet-device-hardware-publisher/main_test.go @@ -0,0 +1,11 @@ +package main + +import "testing" + +func TestInvalidFlags(t *testing.T) { + for _, args := range [][]string{nil, {"--unknown"}, {"--config", "missing", "--listen-address", "invalid"}, {"--config", "missing", "extra"}} { + if run(args) == nil { + t.Fatalf("accepted %v", args) + } + } +} diff --git a/config/components/resource-metrics/README.md b/config/components/resource-metrics/README.md new file mode 100644 index 00000000..39b1316b --- /dev/null +++ b/config/components/resource-metrics/README.md @@ -0,0 +1,26 @@ +# Optional Device resource metadata + +This standalone Kustomization installs only Fleet's `ResourceMetricsPolicy` on +the resource-metrics management control plane. It is not included by Fleet's +default deployment. It neither installs nor upgrades resource-metrics. + +Render and validate locally from the Fleet repository root: + +```sh +kubectl kustomize config/components/resource-metrics +kubectl kustomize config/components/resource-metrics/project-reader +go test ./config/components/resource-metrics +``` + +The separately rendered `project-reader` role belongs on each authorized project +control plane, not automatically on the policy management cluster. It opts into +resource-metrics' reader aggregation, but creates no binding and is not evidence +of Milo authorization. It permits full Device reads (including private fields), +even though the policy exports only four allowlisted labels. Approve that reader +trust boundary explicitly. No Secret read, Fleet mutation, or sensor permission +is granted. Do not substitute the broad inventory viewer role or a privileged +control certificate to make a failed authorization check pass. + +Deployment, exact principal/binding selection, project discovery, Fleet API +availability, ingestion, and tenant query isolation require separate +qualification. See [the metadata contract and rollout gates](../../../docs/enhancements/hardware-telemetry/resource-metadata.md). diff --git a/config/components/resource-metrics/device-policy.yaml b/config/components/resource-metrics/device-policy.yaml new file mode 100644 index 00000000..ae543bfc --- /dev/null +++ b/config/components/resource-metrics/device-policy.yaml @@ -0,0 +1,27 @@ +apiVersion: resourcemetrics.miloapis.com/v1alpha1 +kind: ResourceMetricsPolicy +metadata: + name: fleet-device-metadata +spec: + metricNamePrefix: fleet + generators: + - name: device-metadata + resource: + group: fleet.datumapis.com + version: v1alpha1 + resource: devices + families: + - name: device_info + help: Observed Device identity and declared asset lifecycle; not readiness or allocation eligibility. + type: gauge + metrics: + - value: "1.0" + labels: + - name: device + value: object.metadata.name + - name: namespace + value: object.metadata.namespace + - name: device_uid + value: object.metadata.uid + - name: lifecycle + value: "!has(object.spec.lifecycle) || object.spec.lifecycle == '' ? 'Active' : (object.spec.lifecycle in ['Active', 'Decommissioning', 'Retired'] ? object.spec.lifecycle : 'Unknown')" diff --git a/config/components/resource-metrics/kustomization.yaml b/config/components/resource-metrics/kustomization.yaml new file mode 100644 index 00000000..9ed8cb8c --- /dev/null +++ b/config/components/resource-metrics/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - device-policy.yaml diff --git a/config/components/resource-metrics/policy_test.go b/config/components/resource-metrics/policy_test.go new file mode 100644 index 00000000..84ce83e4 --- /dev/null +++ b/config/components/resource-metrics/policy_test.go @@ -0,0 +1,178 @@ +package resourcemetrics_test + +import ( + "bytes" + "encoding/json" + "os" + "reflect" + "testing" + + "github.com/google/cel-go/cel" + "github.com/google/cel-go/ext" + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + "go.yaml.in/yaml/v3" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" +) + +type policyDocument struct { + APIVersion string `yaml:"apiVersion"` + Kind string `yaml:"kind"` + Metadata struct{ Name string } `yaml:"metadata"` + Spec struct { + MetricNamePrefix string `yaml:"metricNamePrefix"` + Generators []struct { + Name string + Resource struct{ Group, Version, Resource string } + Families []struct { + Name, Help, Type string + Metrics []struct { + Value string + Labels []struct{ Name, Value string } + } + } + } + } +} + +func TestDeviceMetadataPolicy(t *testing.T) { + contents, err := os.ReadFile("device-policy.yaml") + if err != nil { + t.Fatal(err) + } + var document policyDocument + decoder := yaml.NewDecoder(bytes.NewReader(contents)) + decoder.KnownFields(true) + if err := decoder.Decode(&document); err != nil { + t.Fatal(err) + } + if document.APIVersion != "resourcemetrics.miloapis.com/v1alpha1" || document.Kind != "ResourceMetricsPolicy" || document.Metadata.Name != "fleet-device-metadata" || document.Spec.MetricNamePrefix != "fleet" || len(document.Spec.Generators) != 1 { + t.Fatalf("unexpected policy contract: %+v", document) + } + generator := document.Spec.Generators[0] + if generator.Resource.Group != inventory.GroupVersion.Group || generator.Resource.Version != inventory.GroupVersion.Version || generator.Resource.Resource != "devices" || len(generator.Families) != 1 { + t.Fatalf("unexpected generator: %+v", generator) + } + family := generator.Families[0] + if family.Name != "device_info" || family.Type != "gauge" || family.Help == "" || len(family.Metrics) != 1 { + t.Fatalf("unexpected family: %+v", family) + } + metric := family.Metrics[0] + if len(metric.Labels) != 4 { + t.Fatalf("unexpected label count: %d", len(metric.Labels)) + } + environment, err := cel.NewEnv(cel.Variable("object", cel.DynType), ext.Strings(), ext.Encoders(), ext.Math(), ext.Lists()) + if err != nil { + t.Fatal(err) + } + compile := func(expression string) cel.Program { + t.Helper() + parsed, issues := environment.Compile(expression) + if issues.Err() != nil { + t.Fatal(issues.Err()) + } + program, err := environment.Program(parsed) + if err != nil { + t.Fatal(err) + } + return program + } + valueProgram := compile(metric.Value) + programs := map[string]cel.Program{} + for _, label := range metric.Labels { + if _, exists := programs[label.Name]; exists { + t.Fatalf("duplicate label %s", label.Name) + } + programs[label.Name] = compile(label.Value) + } + for _, fixture := range []struct { + name, lifecycle, expected, uid string + explicitEmpty bool + }{ + {name: "omitted-default", expected: "Active", uid: "device-uid-one"}, + {name: "empty-default", expected: "Active", uid: "device-uid-one", explicitEmpty: true}, + {name: "active", lifecycle: "Active", expected: "Active", uid: "device-uid-one"}, + {name: "decommissioning", lifecycle: "Decommissioning", expected: "Decommissioning", uid: "device-uid-one"}, + {name: "retired", lifecycle: "Retired", expected: "Retired", uid: "device-uid-one"}, + {name: "unrecognized", lifecycle: "FutureState", expected: "Unknown", uid: "device-uid-one"}, + {name: "recreated", lifecycle: "Active", expected: "Active", uid: "device-uid-two"}, + } { + t.Run(fixture.name, func(t *testing.T) { + device := inventory.Device{ + ObjectMeta: metav1.ObjectMeta{Name: "synthetic-device", Namespace: "inventory", UID: types.UID(fixture.uid), Labels: map[string]string{"private": "never-export"}, Annotations: map[string]string{"credential": "synthetic-secret"}}, + Spec: inventory.DeviceSpec{Lifecycle: inventory.DeviceLifecycle(fixture.lifecycle), AssetTag: "private-asset", DisplayName: "private-display"}, + } + encoded, err := json.Marshal(device) + if err != nil { + t.Fatal(err) + } + var object map[string]any + if err := json.Unmarshal(encoded, &object); err != nil { + t.Fatal(err) + } + if fixture.explicitEmpty { + object["spec"].(map[string]any)["lifecycle"] = "" + } + delete(object, "status") + activation := map[string]any{"object": object} + value, _, err := valueProgram.Eval(activation) + if err != nil || value.Value() != float64(1) { + t.Fatalf("value = %v, error = %v", value, err) + } + labels := map[string]any{} + for name, program := range programs { + value, _, err := program.Eval(activation) + if err != nil { + t.Fatalf("label %s: %v", name, err) + } + labels[name] = value.Value() + } + want := map[string]any{"device": "synthetic-device", "namespace": "inventory", "device_uid": fixture.uid, "lifecycle": fixture.expected} + if !reflect.DeepEqual(labels, want) { + t.Fatalf("labels = %v, want %v", labels, want) + } + for _, field := range []string{"name", "namespace", "uid"} { + metadata := object["metadata"].(map[string]any) + original := metadata[field] + delete(metadata, field) + label := map[string]string{"name": "device", "namespace": "namespace", "uid": "device_uid"}[field] + if _, _, err := programs[label].Eval(activation); err == nil { + t.Fatalf("missing %s must fail, not invent identity", field) + } + metadata[field] = original + } + }) + } +} + +func TestProjectReaderIsDeviceReadOnly(t *testing.T) { + contents, err := os.ReadFile("project-reader/role.yaml") + if err != nil { + t.Fatal(err) + } + var role struct { + APIVersion string `yaml:"apiVersion"` + Kind string + Metadata struct { + Name string + Labels map[string]string + } + Rules []struct { + APIGroups []string `yaml:"apiGroups"` + Resources []string + Verbs []string + } + } + decoder := yaml.NewDecoder(bytes.NewReader(contents)) + decoder.KnownFields(true) + if err := decoder.Decode(&role); err != nil { + t.Fatal(err) + } + if role.APIVersion != "rbac.authorization.k8s.io/v1" || role.Kind != "ClusterRole" || role.Metadata.Name != "fleet-resource-metrics-device-reader" || !reflect.DeepEqual(role.Metadata.Labels, map[string]string{"resourcemetrics.miloapis.com/aggregate-to-reader": "true"}) || len(role.Rules) != 1 { + t.Fatalf("unexpected reader contract: %+v", role) + } + rule := role.Rules[0] + if !reflect.DeepEqual(rule.APIGroups, []string{inventory.GroupVersion.Group}) || !reflect.DeepEqual(rule.Resources, []string{"devices"}) || !reflect.DeepEqual(rule.Verbs, []string{"get", "list", "watch"}) { + t.Fatalf("reader must grant only Device get/list/watch: %+v", rule) + } +} diff --git a/config/components/resource-metrics/project-reader/kustomization.yaml b/config/components/resource-metrics/project-reader/kustomization.yaml new file mode 100644 index 00000000..4f84bb68 --- /dev/null +++ b/config/components/resource-metrics/project-reader/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - role.yaml diff --git a/config/components/resource-metrics/project-reader/role.yaml b/config/components/resource-metrics/project-reader/role.yaml new file mode 100644 index 00000000..a263ea3f --- /dev/null +++ b/config/components/resource-metrics/project-reader/role.yaml @@ -0,0 +1,10 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-resource-metrics-device-reader + labels: + resourcemetrics.miloapis.com/aggregate-to-reader: "true" +rules: + - apiGroups: [fleet.datumapis.com] + resources: [devices] + verbs: [get, list, watch] diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 125d7209..6640b515 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -59,6 +59,18 @@ their owning services. Fleet consumes these contracts and their evidence. ## Lifecycle and authority contracts +Hardware telemetry follows a separate +[ownership boundary](../enhancements/hardware-telemetry/README.md#telemetry-ownership-boundary): +Fleet qualifies and attributes sensor samples using direct inventory reads; +resource-metrics generates control-plane metadata from +[Fleet-owned policies](../enhancements/hardware-telemetry/resource-metadata.md); +shared telemetry handles ingestion, storage, federation, and customer query/export +authorization. These are complementary feeds, not a synchronous metrics join. +Sensor readings never belong in Kubernetes status, and metadata observations do +not establish provisioning or allocation authority. Customer rollout and read +authorization require independent qualification; this boundary is not a claim +of deployed behavior. + 1. **Preserve distinct identities.** DeviceClaim describes an approved physical installation; Device identifies an actual asset; MachineCapacity represents provider supply; a customer Machine receives one immutable MachineAllocation; diff --git a/docs/enhancements/hardware-telemetry/README.md b/docs/enhancements/hardware-telemetry/README.md index 3cb23a69..09cbcb30 100644 --- a/docs/enhancements/hardware-telemetry/README.md +++ b/docs/enhancements/hardware-telemetry/README.md @@ -20,6 +20,12 @@ Synthetic tests cover these components; they are not an end-to-end consumer service. Qualified read-only credentials, verified handoff activation, a fenced authority adapter, and tenant query/export isolation remain deployment gates. +A separate [inventory-owner Device projection](device-owner-integration.md) +implements qualified fan and temperature projection to the inventory-owning +Project irrespective of allocation or custody state. The [independent publisher](device-owner-publisher.md) +adds a tested runtime adapter; neither component is a deployed customer path. +They do not change the Metal allocation or activation contract. + - [Summary](#summary) - [Motivation](#motivation) - [Proposal](#proposal) @@ -28,6 +34,7 @@ authority adapter, and tenant query/export isolation remain deployment gates. - [Relationship to other proposals](#relationship-to-other-proposals) - [Risks and mitigations](#risks-and-mitigations) - [Design details](#design-details) + - [Telemetry ownership boundary](#telemetry-ownership-boundary) - [Architecture and data flow](#architecture-and-data-flow) - [Target and credential lifecycle](#target-and-credential-lifecycle) - [Telemetry account operation](#telemetry-account-operation) @@ -133,8 +140,52 @@ For each server they hold: ## Design details +### Telemetry ownership boundary + +The inventory rollout uses two complementary, independently qualified feeds. +This ownership decision does not establish that either customer-facing feed is +deployed or that its authorization has been verified. + +- **Fleet sensor publication:** Fleet owns read-only collection and qualification, + physical-to-Device binding, inventory-owner attribution, source freshness, safe + labels, and the approved fan and temperature samples. The narrow publisher + reads inventory directly. Device and Project labels on sensor samples remain + its responsibility. Inventory ownership applies regardless of allocation or + custody; Metal consumer publication has a separate activation/release contract. +- **Control-plane resource metadata:** The optional + [metadata policy bundle](resource-metadata.md) contains Fleet-owned `ResourceMetricsPolicy` + definitions; `milo-os/resource-metrics` evaluates them against resource objects. + This feed describes supported identity and resource-state facts, not sensor + readings. Empty Device status does not establish proposed lifecycle conditions. + Do not add sensor samples to Kubernetes status or extend resource-metrics into + an external Prometheus query engine. +- **Shared telemetry:** Existing infrastructure owns ingestion, storage, + federation, and customer query/export authorization. Resource metadata is not + an authorization source for the sensor publisher, and neither feed grants + access merely by attaching a Project label. + +The metadata feed is not a synchronous prerequisite for sensor delivery. A +future replacement of direct authority reads with a metrics join would require +a separate review of freshness and failure semantics. Qualify actual emitted +identity attributes and downstream label transforms; do not assume automatic +Project UID attachment from design documentation. Independently prove inventory +read authorization for each integration rather than relying on reader-role +aggregation alone. + +The initial sensor rollout retains existing name-based customer query grants. +UID-pinned query grants, Project-recreation isolation, and a broad IAM redesign +are explicitly deferred. This does not relax the publisher's least-privilege +identity, certificate, or cross-Project isolation requirements. Finish and prove +the sensor path first; metadata policies can be validated and deployed separately. + ### Architecture and data flow +The diagrams and allocation-based recording-rule flow below describe the broader +Metal consumer proposal, not the initial inventory-owner runtime. For that +runtime, the [Device publisher](device-owner-publisher.md) is the authoritative +safe sensor projection; resource metadata is a separate feed under the ownership +boundary above, not a new join dependency. + Fleet uses the open-source `idrac_exporter` and contributes the changes it needs [upstream](#upstream-work). Each metric family has one writer: the exporter for BMC data, Fleet for the allocation info series, and the recording @@ -256,6 +307,11 @@ to its recovery table. ### Tenant attribution +This section describes the Metal Machine consumer product. Fleet Device metrics +always belong to the current inventory-owning Project, including while allocated; +see the separate [Device contract](device-owner-integration.md). Its visibility +is `inventory_owner`, and allocation activation/release gates do not apply to it. + Fleet resolves a tenant from this chain of identities: Device (the physical asset), MachineCapacity (provider supply), MachineAllocation (the allocation), and the customer Machine in the tenant's project. The allocation info series diff --git a/docs/enhancements/hardware-telemetry/device-owner-integration.md b/docs/enhancements/hardware-telemetry/device-owner-integration.md new file mode 100644 index 00000000..c50e30a9 --- /dev/null +++ b/docs/enhancements/hardware-telemetry/device-owner-integration.md @@ -0,0 +1,211 @@ +# Inventory-owner Device hardware metrics + +Status: **implemented pure projection with synthetic tests**. A separate +[independent publisher](device-owner-publisher.md) now provides the runtime +adapter and internal endpoint; neither is a deployed customer path. This is a separate product contract +from the [Metal allocation projection](consumer-integration.md), which remains +disabled. It does not manufacture a Machine, allocation, or activation time. +The [inventory proposal](../../proposals/fleet-management/inventory.md) and +[allocation proposal](../../proposals/fleet-management/bare-metal-hardware.md) +retain their separate identities and authorities. + +## Scope and output contract + +The current inventory-owning **Project** receives qualified fan RPM and +temperature readings for its Device irrespective of allocation or custody state. +Allocation, release, service holds, recovery, and unverified custody do not change +inventory ownership or suppress these readings. Unknown ownership, deleting +identities, or unqualified physical mapping still fail closed. This grants +observation only; it neither verifies custody nor publishes capacity. + +The separate Metal Machine product projects readings to consumers only under +its activation and release authorization. An inventory owner and a Metal +consumer can receive separate series for the same physical asset, each under +its own identity and visibility contract. + +Reserve `datum_fleet_device_hardware_*` for this product. The implemented families +are exactly: + +| Qualified source family | Output family | Unit | +| --- | --- | --- | +| `idrac_sensors_fan_speed` | `datum_fleet_device_hardware_fan_speed_rpm` | RPM | +| `idrac_sensors_temperature` | `datum_fleet_device_hardware_temperature_celsius` | Celsius | + +The output label set is exactly: + +| Label | Meaning | +| --- | --- | +| `resourcemanager_datumapis_com_project_name` | Existing exact project routing name, read from current authoritative Project identity | +| `project_uid` | Immutable Project lifetime UID | +| `project_authority` | Authority identifying the Project identity domain | +| `device` | Bounded, sanitized name of the inventory Device visible to that owner | +| `device_uid` | Exact Device incarnation UID | +| `component` | Stable decimal identity in `0..4095`, assigned by the qualified adapter per Device and family | +| `visibility` | Literal `inventory_owner` | + +The projection sanitizes by rejecting names outside its bounded lowercase +alphanumeric/dot/hyphen allowlist, rather than transforming two names into the +same label. Identity fields are bounded ASCII tokens. These checks do not prove +that a name is safe to expose: the inventory authority must supply the owner's +visible Device name, never a BMC hostname, address, serial, or provider alias. +UIDs disambiguate name reuse. No allocation, Machine, namespace, address, serial, +site, raw sensor name, credential, or incoming metric label is emitted. +Forged incoming project/device/component/visibility labels are ignored; all +output labels are constructed from validated trusted inputs. + +Every output retains the **original sample timestamp**. Missing/nonfinite values +and negative RPM are omitted; numeric zero and negative Celsius are valid. +Power, health enumerations, inventory, and diagnostic families are excluded. +Each exact sensor must appear in a qualified physical mapping. Stable component +identities must not be inferred from scrape order, truncated raw names, or a +collision-prone hash, and must not be reused for a replacement sensor within a +Device lifetime. Exhausting the component bound suppresses new identities until +the contract is revised. Mapping changes invalidate in-flight samples. + +## Implemented component boundary + +`internal/devicehardwaremetrics.ProjectReadings` accepts immutable `Snapshot`, +`Policy`, and `Reading` inputs and returns independent series. It has no network, +Kubernetes, Prometheus parsing, manager registration, or publication code. It does +not import or weaken the Metal projection. Concurrent reads are safe; concurrent +mutation of inputs is unsupported. + +A binding requires fresh revision-bearing observations of the Device, Project, +and physical mapping. The snapshot assembly must follow those reads. Every final +read must follow collection. Age limits are strict: evidence at its maximum age +is expired; future and zero times fail. Missing/deleting identities, malformed or +conflicting authority, incomplete snapshots, duplicate Devices/physical targets, +ambiguous project routes, and duplicate qualified sensors reject the whole batch. +Missing bindings emit nothing. Duplicate reading identities reject the entire +batch even if one copy has an invalid value or old ownership token. + +The collector binds every sample **before collection** to Project authority/UID, +Device UID, ownership period, and mapping revision. The final observation must +match those exact identities. Samples must be strictly after ownership and +mapping start times; equality is rejected to avoid attributing samples on an +ambiguous transition timestamp. Tokens and times are adapter evidence, not new +public API fields. There is no eligibility window, custody read, operation fence, +or allocation coordination requirement in this Device projection. + +Caller-populated evidence and `Snapshot.Complete` are **not production proof**. +The library validates structure and consistency under a trusted-adapter +assumption. Never expose this function as an endpoint accepting authority from +a tenant, operator scrape labels, or an arbitrary configuration file. + +## Runtime interface and adapter obligations + +The concrete library input is: + +- `Binding{Device, Project, Mapping}`. +- `Project{AuthorityID, Name, UID, Evidence, Deleting}`. +- `Device{Name, UID, Evidence, Deleting, OwnershipID, OwnedSince}`. +- `Mapping{Evidence, DeviceUID, PhysicalID, TargetID, ValidSince, Sensors}`. +- `Reading{DeviceUID, OwnershipID, MappingRevision, ProjectUID, + ProjectAuthority, Sensor, Value, ObservedAt, Labels}`. + +The checkout has +[`manager.ResolveProjectIdentity`](../../../internal/manager/project_identity.go), +which reads an active Milo Project through `client.Reader` and returns +`controller.ProjectIdentity{AuthorityID, RouteName, UID}`. It does not retain +Project resourceVersion or observation time. An independent publisher must use +an authenticated uncached Milo reader, a trusted authority configuration tied to +that endpoint, and a project-scoped uncached Device reader. It must retain both +reads' resourceVersions, UID, and deletion state. Project name is a lookup route, +not proof of ownership. + +The current [Device API](../../../internal/api/inventory/v1alpha1/types.go) is +project-scoped and has Kubernetes identity metadata, immutable chassis identity, +and a BMC endpoint. It has no ownership-transition epoch or qualified telemetry +sensor mapping. Its serial/SystemUUID are matching evidence, explicitly not +authenticators. Device BMC addresses and raw labels cannot establish authenticated +physical mapping, firmware/unit/missingness qualification, or stable bounded +sensor identities. The [independent publisher](device-owner-publisher.md) consumes explicit protected +operator qualification records for this mapping. The repository does not supply +real physical qualification evidence; an arbitrary UID relabel remains insufficient. + +A runtime integration must: + +1. Resolve the current Project lifetime and read the Device in that authenticated + project context before collection. Establish ownership continuity for the + observation session. A session may conservatively start a new ownership token + and time at a successful read, discarding older samples; it must never reuse + tokens after loss of continuity or an ownership transition, including A → B → A. +2. Obtain the exact authenticated physical mapping and qualified sensor identities. + Pin its revision before collection and preserve original sample timestamps. + A raw query result or a freely chosen target parameter is insufficient. +3. Re-read Project, Device, and mapping after collection. Reject deletion, + replacement, changed ownership, missing authority, or changed mapping. + Revalidate Project identity independently even when a Device or route name + appears unchanged. Assemble the snapshot only after successful final reads. +4. Publish only the two allowlisted families and exact label set, preserving + original timestamps. Restrict ingestion to the authenticated publisher and + bind queued writes/retries to the original Project and Device lifetime. + Current reads alone do not provide an atomic ownership-to-publication handoff; + the eventual ownership transition/publication contract must address that race. + Allocation and custody transitions require no telemetry publication barrier. + +Prefer an independent telemetry publisher deployment. The reported staging +manager revision +[`2f8ea74bcb6a81c8e841e844c8aafcbe4b6306f1`](https://github.com/datum-cloud/fleet/tree/2f8ea74bcb6a81c8e841e844c8aafcbe4b6306f1) +diverges from this checkout; this library does not justify replacing that manager. +Qualified raw readings have been reported for three DFW3 Devices in the +datum-cloud Project, but this component has performed no live validation or +customer ingestion. Telemetry performs no provisioning, hardware writes, +custody verification, cleanup, or capacity publication. + +## Historical visibility and query/export isolation + +This is current-sample projection, not historical backfill. Allocation and +custody changes do not interrupt owner samples or create a new observation window. +An ownership transition changes the ownership token even for A → B → A. +Project deletion/recreation changes Project UID. Hardware replacement changes +Device UID. Neither reused Project names nor reused Device names may relabel old +samples. + +Previously stored samples retain their original Project authority/UID, Device UID, +and visibility. An owner can retain history it received during its own ownership +period; samples are not rewritten for a later owner. If the same +Project lifetime later owns the Device again, its own earlier history remains +attributed to it. A Device detail query must select its exact Device UID, never +name alone; a newly created Device with the same name is not the old Device. +Project-wide authorized history may include that Project's retired Devices, but +must not present those readings as belonging to a replacement. + +This release uses the existing customer query/export authorization by Project +**name**. It does not change IAM, add UID-pinned queries, or migrate the query or +export services. Federation must allow exactly the two families and the label +set above, including visibility, and exclude raw metrics. Existing Project-name +isolation must remain effective across queries, metadata/discovery, and exports. + +**Deferred known limitation:** no durable Project route-name nonreuse guarantee +has been established. If a Project name is reused, the current authorization may +expose retained history from its previous lifetime, including through aggregates, +metadata, or exports. The `project_uid` and `project_authority` labels preserve +provenance but do not enforce lifetime isolation. Current inventory UID checks +reject publication under a replaced identity; they cannot revoke access to +already stored samples. Device UID selectors distinguish replacement Devices in +detail views but are not an authorization boundary. Recreation-aware query/export +controls and their rollout are deferred, not activation prerequisites for this +release. A future lifetime-isolation contract would need authority/UID enforcement +before query evaluation and export, with recreation and historical-range tests. +This component implements none of those query controls and makes no claim that +same-name Project recreation is isolated. + +## Validation + +From the repository root: + +```sh +go test -count=1 -race ./internal/devicehardwaremetrics ./internal/hardwaremetrics +bash hack/validate-doc-links.sh +git diff --check +``` + +Synthetic regressions cover exact families/labels/timestamps, forged labels, +missing/nonfinite readings, valid zero/negative temperature, strict freshness, +invalid/deleting/stale authority, ambiguous identities/routes, duplicate sensors, +ownership/mapping transitions, Project recreation and authority changes, Device +replacement, preserved history, two Projects, and concurrent immutable calls. +They validate the library contract, not authenticated API provenance or live +publication fencing. The existing Metal projection race tests run separately +and its activation/release authorization remains unchanged. diff --git a/docs/enhancements/hardware-telemetry/device-owner-publisher.md b/docs/enhancements/hardware-telemetry/device-owner-publisher.md new file mode 100644 index 00000000..9bffe278 --- /dev/null +++ b/docs/enhancements/hardware-telemetry/device-owner-publisher.md @@ -0,0 +1,270 @@ +# Independent inventory-owner hardware publisher + +Status: implemented with synthetic API and Prometheus tests; **not deployed or +runtime-qualified**. This release uses existing customer query authorization by +Project name, with the deferred [historical visibility limitation](device-owner-integration.md#historical-visibility-and-queryexport-isolation). Metal consumer publication, the raw collector service/image, and +the Fleet manager are unchanged. + +The independent `cmd/fleet-device-hardware-publisher` binary uses the existing +[projection contract](device-owner-integration.md). Its only HTTP endpoint is +`GET /metrics`, default port **9090**, with Prometheus text and explicit original +stored sample timestamps. It emits exactly the two documented families and seven +labels. It adds no Go/process or diagnostic metric families. It observes inventory +regardless of custody and allocation, and performs no writes or hardware access. + +## Deployment interface + +Flags are `--config=/etc/fleet-publisher/config.json` (required) and +`--listen-address=:9090` (default). Unknown flags, positional arguments, missing +config and malformed listen addresses fail startup. JSON rejects unknown fields +and trailing documents. The configuration is bounded to 1 MiB, read at startup, +then reread before and after each publication; any byte change fails closed until +restart. Mount it read-only under operator-only write access, separately from the +reader certificate/kubeconfig. A fresh process creates a new observation session; +there is no persisted sample queue or backfill. + +This is a synthetic example, not a qualification of any real hardware: + +```json +{ + "miloKubeconfig": "/var/run/fleet-reader/kubeconfig", + "project": "example-owner", + "projectUID": "synthetic-project-uid", + "projectAuthority": "api.staging.example.invalid", + "namespace": "inventory", + "prometheusURL": "http://operator-prometheus.monitoring.svc:9090", + "job": "qualified-hardware", + "cluster": "central-staging", + "timeoutSeconds": 15, + "maxSampleAgeSeconds": 300, + "maxResponseBytes": 2097152, + "devices": [ + { + "name": "example-device", + "uid": "synthetic-device-uid", + "physicalID": "synthetic-asset", + "targetID": "synthetic-collector-target", + "instance": "synthetic-raw-instance", + "revision": "qualification-v1", + "evidenceRef": "operator-reviewed-qualification-record-v1", + "qualifiedAt": "2026-11-01T00:00:00Z", + "sensors": [ + {"family": "idrac_sensors_fan_speed", "component": 0, + "id": "fan-1", "name": "Fan", "units": "rpm", "context": ""}, + {"family": "idrac_sensors_temperature", "component": 0, + "id": "temp-1", "name": "Inlet", "units": "celsius", "context": ""} + ] + } + ] +} +``` + +All shown fields are required except a sensor's empty `context`. Limits are +1–32 Devices; 1–8192 sensors per Device; component 0–4095 per family; +`timeoutSeconds` 1–30; `maxSampleAgeSeconds` 1–600; `maxResponseBytes` +1024–8388608 per source response. Device, physical, and target mappings must be +unique. Distinct Devices may share a collector `instance`; their exact source +selectors remain distinct by Device UID. Each family/MemberId and +family/component pair must be unique. +Names/UIDs/revisions satisfy the projection's bounded identity rules. Sensor +strings are bounded to 256 bytes. Fan units must be `rpm`, temperature units +`celsius`. Component numbers are explicit stable assignments, never scrape +indices, hashes, truncated names, or identities reused after sensor replacement. + +The Prometheus URL must be HTTP or HTTPS without userinfo, query or fragment. +It is a **base URL**, not the query endpoint: for VictoriaMetrics use +`http://vmselect.monitoring.svc:8481/select/0/prometheus`, never +`http://vmselect.monitoring.svc:8481/select/0/prometheus/api/v1/query`. +The publisher appends `/api/v1/query` beneath the optional base path prefix. +Configuration containing an `/api/v1` path segment is rejected, not normalized. +Only that configured origin and query path are used. No redirects, arbitrary PromQL, target URLs, or incoming request +parameters are accepted. HTTP has a total timeout and a response byte limit; +HTTPS uses normal certificate verification. HTTP requires a protected cluster +network. The complete scrape shares the configured timeout across all Devices +and API calls, so timeout sizing must cover the configured batch. + +The Milo kubeconfig must address a root HTTPS endpoint with certificate +verification enabled and a client certificate or bearer token. Executable auth +plugins, basic auth, and impersonation are rejected. The same authenticated +client configuration is scoped to +`/apis/resourcemanager.miloapis.com/v1alpha1/projects//control-plane` +for Device reads. Static REST mappings avoid discovery permissions. This +configuration is trusted operator material. `projectAuthority` must equal the +verified root URL host (lowercase hostname with an optional port), and an explicit +TLS server-name override must equal that hostname. Arbitrary independent authority +aliases are rejected. The API server certificate and kubeconfig CA establish +that endpoint binding; a label cannot authenticate an authority. +No credentials belong in this JSON or Git. + +## Two independent evidence requirements + +**Authenticated inventory:** uncached typed GETs resolve the current named Milo +Project and namespaced Fleet Devices. Exact name, namespace, UID, +resourceVersion, and deletion state are checked. The configured Project UID is +an additional deployment admission pin, never a replacement for reading Milo. +A reused Project route or Device name fails closed. No custody, allocation, +Secrets, list, or watch rights are needed. Every source read is followed by fresh +Project and Device reads; any changed resourceVersion rejects the batch. Changes +between scrapes conservatively start a new session, even when unrelated to +ownership. API errors discard the session and all output. + +**Qualified physical mapping:** the protected mapping asserts that the exact +`job`, `cluster`, `instance`, and `device_uid` source belongs to that current +Device incarnation and an approved collector deployment. Sensor matching uses +exact family, MemberId (`id`), name, units, and context. Additional raw labels, +including incoming Project/visibility/component labels, never supply authority +or appear in output. The mapping needs a retained operator-reviewed evidence +record referenced by `evidenceRef`, a revision, and a qualification time. The +publisher validates structure and live inventory binding; it cannot validate +an audit reference's contents or turn a freely authored UID relabel into proof. + +Before constructing real configuration, the operator must retain the existing +qualification evidence for: physical asset to authenticated Device incarnation; +approved collector endpoint/deployment and protected scrape relabel ownership; +exact job/cluster/instance/Device UID mapping; firmware/unit/missingness behavior; +raw sensor tuples and permanent component assignments; and original timestamp +and diagnostics preservation. BMC serial or SystemUUID may corroborate the +physical match but **is not an authenticator**. Missing evidence means the mapping +is not qualified and publication must remain disabled. Updating qualification +requires a config revision and restart; existing component assignments must not +be reused for replacement sensors. This is an explicit operator trust boundary, +not a new inventory API or invented ownership coordinator. + +## Source timestamps and failure behavior + +A bounded instant API request uses a raw range selector: + +```promql +{__name__=~"up|fleet_hardware_collection_success|fleet_hardware_coverage_complete|fleet_hardware_collection_started_timestamp_seconds|idrac_sensors_fan_speed|idrac_sensors_temperature",job="qualified-hardware",cluster="central-staging",device_uid="synthetic-device-uid",instance="synthetic-raw-instance"}[300s] +``` + +The response must be a matrix of original stored samples, not an instant vector +or `query_range` evaluation grid. The latest `up` must be 1. Collection success +must be 1, coverage must be 0 or 1, and collection-start must be present. Each +latest diagnostic must have the **same exact stored timestamp as latest `up`**. +Thus failed exporter scrapes cannot reuse old success diagnostics. Federation or +recording that retimestamps samples cannot satisfy the qualified source contract. + +Coverage 0 is allowed: unavailable temperatures are absent, and valid qualified +fans/temperatures still publish. A sensor is emitted only when its latest stored +sample timestamp equals this successful scrape's timestamp. Old numeric samples +left in matrix lookback after a sensor disappears are omitted, never paired with +new success. Duplicate or unexpected current sensor identities reject the batch. +Missing/nonfinite values are omitted by the projection; actual zero and negative +Celsius survive. There is no interpolation or fabricated observation. + +Both the original stored timestamp and collector collection-start value must be +fresh. Collection-start must be strictly after session and mapping establishment; +the projection also requires the sample timestamp strictly after both. Prometheus +normally stamps at scrape request start, slightly before the collector starts; +the absolute difference is bounded by the configured timeout. Millisecond stored +timestamps are preserved through JSON float conversion and text exposition. +Neither timestamp proves when the BMC physically measured its sensor. Firmware +freshness and calibration remain qualification evidence outside this adapter. + +The first successful authority observation returns an empty 200 and starts a +random process-local session. Subsequent samples from before that session are +not backfilled. On any collection/authority/config error, the endpoint returns +503 without metrics and invalidates the session. Timestamp-coherence failure +returns the bounded internal reason `source_timestamp_mismatch`; duplicate +diagnostics return `source_identity_conflict`. Errors never include raw labels, +source URLs, or credentials. Concurrent scrapes return 503 +rather than queue stale authority reads. No cached result receives a new timestamp +or a fresh TTL. A whole batch is buffered and verified before any metric bytes +are sent. There is no automatic retry or background publication. + +The final reads are **not atomic with HTTP output**. Ownership/deletion can change +after the last API read, and an unobserved change-and-return between observations +cannot be detected without an ownership epoch. Current APIs supply no such epoch. +A short scrape timeout bounds this residual observation-to-output race but does +not fence it. Project/Device UIDs and protected mapping prevent name reuse from +relabeling published samples; they do not isolate retained history under the +existing Project-name query/export authorization. No +allocation gating or coordinator is added, and no strict publication fencing or +runtime readiness is claimed. + +## Independent central-staging rollout plan + +Build a separate image from +[`build/device-hardware-publisher.Dockerfile`](../../../build/device-hardware-publisher.Dockerfile). +Do not replace the diverged deployed manager or the raw collector image/service. +Infra owns an independent Deployment, read-only qualification ConfigMap, reader +certificate mount, ClusterIP Service port 9090, and NetworkPolicy. Use a separate +reader identity with only `get` of the one named Milo Project and `get` of the +configured namespaced Device names in that Project control plane. Broader Device +list/watch, Secrets, custody, allocation, write, and wildcard rights are not used. +The platform may deliver a certificate via a mounted Secret; the reader does not +need Kubernetes Secrets API access. + +Allow ingress only from the shared operator Prometheus scraper. Allow egress only +to DNS, the pinned Milo API endpoint, and the operator Prometheus source service. +Scrape `/metrics` with `honor_timestamps: true`; do not attach or override any +of the seven product labels. Disable label collisions and avoid a second writer +for these metric families. Narrow resource-store federation must select exactly +`datum_fleet_device_hardware_fan_speed_rpm` and +`datum_fleet_device_hardware_temperature_celsius`, require +`visibility="inventory_owner"`, preserve timestamps and all seven labels, and +remove scrape transport labels. Raw/diagnostic families must never federate. +Use the existing customer Project-name authorization for query, metadata, +discovery, and export; verify ordinary cross-Project isolation and the narrow +federation allowlist during rollout. Project recreation, IAM migration, and +UID-pinned query rollout are deferred and are not activation prerequisites. The +real raw pipeline must demonstrate timestamp coherence and qualified physical +mapping before live publication. Synthetic tests do not establish those facts. + +## Image build and publication + +The separate [publisher workflow](../../../.github/workflows/publish-device-hardware-publisher.yml) +uses the same pinned reusable image publisher as the other Fleet images. It builds +`ghcr.io/datum-cloud/fleet-device-hardware-publisher` for `linux/amd64` and +`linux/arm64` on pushes and published releases, or manual dispatch. It does not +update the manager, raw collector, or kustomize bundle. Image publication depends +on a focused race-test and vet job in that workflow, including manual and release +runs. Existing CI also includes the publisher in `go test ./...`, race tests, and +vet. + +From a reviewed, committed release checkout, build and publish only this image: + +```sh +publisher_revision=$(git rev-parse HEAD) +docker buildx build --platform linux/amd64,linux/arm64 \ + --file build/device-hardware-publisher.Dockerfile \ + --tag "ghcr.io/datum-cloud/fleet-device-hardware-publisher:sha-${publisher_revision}" \ + --metadata-file /tmp/fleet-device-hardware-publisher-build.json --push . +``` + +This command requires an authenticated registry session and a multi-platform +Buildx builder. The workflow generates the repository's standard version and SHA +tags instead. Tags identify builds but are mutable registry references: resolve +the published manifest digest and configure the independent Deployment image as +`ghcr.io/datum-cloud/fleet-device-hardware-publisher@sha256:`. +Record that digest with the source commit and qualification revision. The local +command's Buildx metadata records `containerimage.digest`. No container build, +registry publication, or live rollout is established by the checks below. + +The Dockerfile cross-compiles a static Go binary (`CGO_ENABLED=0`) using pinned +Go 1.27.4 and distroless nonroot base digests. The entrypoint is +`/fleet-device-hardware-publisher`; pass `--config=/etc/fleet-publisher/config.json` +and optionally `--listen-address=:9090`. Mount configuration and reader credentials +read-only and deploy the digest matching the cluster architecture (the combined +manifest supports both architectures). + +## Local validation + +```sh +go test -count=1 -race ./internal/devicehardwarepublisher ./internal/devicehardwaremetrics ./internal/hardwaremetrics ./cmd/fleet-device-hardware-publisher +go build -o /tmp/fleet-device-hardware-publisher ./cmd/fleet-device-hardware-publisher +bash hack/validate-doc-links.sh +git diff --check +``` + +Tests use synthetic HTTP API/source servers and no credentials or hardware. They +cover exact source queries, partial coverage, valid zero, original timestamps, +missing sensors in later scrapes, failed scrape/collection diagnostics, mismatched +identity, Project recreation, Device replacement/deletion, API failure, changed +revisions/config, no-backfill sessions, bounded responses, redirects, timeouts, +and concurrent scrapes. An authenticated HTTPS fixture constructs the production +publisher from its kubeconfig, checks exact output and credential separation, +and exercises authorization/source failure recovery without session backfill. +They do not establish real qualification, deployment, +query isolation, or hardware measurement freshness. diff --git a/docs/enhancements/hardware-telemetry/resource-metadata.md b/docs/enhancements/hardware-telemetry/resource-metadata.md new file mode 100644 index 00000000..a61cba2d --- /dev/null +++ b/docs/enhancements/hardware-telemetry/resource-metadata.md @@ -0,0 +1,112 @@ +# Fleet-owned resource metadata + +## Implemented packaging, not a deployed service + +The optional [policy bundle](../../../config/components/resource-metrics/README.md) +adds a control-plane metadata feed alongside, not inside, the +[Device sensor publisher](device-owner-publisher.md). Fleet owns policy content; +resource-metrics owns object observation, CEL evaluation, and OTLP emission. +The sensor publisher remains an independent direct inventory reader. Neither +feed synchronously depends on the other, and no metrics join supplies authority. +No sensor samples enter Device status, and no external Prometheus query extension +is added to resource-metrics. Shared telemetry still owns ingestion and access. + +Compatibility was inspected against the local `milo-os/resource-metrics` source +at `79dfc204b62f924d96760105af391895af937ebe`, specifically +`api/v1alpha1/custom_resource_metrics_types.go`, `internal/policy/cel.go`, +`internal/metrics/naming.go`, `internal/otel/runtime.go`, and the sample policy. +This is a source compatibility observation, not a dependency upgrade or proof of +the deployed version. Fleet's actual [Device API](../../../internal/api/inventory/v1alpha1/types.go) +and [CRD](../../../config/components/inventory/crds/fleet.datumapis.com.yaml) +are authoritative over illustrative proposal fields. + +## Narrow metric contract + +`fleet_device_info` is a gauge of `1.0` for each observed namespaced Device. +The explicit `fleet` policy prefix avoids dependence on the controller default. +Its only policy labels are: + +| Label | Source | Meaning | +| --- | --- | --- | +| `device` | `metadata.name` | API record name, not a physical serial | +| `namespace` | `metadata.namespace` | Namespace inside the observed control plane | +| `device_uid` | `metadata.uid` | Device record incarnation, not Project identity | +| `lifecycle` | `spec.lifecycle` | Declared asset service state | + +Lifecycle is `Active`, `Decommissioning`, or `Retired`. Missing or empty lifecycle +means `Active`, matching the CRD default and `LifecycleOf`; an unexpected string +maps to `Unknown`, never readiness. Device status is empty. There is no status +phase, condition, sensor measurement, capacity availability, allocation, custody, +installation, managed node, or health inference in this policy. An Active record +is not proof of verification, spare capacity, ownership transfer, or permission +to operate hardware. Retired records remain observable until deleted. + +No serial, asset tag, BMC address/reference, MAC, provider identifier, placement, +display name, arbitrary annotation, or arbitrary label is exported. API record +names must themselves follow the operator's safe naming policy. Reader access +still exposes the full object; label filtering is not an API access boundary. +UID changes distinguish Device recreation. A lifecycle change changes the series +labels; deletion stops new observations rather than emitting a zero/tombstone. +Stored historical series and backend staleness remain telemetry concerns. + +## Actual Project attributes and transforms + +At the inspected revision, `attrsFor` adds **`milo.project.name`** using +`strings.TrimPrefix(clusterName, "/")` and **`milo.control_plane.type`** using +`root` only for cluster name `root`, otherwise `project`. It does **not** attach +Project UID. The upstream architecture prose claiming automatic Project UID +attachment does not match this runtime. Policies evaluate the Device object, +not a Project object; no fabricated UID or annotation lookup fills the gap. + +The upstream `test/e2e/metrics-emission/chainsaw-test.yaml` and +`test/e2e/root-metrics-emission/chainsaw-test.yaml` assert the remote-write path's +dot-to-underscore label normalization: `milo_project_name` and +`milo_control_plane_type`. These fixtures were inspected, not run here. The +runtime emits dotted OTLP keys; the deployment's downstream collector/exporter +determines final stored label spelling. Do not assume that every OTLP backend +uses the fixture transform, or confuse the sensor publisher's explicit +`project_uid` with an attribute available on this metadata feed. + +Before using a query, capture a real OTLP data point and its stored series and +verify both identity and label transformation in that environment. Name-based +Project query grants remain the initial boundary; this work does not implement +UID-pinned grants or Project-recreation isolation. A label is never a grant. + +## Authorization and rollout gates + +1. Confirm the installed ResourceMetricsPolicy CRD/runtime supports the inspected + contract and the Fleet Device API exists in the intended project control planes. + Policies are cluster-scoped on the management plane and apply to all discovered + project control planes; this API has no per-project policy selector. +2. Approve and identify the exact resource-metrics principal independently of the + sensor publisher. Upstream `config/rbac/README.md` describes a per-project + aggregated reader role and a bootstrap binding; the optional Fleet + `project-reader` supplies only a narrow Devices reader role. Determine whether + the actual Milo authorization path honors that RBAC, requires IAM grants, or + requires another qualified binding. Existing Fleet IAM Role definitions are + not proof of effective access. The upstream Milo example's `system:masters` + client certificate is not least-privilege qualification. +3. Verify discovery and get/list/watch as that principal in each intended project, + and denial for unapproved projects/resources and all mutations. Verify missing + permissions are reported and informer/cache failures cannot masquerade as + healthy zero inventory. No binding, credential, or live authorization test is + supplied here. Root collection requires separate explicit RBAC and review; + this project reader package does not enable or authorize it. +4. Validate OTLP delivery, exact labels, deletion/staleness, Device recreation, + Project-name routing, and cross-Project query/export denial. Existing shared + ingestion credentials and name-based grants must be qualified independently. +5. Opt in to the policy only after those gates. Do not enable a Fleet or sensor + deployment merely to install metadata. Roll back by removing this optional + policy and its separately installed reader role, preserving unrelated readers + and publisher operation. Historical data retention is unchanged. + +## Local evidence and limits + +The bundle's Go tests use Fleet's existing CEL and YAML dependencies and real +Device structs serialized to JSON. They compile/evaluate the shipped expressions +for default and explicit lifecycle states, unexpected lifecycle, missing identity, +Device recreation, and private-field exclusion. Local Kustomize rendering checks +the independent policy/reader packages. These tests do not execute upstream +controller informers, upstream sanitization, CRD admission, transport, aggregation, +IAM, or customer query enforcement. Those remain rollout prerequisites, not +implemented or verified deployment behavior. diff --git a/internal/devicehardwaremetrics/projection.go b/internal/devicehardwaremetrics/projection.go new file mode 100644 index 00000000..ebb3c32e --- /dev/null +++ b/internal/devicehardwaremetrics/projection.go @@ -0,0 +1,234 @@ +// Package devicehardwaremetrics projects current samples for inventory-owning +// projects. It provides no authority reader, production proof, or publisher. +package devicehardwaremetrics + +import ( + "errors" + "math" + "regexp" + "strconv" + "time" +) + +const ( + ProjectLabel = "resourcemanager_datumapis_com_project_name" + FanFamily = "idrac_sensors_fan_speed" + TemperatureFamily = "idrac_sensors_temperature" + MaxComponent = 4095 + Visibility = "inventory_owner" +) + +var ( + ErrAuthorityUnavailable = errors.New("device hardware metric authority unavailable") + ErrDuplicateReading = errors.New("duplicate device hardware reading identity") + identifier = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,252}$`) + deviceName = regexp.MustCompile(`^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$`) +) + +// Evidence identifies a trusted adapter's authoritative read. A string revision +// or a recent timestamp supplied by an untrusted caller is not proof. +type Evidence struct { + Revision string + ObservedAt time.Time +} + +type Project struct { + AuthorityID, Name, UID string + Evidence Evidence + Deleting bool +} + +type Device struct { + Name, UID string + Evidence Evidence + Deleting bool + // OwnershipID changes on every ownership transition, including A -> B -> A. + OwnershipID string + OwnedSince time.Time +} + +// Sensor is a stable, qualified adapter-assigned identity, not a scrape index +// or a truncated/hash-derived arbitrary BMC label. Each family needs unit and +// missingness qualification for the physical target's hardware/firmware. +type Sensor struct { + Family string + Component uint32 +} + +type Mapping struct { + Evidence Evidence + DeviceUID, PhysicalID, TargetID string + ValidSince time.Time + Sensors []Sensor +} + +type Binding struct { + Device Device + Project Project + Mapping Mapping +} + +// Snapshot is an immutable adapter result, not an API or an authentication +// mechanism. Complete requires coherent coverage of all relevant authorities; +// see the component contract before implementing an adapter. +type Snapshot struct { + Evidence Evidence + Complete bool + Bindings []Binding +} + +type Policy struct { + MaxAuthorityAge, MaxSampleAge time.Duration +} + +// Reading's identity is attached by the trusted collector before collection, +// never reconstructed from incoming metric labels after ownership changes. +type Reading struct { + DeviceUID, OwnershipID, MappingRevision string + ProjectUID, ProjectAuthority string + Sensor Sensor + Value *float64 + ObservedAt time.Time + Labels map[string]string +} + +type Series struct { + Name string + Labels map[string]string + Value float64 + Timestamp time.Time +} + +// ProjectReadings fails the entire batch closed on invalid or ambiguous +// authority. Invalid values/families are omitted; duplicate sensor identities +// reject the batch even if one duplicate has an invalid value. +// Inputs must remain immutable for the duration of the call. +func ProjectReadings(now time.Time, policy Policy, snapshot Snapshot, readings []Reading) ([]Series, error) { + if now.IsZero() || policy.MaxAuthorityAge <= 0 || policy.MaxSampleAge <= 0 || !snapshot.Complete || + !validEvidence(now, snapshot.Evidence, policy.MaxAuthorityAge) { + return nil, ErrAuthorityUnavailable + } + bindings := make(map[string]Binding) + physical, targets, names := make(map[string]bool), make(map[string]bool), make(map[string]bool) + projectsByRoute, projectsByUID := make(map[string]Project), make(map[string]Project) + for _, b := range snapshot.Bindings { + if !b.valid(now, policy, snapshot.Evidence.ObservedAt) { + return nil, ErrAuthorityUnavailable + } + nameKey := b.Project.AuthorityID + "\x00" + b.Project.UID + "\x00" + b.Device.Name + if _, exists := bindings[b.Device.UID]; exists || physical[b.Mapping.PhysicalID] || targets[b.Mapping.TargetID] || names[nameKey] { + return nil, ErrAuthorityUnavailable + } + // The existing transport routes by project name alone. Reject even + // cross-authority route collisions rather than relying on extra labels. + uidKey := b.Project.AuthorityID + "\x00" + b.Project.UID + if previous, ok := projectsByRoute[b.Project.Name]; ok && previous != b.Project { + return nil, ErrAuthorityUnavailable + } + if previous, ok := projectsByUID[uidKey]; ok && previous != b.Project { + return nil, ErrAuthorityUnavailable + } + bindings[b.Device.UID] = b + physical[b.Mapping.PhysicalID], targets[b.Mapping.TargetID], names[nameKey] = true, true, true + projectsByRoute[b.Project.Name], projectsByUID[uidKey] = b.Project, b.Project + } + seen := make(map[string]bool) + var result []Series + for _, r := range readings { + key := r.DeviceUID + "\x00" + r.Sensor.Family + "\x00" + strconv.FormatUint(uint64(r.Sensor.Component), 10) + if seen[key] { + return nil, ErrDuplicateReading + } + seen[key] = true + b, found := bindings[r.DeviceUID] + if !found || r.OwnershipID != b.Device.OwnershipID || r.MappingRevision != b.Mapping.Evidence.Revision || + r.ProjectUID != b.Project.UID || r.ProjectAuthority != b.Project.AuthorityID || + !fresh(now, r.ObservedAt, policy.MaxSampleAge) || !r.ObservedAt.After(b.Device.OwnedSince) || + !r.ObservedAt.After(b.Mapping.ValidSince) || + r.Value == nil || math.IsNaN(*r.Value) || math.IsInf(*r.Value, 0) { + continue + } + // All final authority reads must follow collection, not just snapshot assembly. + if r.ObservedAt.After(b.Device.Evidence.ObservedAt) || r.ObservedAt.After(b.Project.Evidence.ObservedAt) || + r.ObservedAt.After(b.Mapping.Evidence.ObservedAt) { + continue + } + qualified := false + for _, sensor := range b.Mapping.Sensors { + if sensor == r.Sensor { + qualified = true + break + } + } + if !qualified { + continue + } + name := outputFamily(r.Sensor.Family) + if name == "" || (r.Sensor.Family == FanFamily && *r.Value < 0) { + continue + } + result = append(result, Series{ + Name: name, Value: *r.Value, Timestamp: r.ObservedAt, + Labels: map[string]string{ + ProjectLabel: b.Project.Name, "project_uid": b.Project.UID, "project_authority": b.Project.AuthorityID, + "device": b.Device.Name, "device_uid": b.Device.UID, + "visibility": Visibility, + "component": strconv.FormatUint(uint64(r.Sensor.Component), 10), + }, + }) + } + return result, nil +} + +func (b Binding) valid(now time.Time, policy Policy, snapshotTime time.Time) bool { + for _, value := range []string{b.Device.UID, b.Device.OwnershipID, b.Project.AuthorityID, b.Project.Name, b.Project.UID, + b.Mapping.DeviceUID, b.Mapping.PhysicalID, b.Mapping.TargetID} { + if !identifier.MatchString(value) { + return false + } + } + if !deviceName.MatchString(b.Device.Name) || b.Device.Deleting || b.Project.Deleting || + b.Mapping.DeviceUID != b.Device.UID { + return false + } + for _, e := range []Evidence{b.Device.Evidence, b.Project.Evidence, b.Mapping.Evidence} { + if !validEvidence(now, e, policy.MaxAuthorityAge) || e.ObservedAt.After(snapshotTime) { + return false + } + } + if !started(b.Device.OwnedSince, b.Device.Evidence.ObservedAt) || !started(b.Mapping.ValidSince, b.Mapping.Evidence.ObservedAt) { + return false + } + if len(b.Mapping.Sensors) == 0 || len(b.Mapping.Sensors) > 2*(MaxComponent+1) { + return false + } + seen := make(map[Sensor]bool) + for _, sensor := range b.Mapping.Sensors { + if outputFamily(sensor.Family) == "" || sensor.Component > MaxComponent || seen[sensor] { + return false + } + seen[sensor] = true + } + return true +} + +func outputFamily(family string) string { + switch family { + case FanFamily: + return "datum_fleet_device_hardware_fan_speed_rpm" + case TemperatureFamily: + return "datum_fleet_device_hardware_temperature_celsius" + default: + return "" + } +} + +func validEvidence(now time.Time, evidence Evidence, maximum time.Duration) bool { + return identifier.MatchString(evidence.Revision) && fresh(now, evidence.ObservedAt, maximum) +} + +func started(start, observed time.Time) bool { return !start.IsZero() && !start.After(observed) } + +func fresh(now, observed time.Time, maximum time.Duration) bool { + return !observed.IsZero() && !observed.After(now) && now.Sub(observed) < maximum +} diff --git a/internal/devicehardwaremetrics/projection_test.go b/internal/devicehardwaremetrics/projection_test.go new file mode 100644 index 00000000..c405d19f --- /dev/null +++ b/internal/devicehardwaremetrics/projection_test.go @@ -0,0 +1,378 @@ +package devicehardwaremetrics + +import ( + "errors" + "math" + "reflect" + "testing" + "time" +) + +func fixture() (time.Time, Policy, Snapshot, Reading) { + now := time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC) + e := Evidence{Revision: "revision-1", ObservedAt: now} + since := now.Add(-time.Hour) + snapshot := Snapshot{Evidence: e, Complete: true, Bindings: []Binding{{ + Device: Device{Name: "server-1", UID: "device-1", Evidence: e, OwnershipID: "owner-1", OwnedSince: since}, + Project: Project{AuthorityID: "milo-example", Name: "project-a", UID: "project-uid-a", Evidence: e}, + Mapping: Mapping{Evidence: e, DeviceUID: "device-1", PhysicalID: "physical-1", TargetID: "target-1", ValidSince: since, + Sensors: []Sensor{{FanFamily, 1}, {TemperatureFamily, 2}}}, + }}} + value := 1200.0 + r := Reading{DeviceUID: "device-1", OwnershipID: "owner-1", MappingRevision: "revision-1", ProjectUID: "project-uid-a", ProjectAuthority: "milo-example", + Sensor: Sensor{FanFamily, 1}, Value: &value, ObservedAt: now.Add(-time.Second)} + return now, Policy{MaxAuthorityAge: time.Minute, MaxSampleAge: 2 * time.Minute}, snapshot, r +} + +func TestExactOutputContract(t *testing.T) { + now, p, s, r := fixture() + r.Labels = map[string]string{ProjectLabel: "victim", "project_uid": "forged", "device_uid": "forged", "component": "secret", "serial": "secret", "instance": "private-address"} + got, err := ProjectReadings(now, p, s, []Reading{r}) + want := map[string]string{ProjectLabel: "project-a", "project_uid": "project-uid-a", "project_authority": "milo-example", "device": "server-1", "device_uid": "device-1", "component": "1", "visibility": "inventory_owner"} + if err != nil || len(got) != 1 { + t.Fatalf("projection: %v %v", got, err) + } + if got[0].Name != "datum_fleet_device_hardware_fan_speed_rpm" || !reflect.DeepEqual(got[0].Labels, want) || got[0].Value != *r.Value || !got[0].Timestamp.Equal(r.ObservedAt) { + t.Fatalf("output: %#v", got[0]) + } + got[0].Labels[ProjectLabel] = "mutated" + if s.Bindings[0].Project.Name != "project-a" || r.Labels[ProjectLabel] != "victim" { + t.Fatal("mutated inputs") + } +} + +func TestAuthorityFailsClosed(t *testing.T) { + cases := map[string]func(*Snapshot){ + "incomplete": func(s *Snapshot) { s.Complete = false }, + "missing snapshot revision": func(s *Snapshot) { s.Evidence.Revision = "" }, + "missing snapshot time": func(s *Snapshot) { s.Evidence.ObservedAt = time.Time{} }, + "future snapshot": func(s *Snapshot) { s.Evidence.ObservedAt = s.Evidence.ObservedAt.Add(time.Second) }, + "stale snapshot": func(s *Snapshot) { s.Evidence.ObservedAt = s.Evidence.ObservedAt.Add(-time.Minute) }, + "assembly predates records": func(s *Snapshot) { s.Evidence.ObservedAt = s.Evidence.ObservedAt.Add(-time.Second) }, + "device deleting": func(s *Snapshot) { s.Bindings[0].Device.Deleting = true }, + "project deleting": func(s *Snapshot) { s.Bindings[0].Project.Deleting = true }, + "missing device UID": func(s *Snapshot) { s.Bindings[0].Device.UID = "" }, + "unsafe device name": func(s *Snapshot) { s.Bindings[0].Device.Name = "server\nserial=secret" }, + "missing ownership": func(s *Snapshot) { s.Bindings[0].Device.OwnershipID = "" }, + "missing ownership start": func(s *Snapshot) { s.Bindings[0].Device.OwnedSince = time.Time{} }, + "future ownership": func(s *Snapshot) { s.Bindings[0].Device.OwnedSince = s.Evidence.ObservedAt.Add(time.Second) }, + "missing project UID": func(s *Snapshot) { s.Bindings[0].Project.UID = "" }, + "missing project authority": func(s *Snapshot) { s.Bindings[0].Project.AuthorityID = "" }, + "missing route": func(s *Snapshot) { s.Bindings[0].Project.Name = "" }, + "unsafe project UID": func(s *Snapshot) { s.Bindings[0].Project.UID = "x\x00y" }, + "missing mapping": func(s *Snapshot) { s.Bindings[0].Mapping = Mapping{} }, + "wrong mapping device": func(s *Snapshot) { s.Bindings[0].Mapping.DeviceUID = "other" }, + "missing physical identity": func(s *Snapshot) { s.Bindings[0].Mapping.PhysicalID = "" }, + "missing target": func(s *Snapshot) { s.Bindings[0].Mapping.TargetID = "" }, + "no qualified sensors": func(s *Snapshot) { s.Bindings[0].Mapping.Sensors = nil }, + "unknown qualified family": func(s *Snapshot) { s.Bindings[0].Mapping.Sensors[0].Family = "power" }, + "unbounded component": func(s *Snapshot) { s.Bindings[0].Mapping.Sensors[0].Component = MaxComponent + 1 }, + "duplicate sensor mapping": func(s *Snapshot) { + s.Bindings[0].Mapping.Sensors = append(s.Bindings[0].Mapping.Sensors, s.Bindings[0].Mapping.Sensors[0]) + }, + "duplicate device": func(s *Snapshot) { s.Bindings = append(s.Bindings, s.Bindings[0]) }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + now, p, s, r := fixture() + mutate(&s) + got, err := ProjectReadings(now, p, s, []Reading{r}) + if !errors.Is(err, ErrAuthorityUnavailable) || len(got) != 0 { + t.Fatalf("unsafe output: %v %v", got, err) + } + }) + } + for _, record := range []string{"device", "project", "mapping"} { + for _, failure := range []string{"missing revision", "missing time", "stale", "future"} { + t.Run(record+"/"+failure, func(t *testing.T) { + now, p, s, r := fixture() + b := &s.Bindings[0] + e := map[string]*Evidence{"device": &b.Device.Evidence, "project": &b.Project.Evidence, "mapping": &b.Mapping.Evidence}[record] + switch failure { + case "missing revision": + e.Revision = "" + case "missing time": + e.ObservedAt = time.Time{} + case "stale": + e.ObservedAt = now.Add(-p.MaxAuthorityAge) + case "future": + e.ObservedAt = now.Add(time.Second) + } + got, err := ProjectReadings(now, p, s, []Reading{r}) + if err == nil || len(got) != 0 { + t.Fatalf("unsafe output: %v %v", got, err) + } + }) + } + } +} + +func TestInvalidSamplesAreOmitted(t *testing.T) { + cases := map[string]func(*Reading){ + "unknown device": func(r *Reading) { r.DeviceUID = "unknown" }, + "missing project UID": func(r *Reading) { r.ProjectUID = "" }, + "missing project authority": func(r *Reading) { r.ProjectAuthority = "" }, + "old owner": func(r *Reading) { r.OwnershipID = "old" }, + "old mapping": func(r *Reading) { r.MappingRevision = "old" }, + "missing": func(r *Reading) { r.Value = nil }, + "NaN": func(r *Reading) { v := math.NaN(); r.Value = &v }, + "positive infinity": func(r *Reading) { v := math.Inf(1); r.Value = &v }, + "negative infinity": func(r *Reading) { v := math.Inf(-1); r.Value = &v }, + "negative rpm": func(r *Reading) { v := -1.0; r.Value = &v }, + "unqualified sensor": func(r *Reading) { r.Sensor.Component = 3 }, + "power": func(r *Reading) { r.Sensor.Family = "idrac_power_consumed_watts" }, + "missing timestamp": func(r *Reading) { r.ObservedAt = time.Time{} }, + "future": func(r *Reading) { r.ObservedAt = r.ObservedAt.Add(2 * time.Second) }, + "stale boundary": func(r *Reading) { r.ObservedAt = r.ObservedAt.Add(-2*time.Minute + time.Second) }, + } + for name, mutate := range cases { + t.Run(name, func(t *testing.T) { + now, p, s, r := fixture() + mutate(&r) + got, err := ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 0 { + t.Fatalf("unsafe output: %v %v", got, err) + } + }) + } + for _, record := range []string{"device", "project", "mapping"} { + t.Run("sample after "+record, func(t *testing.T) { + now, p, s, r := fixture() + b := &s.Bindings[0] + e := map[string]*Evidence{"device": &b.Device.Evidence, "project": &b.Project.Evidence, "mapping": &b.Mapping.Evidence}[record] + e.ObservedAt = r.ObservedAt.Add(-time.Nanosecond) + got, err := ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 0 { + t.Fatalf("unsafe output: %v %v", got, err) + } + }) + } +} + +func TestDuplicateReadingsRejectWholeBatch(t *testing.T) { + for _, invalid := range []bool{false, true} { + now, p, s, r := fixture() + duplicate := r + if invalid { + duplicate.Value = nil + duplicate.OwnershipID = "old" + } + got, err := ProjectReadings(now, p, s, []Reading{r, duplicate}) + if !errors.Is(err, ErrDuplicateReading) || len(got) != 0 { + t.Fatalf("duplicates: %v %v", got, err) + } + } +} + +func secondBinding(s Snapshot) Binding { + b := s.Bindings[0] + b.Device.UID = "device-2" + b.Device.Name = "server-2" + b.Mapping.DeviceUID = "device-2" + b.Mapping.PhysicalID = "physical-2" + b.Mapping.TargetID = "target-2" + return b +} + +func TestAmbiguousAuthorityRejectsWholeBatch(t *testing.T) { + for _, conflict := range []string{"physical", "target", "device name", "route UID", "route authority", "UID route"} { + t.Run(conflict, func(t *testing.T) { + now, p, s, r := fixture() + b := secondBinding(s) + switch conflict { + case "physical": + b.Mapping.PhysicalID = s.Bindings[0].Mapping.PhysicalID + case "target": + b.Mapping.TargetID = s.Bindings[0].Mapping.TargetID + case "device name": + b.Device.Name = s.Bindings[0].Device.Name + case "route UID": + b.Project.UID = "other" + case "route authority": + b.Project.AuthorityID = "other" + case "UID route": + b.Project.Name = "other" + } + s.Bindings = append(s.Bindings, b) + got, err := ProjectReadings(now, p, s, []Reading{r}) + if err == nil || len(got) != 0 { + t.Fatalf("ambiguous output: %v %v", got, err) + } + }) + } +} + +func TestDeviceReplacementDoesNotRelabelOldReading(t *testing.T) { + now, policy, snapshot, oldReading := fixture() + replacement := secondBinding(snapshot) + replacement.Device.Name = snapshot.Bindings[0].Device.Name + snapshot.Bindings[0] = replacement + series, err := ProjectReadings(now, policy, snapshot, []Reading{oldReading}) + if err != nil || len(series) != 0 { + t.Fatalf("old incarnation projected: %v %v", series, err) + } + newReading := oldReading + newReading.DeviceUID = replacement.Device.UID + series, err = ProjectReadings(now, policy, snapshot, []Reading{newReading}) + if err != nil || len(series) != 1 { + t.Fatalf("replacement projection: %v %v", series, err) + } + if series[0].Labels["device_uid"] != replacement.Device.UID || series[0].Labels["device"] != replacement.Device.Name { + t.Fatalf("replacement identity: %v", series[0].Labels) + } +} + +func TestTwoDevicesAndProjects(t *testing.T) { + for _, sameProject := range []bool{false, true} { + now, p, s, r := fixture() + b := secondBinding(s) + if !sameProject { + b.Project.Name = "project-b" + b.Project.UID = "project-uid-b" + } + s.Bindings = append(s.Bindings, b) + r2 := r + r2.DeviceUID = b.Device.UID + r2.ProjectUID = b.Project.UID + got, err := ProjectReadings(now, p, s, []Reading{r, r2}) + if err != nil || len(got) != 2 || got[0].Labels[ProjectLabel] != "project-a" || got[1].Labels[ProjectLabel] != b.Project.Name { + t.Fatalf("project isolation: %v %v", got, err) + } + } +} + +func TestOwnershipAndMappingTransitions(t *testing.T) { + for _, transition := range []string{"owner", "mapping"} { + t.Run(transition, func(t *testing.T) { + now, p, s, r := fixture() + history, err := ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(history) != 1 { + t.Fatal(err) + } + b := &s.Bindings[0] + switch transition { + case "owner": + b.Device.OwnershipID = "owner-2" + b.Device.OwnedSince = now + b.Project.UID = "recreated-project" + case "mapping": + b.Mapping.Evidence.Revision = "revision-2" + b.Mapping.ValidSince = now + } + got, _ := ProjectReadings(now, p, s, []Reading{r}) + if len(got) != 0 { + t.Fatal("old reading relabeled") + } + r.OwnershipID = b.Device.OwnershipID + r.ProjectUID = b.Project.UID + r.MappingRevision = b.Mapping.Evidence.Revision + r.ObservedAt = now + got, _ = ProjectReadings(now, p, s, []Reading{r}) + if len(got) != 0 { + t.Fatal("transition timestamp is ambiguous") + } + now = now.Add(time.Second) + r.ObservedAt = now + s.Evidence.ObservedAt = now + b.Device.Evidence.ObservedAt = now + b.Project.Evidence.ObservedAt = now + b.Mapping.Evidence.ObservedAt = now + got, err = ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 1 || history[0].Labels["project_uid"] != "project-uid-a" { + t.Fatalf("new period or retained history: %v %v %v", history, got, err) + } + }) + } +} + +func TestNumericAndFreshnessBoundaries(t *testing.T) { + now, p, s, r := fixture() + for _, sensor := range s.Bindings[0].Mapping.Sensors { + for _, value := range []float64{0, 20} { + r.Sensor = sensor + r.Value = &value + r.ObservedAt = now + got, err := ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 1 || got[0].Name != outputFamily(sensor.Family) || got[0].Value != value { + t.Fatalf("valid reading: %v %v", got, err) + } + } + } + r.Sensor = Sensor{TemperatureFamily, 2} + v := -20.0 + r.Value = &v + got, err := ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 1 { + t.Fatal("negative temperature lost") + } + r.ObservedAt = now.Add(-p.MaxSampleAge + time.Nanosecond) + got, err = ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 1 { + t.Fatal("fresh boundary lost") + } + for _, policy := range []Policy{{}, {MaxAuthorityAge: time.Minute}, {MaxSampleAge: time.Minute}} { + got, err = ProjectReadings(now, policy, s, []Reading{r}) + if err == nil || len(got) != 0 { + t.Fatal("invalid policy") + } + } + s.Bindings = nil + got, err = ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 0 { + t.Fatal("missing binding produced data") + } +} + +func TestConcurrentImmutableProjection(t *testing.T) { + now, p, s, r := fixture() + for range 16 { + t.Run("concurrent", func(t *testing.T) { + t.Parallel() + got, err := ProjectReadings(now, p, s, []Reading{r}) + if err != nil || len(got) != 1 { + t.Fatalf("projection: %v %v", got, err) + } + }) + } +} +func TestProjectLifetimeChangeDoesNotRelabelOldReading(t *testing.T) { + for _, change := range []string{"UID", "authority", "route", "ownership cycle"} { + t.Run(change, func(t *testing.T) { + now, policy, snapshot, reading := fixture() + history, err := ProjectReadings(now, policy, snapshot, []Reading{reading}) + if err != nil || len(history) != 1 { + t.Fatalf("initial projection: %v %v", history, err) + } + b := &snapshot.Bindings[0] + switch change { + case "UID": + b.Project.UID = "recreated-project" + case "authority": + b.Project.AuthorityID = "other-authority" + case "route": + b.Project.Name = "project-b" + b.Project.UID = "project-b-uid" + case "ownership cycle": + b.Device.OwnershipID = "owner-a-returned" + } + got, err := ProjectReadings(now, policy, snapshot, []Reading{reading}) + if err != nil || len(got) != 0 { + t.Fatalf("old identity relabeled: %v %v", got, err) + } + if history[0].Labels["project_uid"] != "project-uid-a" || history[0].Labels["project_authority"] != "milo-example" { + t.Fatal("retained history changed") + } + }) + } +} + +func TestConflictingProjectEvidenceRejectsWholeBatch(t *testing.T) { + now, policy, snapshot, reading := fixture() + other := secondBinding(snapshot) + other.Project.Evidence.Revision = "different-project-version" + snapshot.Bindings = append(snapshot.Bindings, other) + series, err := ProjectReadings(now, policy, snapshot, []Reading{reading}) + if !errors.Is(err, ErrAuthorityUnavailable) || len(series) != 0 { + t.Fatalf("incoherent Project identity accepted: %v %v", series, err) + } +} diff --git a/internal/devicehardwarepublisher/authenticated_test.go b/internal/devicehardwarepublisher/authenticated_test.go new file mode 100644 index 00000000..60d50150 --- /dev/null +++ b/internal/devicehardwarepublisher/authenticated_test.go @@ -0,0 +1,123 @@ +package devicehardwarepublisher + +import ( + "encoding/base64" + "encoding/json" + "encoding/pem" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestAuthenticatedPublisherRecovery(t *testing.T) { + config := fixtureConfig() + fixture := &apiFixture{projectUID: config.ProjectUID, deviceUID: config.Devices[0].UID, revision: "1"} + var denied atomic.Bool + var inventoryCalls atomic.Int64 + inventoryServer := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + inventoryCalls.Add(1) + if request.Header.Get("Authorization") != "Bearer synthetic-inventory-reader" { + t.Error("inventory request missing reader authentication") + writer.WriteHeader(http.StatusUnauthorized) + return + } + if denied.Load() { + http.Error(writer, "private-inventory-error-sentinel", http.StatusForbidden) + return + } + fixture.ServeHTTP(writer, request) + })) + defer inventoryServer.Close() + stamp := time.Now().Add(-time.Second).Truncate(time.Millisecond) + var sourceFailed atomic.Bool + var sourceCalls atomic.Int64 + sourceServer := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + sourceCalls.Add(1) + if request.Header.Get("Authorization") != "" { + t.Error("inventory credential leaked to source") + } + if request.Method != http.MethodGet || request.URL.Path != "/api/v1/query" || len(request.URL.Query()) != 3 || strings.Contains(request.URL.RawQuery, "attacker") { + t.Error("incoming parameters changed source request") + } + if sourceFailed.Load() { + http.Error(writer, "private-source-error-sentinel", http.StatusBadGateway) + return + } + writer.Write(sourceFixture(config, stamp, nil)) + })) + defer sourceServer.Close() + config.PrometheusURL = sourceServer.URL + config.ProjectAuthority = strings.TrimPrefix(inventoryServer.URL, "https://") + config.MiloKubeconfig = filepath.Join(t.TempDir(), "kubeconfig") + certificate := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: inventoryServer.Certificate().Raw}) + kubeconfig := fmt.Sprintf("apiVersion: v1\nkind: Config\nclusters:\n- name: root\n cluster:\n server: %s\n certificate-authority-data: %s\ncontexts:\n- name: root\n context:\n cluster: root\n user: reader\ncurrent-context: root\nusers:\n- name: reader\n user:\n token: synthetic-inventory-reader\n", inventoryServer.URL, base64.StdEncoding.EncodeToString(certificate)) + if err := os.WriteFile(config.MiloKubeconfig, []byte(kubeconfig), 0600); err != nil { + t.Fatal(err) + } + configPath := filepath.Join(t.TempDir(), "config.json") + contents, err := json.Marshal(config) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(configPath, contents, 0600); err != nil { + t.Fatal(err) + } + publisher, err := New(configPath) + if err != nil { + t.Fatal(err) + } + prime(t, publisher) + if sourceCalls.Load() != 0 || inventoryCalls.Load() != 2 { + t.Fatal("priming did not exclusively read Project and Device") + } + response := httptest.NewRecorder() + publisher.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics?query=attacker&target=http://attacker.invalid", nil)) + want := fmt.Sprintf("datum_fleet_device_hardware_fan_speed_rpm{component=\"0\",device=\"server-1\",device_uid=\"device-1\",project_authority=%q,project_uid=\"project-1\",resourcemanager_datumapis_com_project_name=\"owner\",visibility=\"inventory_owner\"} 0 %d\n", config.ProjectAuthority, stamp.UnixMilli()) + want += fmt.Sprintf("datum_fleet_device_hardware_temperature_celsius{component=\"1\",device=\"server-1\",device_uid=\"device-1\",project_authority=%q,project_uid=\"project-1\",resourcemanager_datumapis_com_project_name=\"owner\",visibility=\"inventory_owner\"} -4 %d\n", config.ProjectAuthority, stamp.UnixMilli()) + if response.Code != http.StatusOK || response.Body.String() != want || response.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("unexpected authenticated output: %d %s", response.Code, response.Body.String()) + } + for _, failure := range []struct { + name string + flag *atomic.Bool + }{{name: "inventory forbidden", flag: &denied}, {name: "source unavailable", flag: &sourceFailed}} { + t.Run(failure.name, func(t *testing.T) { + failure.flag.Store(true) + response := scrape(publisher) + if response.Code != http.StatusServiceUnavailable || response.Body.String() != "hardware evidence unavailable\n" || publisher.session != "" { + t.Fatalf("failure leaked data or retained session: %d %s", response.Code, response.Body.String()) + } + failure.flag.Store(false) + if response := scrape(publisher); response.Code != http.StatusOK || response.Body.Len() != 0 { + t.Fatal("recovery reused old publication") + } + if response := scrape(publisher); response.Code != http.StatusServiceUnavailable { + t.Fatal("recovery backfilled the previous session sample") + } + prime(t, publisher) + if response := scrape(publisher); response.Code != http.StatusOK || response.Body.String() != want { + t.Fatal("fresh observation session did not recover") + } + }) + } + before := inventoryCalls.Load() + for _, request := range []*http.Request{ + httptest.NewRequest(http.MethodPost, "/metrics", nil), + httptest.NewRequest(http.MethodGet, "/other", nil), + } { + response := httptest.NewRecorder() + publisher.ServeHTTP(response, request) + if response.Code != http.StatusMethodNotAllowed && response.Code != http.StatusNotFound { + t.Fatal("unexpected endpoint accepted") + } + } + if inventoryCalls.Load() != before { + t.Fatal("invalid endpoint triggered authority reads") + } +} diff --git a/internal/devicehardwarepublisher/authority.go b/internal/devicehardwarepublisher/authority.go new file mode 100644 index 00000000..25c8a666 --- /dev/null +++ b/internal/devicehardwarepublisher/authority.go @@ -0,0 +1,98 @@ +package devicehardwarepublisher + +import ( + "context" + "errors" + "net/http" + "net/url" + "strings" + "time" + + inventory "go.datum.net/fleet/internal/api/inventory/v1alpha1" + projection "go.datum.net/fleet/internal/devicehardwaremetrics" + milo "go.miloapis.com/milo/pkg/apis/resourcemanager/v1alpha1" + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/rest" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +type authority struct{ projects, devices client.Reader } + +func newAuthority(c Config) (authority, error) { + cfg, e := clientcmd.BuildConfigFromFlags("", c.MiloKubeconfig) + if e != nil { + return authority{}, e + } + u, e := url.Parse(cfg.Host) + if e != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || strings.Trim(u.Path, "/") != "" || cfg.Insecure || c.ProjectAuthority != strings.ToLower(u.Host) || u.Host != strings.ToLower(u.Host) || (cfg.ServerName != "" && cfg.ServerName != u.Hostname()) { + return authority{}, errors.New("Milo kubeconfig must use a verified HTTPS root endpoint whose host equals projectAuthority") + } + hasCertificate := (len(cfg.CertData) > 0 || cfg.CertFile != "") && (len(cfg.KeyData) > 0 || cfg.KeyFile != "") + if !hasCertificate && cfg.BearerToken == "" && cfg.BearerTokenFile == "" { + return authority{}, errors.New("Milo reader requires a client certificate or bearer token") + } + if cfg.ExecProvider != nil || cfg.AuthProvider != nil || cfg.Username != "" || cfg.Password != "" || cfg.Impersonate.UserName != "" || cfg.Impersonate.UID != "" || len(cfg.Impersonate.Groups) != 0 || len(cfg.Impersonate.Extra) != 0 { + return authority{}, errors.New("Milo reader does not support executable authentication, basic auth, or impersonation") + } + cfg.Timeout = time.Duration(c.TimeoutSeconds) * time.Second + return authorityFromConfig(c, cfg) +} + +// Both clients are uncached and use static mappings: no discovery/list rights. +func authorityFromConfig(c Config, cfg *rest.Config) (authority, error) { + scheme := runtime.NewScheme() + if e := milo.AddToScheme(scheme); e != nil { + return authority{}, e + } + if e := inventory.AddToScheme(scheme); e != nil { + return authority{}, e + } + pg := schema.GroupVersion{Group: "resourcemanager.miloapis.com", Version: "v1alpha1"} + mapper := meta.NewDefaultRESTMapper([]schema.GroupVersion{pg, inventory.GroupVersion}) + mapper.Add(pg.WithKind("Project"), meta.RESTScopeRoot) + mapper.Add(inventory.GroupVersion.WithKind("Device"), meta.RESTScopeNamespace) + httpClient, e := rest.HTTPClientFor(cfg) + if e != nil { + return authority{}, e + } + boundedClient := *httpClient + boundedClient.CheckRedirect = func(*http.Request, []*http.Request) error { return errors.New("inventory redirects are forbidden") } + root, e := client.New(cfg, client.Options{Scheme: scheme, Mapper: mapper, HTTPClient: &boundedClient}) + if e != nil { + return authority{}, e + } + scoped := rest.CopyConfig(cfg) + scoped.Host = strings.TrimRight(cfg.Host, "/") + "/apis/resourcemanager.miloapis.com/v1alpha1/projects/" + c.Project + "/control-plane" + devices, e := client.New(scoped, client.Options{Scheme: scheme, Mapper: mapper, HTTPClient: &boundedClient}) + return authority{root, devices}, e +} +func (a authority) read(ctx context.Context, c Config) ([]projection.Binding, error) { + p := &milo.Project{} + if e := a.projects.Get(ctx, client.ObjectKey{Name: c.Project}, p); e != nil { + return nil, e + } + observed := time.Now() + if p.Name != c.Project || string(p.UID) != c.ProjectUID || p.ResourceVersion == "" || !p.DeletionTimestamp.IsZero() { + return nil, ErrInvalid + } + project := projection.Project{AuthorityID: c.ProjectAuthority, Name: p.Name, UID: string(p.UID), Evidence: projection.Evidence{Revision: p.ResourceVersion, ObservedAt: observed}} + bindings := make([]projection.Binding, 0, len(c.Devices)) + for _, m := range c.Devices { + d := &inventory.Device{} + if e := a.devices.Get(ctx, client.ObjectKey{Namespace: c.Namespace, Name: m.Name}, d); e != nil { + return nil, e + } + if d.Name != m.Name || d.Namespace != c.Namespace || string(d.UID) != m.UID || d.ResourceVersion == "" || !d.DeletionTimestamp.IsZero() { + return nil, ErrInvalid + } + b := projection.Binding{Project: project, Device: projection.Device{Name: d.Name, UID: string(d.UID), Evidence: projection.Evidence{Revision: d.ResourceVersion, ObservedAt: time.Now()}}, Mapping: projection.Mapping{DeviceUID: m.UID, PhysicalID: m.PhysicalID, TargetID: m.TargetID, ValidSince: m.QualifiedAt, Evidence: projection.Evidence{Revision: m.Revision, ObservedAt: time.Now()}}} + for _, s := range m.Sensors { + b.Mapping.Sensors = append(b.Mapping.Sensors, projection.Sensor{Family: s.Family, Component: s.Component}) + } + bindings = append(bindings, b) + } + return bindings, nil +} diff --git a/internal/devicehardwarepublisher/config.go b/internal/devicehardwarepublisher/config.go new file mode 100644 index 00000000..49e05f5f --- /dev/null +++ b/internal/devicehardwarepublisher/config.go @@ -0,0 +1,145 @@ +// Package devicehardwarepublisher adapts authenticated inventory and an +// operator-qualified collector mapping to the inventory-owner projection. +package devicehardwarepublisher + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/url" + "os" + "regexp" + "strings" + "time" + + projection "go.datum.net/fleet/internal/devicehardwaremetrics" +) + +const MaxConfigBytes = 1 << 20 + +var token = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,252}$`) +var name = regexp.MustCompile(`^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$`) +var ErrInvalid = errors.New("invalid publisher configuration or evidence") + +// Config is trusted operator configuration, not tenant input. EvidenceRef is +// an audit reference, not a signature: protection and qualification are external. +type Config struct { + MiloKubeconfig string `json:"miloKubeconfig"` + Project string `json:"project"` + ProjectUID string `json:"projectUID"` + ProjectAuthority string `json:"projectAuthority"` + Namespace string `json:"namespace"` + PrometheusURL string `json:"prometheusURL"` + Job string `json:"job"` + Cluster string `json:"cluster"` + TimeoutSeconds int `json:"timeoutSeconds"` + MaxSampleAgeSeconds int `json:"maxSampleAgeSeconds"` + MaxResponseBytes int64 `json:"maxResponseBytes"` + Devices []DeviceMapping `json:"devices"` +} +type DeviceMapping struct { + Name string `json:"name"` + UID string `json:"uid"` + PhysicalID string `json:"physicalID"` + TargetID string `json:"targetID"` + Instance string `json:"instance"` + Revision string `json:"revision"` + EvidenceRef string `json:"evidenceRef"` + QualifiedAt time.Time `json:"qualifiedAt"` + Sensors []SensorMapping `json:"sensors"` +} +type SensorMapping struct { + Family string `json:"family"` + Component uint32 `json:"component"` + ID string `json:"id"` + Name string `json:"name"` + Units string `json:"units"` + Context string `json:"context"` +} + +func ReadConfig(path string) (Config, []byte, error) { + f, err := os.Open(path) + if err != nil { + return Config{}, nil, err + } + defer f.Close() + b, err := io.ReadAll(io.LimitReader(f, MaxConfigBytes+1)) + if err != nil || len(b) > MaxConfigBytes { + return Config{}, nil, ErrInvalid + } + c, err := ParseConfig(b) + return c, b, err +} +func ParseConfig(b []byte) (Config, error) { + var c Config + d := json.NewDecoder(bytes.NewReader(b)) + d.DisallowUnknownFields() + if d.Decode(&c) != nil || d.Decode(new(any)) != io.EOF { + return c, ErrInvalid + } + // Component zero is valid, but it must be an explicit stable assignment. + var presence struct { + Devices []struct { + Sensors []struct { + Component *uint32 `json:"component"` + } `json:"sensors"` + } `json:"devices"` + } + if json.Unmarshal(b, &presence) != nil { + return c, ErrInvalid + } + for _, device := range presence.Devices { + for _, sensor := range device.Sensors { + if sensor.Component == nil { + return c, ErrInvalid + } + } + } + return c, c.Validate() +} +func (c Config) Validate() error { + if c.MiloKubeconfig == "" || !name.MatchString(c.Project) || !name.MatchString(c.Namespace) || !token.MatchString(c.ProjectUID) || !token.MatchString(c.ProjectAuthority) || !bounded(c.Job) || !bounded(c.Cluster) || c.TimeoutSeconds < 1 || c.TimeoutSeconds > 30 || c.MaxSampleAgeSeconds < 1 || c.MaxSampleAgeSeconds > 600 || c.MaxResponseBytes < 1024 || c.MaxResponseBytes > 8<<20 || len(c.Devices) == 0 || len(c.Devices) > 32 { + return ErrInvalid + } + u, e := url.Parse(c.PrometheusURL) + if e != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Opaque != "" { + return ErrInvalid + } + // Require a service base URL, never a complete Prometheus API endpoint. + // Reject rather than guessing which path segments the operator intended. + if strings.Contains(strings.TrimRight(u.Path, "/")+"/", "/api/v1/") { + return errors.New("prometheusURL must be a base URL without /api/v1") + } + seen := map[string]bool{} + for _, v := range c.Devices { + if !name.MatchString(v.Name) || !token.MatchString(v.UID) || !token.MatchString(v.PhysicalID) || !token.MatchString(v.TargetID) || !token.MatchString(v.Revision) || !bounded(v.Instance) || !bounded(v.EvidenceRef) || v.QualifiedAt.IsZero() || v.QualifiedAt.After(time.Now()) || len(v.Sensors) == 0 || len(v.Sensors) > 8192 { + return ErrInvalid + } + for _, key := range []string{"name:" + v.Name, "uid:" + v.UID, "physical:" + v.PhysicalID, "target:" + v.TargetID} { + if seen[key] { + return ErrInvalid + } + seen[key] = true + } + raw := map[string]bool{} + components := map[projection.Sensor]bool{} + for _, s := range v.Sensors { + if !bounded(s.ID) || !bounded(s.Name) || len(s.Context) > 256 || s.Component > projection.MaxComponent { + return ErrInvalid + } + if !(s.Family == projection.FanFamily && s.Units == "rpm" && s.Context == "" || s.Family == projection.TemperatureFamily && s.Units == "celsius") { + return ErrInvalid + } + key := s.Family + "\x00" + s.ID + component := projection.Sensor{Family: s.Family, Component: s.Component} + if raw[key] || components[component] { + return ErrInvalid + } + raw[key] = true + components[component] = true + } + } + return nil +} +func bounded(s string) bool { return len(s) > 0 && len(s) <= 256 } diff --git a/internal/devicehardwarepublisher/publisher.go b/internal/devicehardwarepublisher/publisher.go new file mode 100644 index 00000000..ff01246b --- /dev/null +++ b/internal/devicehardwarepublisher/publisher.go @@ -0,0 +1,166 @@ +package devicehardwarepublisher + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "net/http" + "sort" + "strconv" + "sync" + "time" + + projection "go.datum.net/fleet/internal/devicehardwaremetrics" +) + +type Publisher struct { + config Config + configPath string + configBytes []byte + configInvalid bool + authority authority + http *http.Client + mu sync.Mutex + session string + since time.Time + previous []projection.Binding +} + +func New(path string) (*Publisher, error) { + c, b, e := ReadConfig(path) + if e != nil { + return nil, e + } + a, e := newAuthority(c) + if e != nil { + return nil, e + } + return &Publisher{config: c, configPath: path, configBytes: b, authority: a, http: &http.Client{Timeout: time.Duration(c.TimeoutSeconds) * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil +} +func (p *Publisher) reset() { p.session = ""; p.since = time.Time{}; p.previous = nil } +func same(a, b []projection.Binding) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i].Device.UID != b[i].Device.UID || a[i].Device.Evidence.Revision != b[i].Device.Evidence.Revision || a[i].Project.UID != b[i].Project.UID || a[i].Project.Evidence.Revision != b[i].Project.Evidence.Revision { + return false + } + } + return true +} + +// ServeHTTP performs no background collection, caching, retries, or writes. +// Overlapping scrapes fail closed instead of queueing authority observations. +func (p *Publisher) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/metrics" { + http.NotFound(w, r) + return + } + if r.Method != http.MethodGet { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + if !p.mu.TryLock() { + http.Error(w, "scrape in progress", http.StatusServiceUnavailable) + return + } + defer p.mu.Unlock() + ctx, cancel := context.WithTimeout(r.Context(), time.Duration(p.config.TimeoutSeconds)*time.Second) + defer cancel() + output, e := p.collect(ctx) + if e != nil { + p.reset() + message := "hardware evidence unavailable" + if errors.Is(e, ErrSourceTimestampMismatch) { + message = ErrSourceTimestampMismatch.Error() + } + if errors.Is(e, ErrSourceConflict) { + message = ErrSourceConflict.Error() + } + http.Error(w, message, http.StatusServiceUnavailable) + return + } + w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + _, _ = w.Write(output) +} +func (p *Publisher) collect(ctx context.Context) ([]byte, error) { + if p.configInvalid { + return nil, ErrInvalid + } + _, raw, e := ReadConfig(p.configPath) + if e != nil || !bytes.Equal(raw, p.configBytes) { + p.configInvalid = true + return nil, ErrInvalid + } + before, e := p.authority.read(ctx, p.config) + if e != nil { + return nil, e + } + if p.session == "" || !same(p.previous, before) { + p.reset() + var nonce [16]byte + if _, e := rand.Read(nonce[:]); e != nil { + return nil, e + } + p.session = hex.EncodeToString(nonce[:]) + p.since = time.Now() + p.previous = before + return nil, nil // never backfill observations preceding authenticated session + } + var readings []projection.Reading + for i := range before { + before[i].Device.OwnershipID = p.session + before[i].Device.OwnedSince = p.since + values, e := readSource(ctx, p.http, p.config, p.config.Devices[i], before[i], time.Now()) + if e != nil { + return nil, e + } + readings = append(readings, values...) + } + after, e := p.authority.read(ctx, p.config) + if e != nil || !same(before, after) { + return nil, ErrInvalid + } + _, raw, e = ReadConfig(p.configPath) + if e != nil || !bytes.Equal(raw, p.configBytes) { + p.configInvalid = true + return nil, ErrInvalid + } + now := time.Now() + for i := range after { + after[i].Device.OwnershipID = p.session + after[i].Device.OwnedSince = p.since + after[i].Mapping.Evidence.ObservedAt = now + } + snapshot := projection.Snapshot{Complete: true, Evidence: projection.Evidence{Revision: p.session, ObservedAt: now}, Bindings: after} + series, e := projection.ProjectReadings(now, projection.Policy{MaxAuthorityAge: time.Duration(p.config.TimeoutSeconds) * time.Second, MaxSampleAge: time.Duration(p.config.MaxSampleAgeSeconds) * time.Second}, snapshot, readings) + if e != nil { + return nil, e + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + var output bytes.Buffer + for _, s := range series { + fmt.Fprintf(&output, "%s{", s.Name) + keys := make([]string, 0, len(s.Labels)) + for k := range s.Labels { + keys = append(keys, k) + } + sort.Strings(keys) + for i, k := range keys { + if i > 0 { + output.WriteByte(',') + } + fmt.Fprintf(&output, "%s=%s", k, strconv.Quote(s.Labels[k])) + } + fmt.Fprintf(&output, "} %s %d\n", strconv.FormatFloat(s.Value, 'g', -1, 64), s.Timestamp.UnixMilli()) + } + p.previous = after + return output.Bytes(), nil +} diff --git a/internal/devicehardwarepublisher/publisher_test.go b/internal/devicehardwarepublisher/publisher_test.go new file mode 100644 index 00000000..fa410ed5 --- /dev/null +++ b/internal/devicehardwarepublisher/publisher_test.go @@ -0,0 +1,448 @@ +package devicehardwarepublisher + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + projection "go.datum.net/fleet/internal/devicehardwaremetrics" + "k8s.io/client-go/rest" +) + +func fixtureConfig() Config { + return Config{MiloKubeconfig: "/protected/kubeconfig", Project: "owner", ProjectUID: "project-1", ProjectAuthority: "milo-staging", Namespace: "inventory", PrometheusURL: "http://prometheus.invalid", Job: "qualified", Cluster: "central", TimeoutSeconds: 5, MaxSampleAgeSeconds: 120, MaxResponseBytes: 1 << 20, Devices: []DeviceMapping{{Name: "server-1", UID: "device-1", PhysicalID: "asset-1", TargetID: "collector-1", Instance: "internal-target", Revision: "mapping-1", EvidenceRef: "reviewed-evidence-1", QualifiedAt: time.Now().Add(-time.Hour), Sensors: []SensorMapping{{Family: projection.FanFamily, Component: 0, ID: "fan-1", Name: "Fan", Units: "rpm"}, {Family: projection.TemperatureFamily, Component: 1, ID: "temp-1", Name: "Inlet", Units: "celsius", Context: ""}}}}} +} +func sourceFixture(c Config, stamp time.Time, mutate func([]map[string]any)) []byte { + ts := float64(stamp.UnixMilli()) / 1000 + entries := []map[string]any{} + for _, v := range []struct{ family, value string }{{"up", "1"}, {successFamily, "1"}, {coverageFamily, "0"}, {startedFamily, fmt.Sprint(ts + 0.001)}, {projection.FanFamily, "0"}, {projection.TemperatureFamily, "-4"}} { + labels := map[string]string{"__name__": v.family, "job": c.Job, "cluster": c.Cluster, "device_uid": c.Devices[0].UID, "instance": c.Devices[0].Instance, "project_uid": "forged", "visibility": "forged"} + for _, sensor := range c.Devices[0].Sensors { + if sensor.Family == v.family { + labels["id"] = sensor.ID + labels["name"] = sensor.Name + labels["units"] = sensor.Units + if sensor.Family == projection.TemperatureFamily { + labels["context"] = sensor.Context + } + } + } + entries = append(entries, map[string]any{"metric": labels, "values": [][]any{{ts, v.value}}}) + } + if mutate != nil { + mutate(entries) + } + b, _ := json.Marshal(map[string]any{"status": "success", "data": map[string]any{"resultType": "matrix", "result": entries}}) + return b +} +func binding(c Config) projection.Binding { + return projection.Binding{Device: projection.Device{UID: "device-1", OwnershipID: "session-1", OwnedSince: time.Now().Add(-time.Minute)}, Project: projection.Project{UID: c.ProjectUID, AuthorityID: c.ProjectAuthority}, Mapping: projection.Mapping{ValidSince: c.Devices[0].QualifiedAt}} +} +func TestSourceTimestampsAndMissingness(t *testing.T) { + c := fixtureConfig() + stamp := time.Now().Add(-time.Second).Truncate(time.Millisecond) + tests := []struct { + name string + mutate func([]map[string]any) + want int + fail bool + }{ + {name: "partial coverage and real zero", want: 2}, + {name: "missing in latest scrape", want: 1, mutate: func(e []map[string]any) { + e[4]["values"] = [][]any{{float64(stamp.Add(-time.Second).UnixMilli()) / 1000, "100"}} + }}, + {name: "failed collection", fail: true, mutate: func(e []map[string]any) { e[1]["values"] = [][]any{{float64(stamp.UnixMilli()) / 1000, "0"}} }}, + {name: "failed exporter scrape", fail: true, mutate: func(e []map[string]any) { e[0]["values"] = [][]any{{float64(stamp.UnixMilli()) / 1000, "0"}} }}, + {name: "new up cannot reuse old success", fail: true, mutate: func(e []map[string]any) { + e[1]["values"] = [][]any{{float64(stamp.Add(-time.Second).UnixMilli()) / 1000, "1"}} + }}, + {name: "wrong target", fail: true, mutate: func(e []map[string]any) { e[4]["metric"].(map[string]string)["device_uid"] = "other" }}, + {name: "wrong sensor", fail: true, mutate: func(e []map[string]any) { e[4]["metric"].(map[string]string)["id"] = "other" }}, + {name: "future collection", fail: true, mutate: func(e []map[string]any) { + e[3]["values"] = [][]any{{float64(stamp.UnixMilli()) / 1000, fmt.Sprint(float64(time.Now().Add(time.Hour).Unix()))}} + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query().Get("query") + if r.URL.Path != "/api/v1/query" || !strings.HasSuffix(query, "[120s]") || !strings.Contains(query, `device_uid="device-1"`) { + t.Errorf("unsafe query %s", r.URL) + } + w.Write(sourceFixture(c, stamp, tt.mutate)) + })) + defer server.Close() + c.PrometheusURL = server.URL + readings, err := readSource(context.Background(), server.Client(), c, c.Devices[0], binding(c), time.Now()) + if (err != nil) != tt.fail { + t.Fatalf("error=%v", err) + } + if tt.fail { + return + } + if len(readings) != tt.want { + t.Fatalf("got %d readings", len(readings)) + } + for _, r := range readings { + if r.ObservedAt.UnixMilli() != stamp.UnixMilli() { + t.Fatalf("lost stored timestamp %v != %v", r.ObservedAt, stamp) + } + if r.ProjectUID != "project-1" { + t.Fatal("trusted raw project") + } + } + }) + } +} + +type apiFixture struct { + mu sync.Mutex + projectUID, deviceUID, revision string + deleted, fail, flip bool + gets []string +} + +func (a *apiFixture) ServeHTTP(w http.ResponseWriter, r *http.Request) { + a.mu.Lock() + defer a.mu.Unlock() + a.gets = append(a.gets, r.Method+" "+r.URL.Path) + if a.fail { + http.Error(w, "unavailable", 500) + return + } + if r.Method != "GET" { + http.Error(w, "read only", 403) + return + } + meta := map[string]any{"name": "owner", "uid": a.projectUID, "resourceVersion": "1"} + kind, version := "Project", "resourcemanager.miloapis.com/v1alpha1" + switch r.URL.Path { + case "/apis/resourcemanager.miloapis.com/v1alpha1/projects/owner": + case "/apis/resourcemanager.miloapis.com/v1alpha1/projects/owner/control-plane/apis/fleet.datumapis.com/v1alpha1/namespaces/inventory/devices/server-1": + meta = map[string]any{"name": "server-1", "namespace": "inventory", "uid": a.deviceUID, "resourceVersion": a.revision} + kind, version = "Device", "fleet.datumapis.com/v1alpha1" + if a.flip { + a.revision = "2" + } + default: + http.NotFound(w, r) + return + } + if a.deleted { + meta["deletionTimestamp"] = time.Now().UTC().Format(time.RFC3339) + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(map[string]any{"apiVersion": version, "kind": kind, "metadata": meta}) +} +func newTestPublisher(t *testing.T) (*Publisher, *apiFixture, *time.Time) { + t.Helper() + c := fixtureConfig() + api := &apiFixture{projectUID: c.ProjectUID, deviceUID: c.Devices[0].UID, revision: "1"} + server := httptest.NewServer(api) + t.Cleanup(server.Close) + a, err := authorityFromConfig(c, &rest.Config{Host: server.URL}) + if err != nil { + t.Fatal(err) + } + stamp := time.Now().Add(-time.Second).Truncate(time.Millisecond) + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(sourceFixture(c, stamp, nil)) })) + t.Cleanup(source.Close) + c.PrometheusURL = source.URL + b, _ := json.Marshal(c) + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, b, 0600); err != nil { + t.Fatal(err) + } + return &Publisher{config: c, configPath: path, configBytes: b, authority: a, http: source.Client()}, api, &stamp +} +func scrape(p *Publisher) *httptest.ResponseRecorder { + r := httptest.NewRecorder() + p.ServeHTTP(r, httptest.NewRequest("GET", "/metrics", nil)) + return r +} +func prime(t *testing.T, p *Publisher) { + t.Helper() + if r := scrape(p); r.Code != 200 || r.Body.Len() != 0 { + t.Fatalf("session backfill: %d %s", r.Code, r.Body.String()) + } + p.since = time.Now().Add(-time.Minute) +} +func TestPublisherAuthenticatedOutputAndLifetime(t *testing.T) { + for _, change := range []string{"none", "project recreation", "device replacement", "deletion", "api failure", "mid-read revision", "config change"} { + t.Run(change, func(t *testing.T) { + p, a, stamp := newTestPublisher(t) + prime(t, p) + a.mu.Lock() + switch change { + case "project recreation": + a.projectUID = "project-2" + case "device replacement": + a.deviceUID = "device-2" + case "deletion": + a.deleted = true + case "api failure": + a.fail = true + case "mid-read revision": + a.flip = true + case "config change": + os.WriteFile(p.configPath, append(p.configBytes, ' '), 0600) + } + a.mu.Unlock() + r := scrape(p) + if change != "none" { + if r.Code != 503 || strings.Contains(r.Body.String(), "datum_fleet") { + t.Fatalf("did not fail closed: %d %s", r.Code, r.Body.String()) + } + if p.session != "" { + t.Fatal("failed session retained") + } + return + } + if r.Code != 200 { + t.Fatalf("%d %s", r.Code, r.Body.String()) + } + lines := strings.Split(strings.TrimSpace(r.Body.String()), "\n") + if len(lines) != 2 { + t.Fatalf("%s", r.Body.String()) + } + for _, line := range lines { + if !strings.HasSuffix(line, fmt.Sprint(stamp.UnixMilli())) || strings.Count(line, "=") != 7 || strings.Contains(line, "forged") || !strings.Contains(line, `visibility="inventory_owner"`) { + t.Fatalf("bad output %s", line) + } + } + if !strings.Contains(lines[0], "} 0 ") { + t.Fatal("valid zero lost") + } + a.mu.Lock() + defer a.mu.Unlock() + for _, path := range a.gets { + if strings.Contains(path, "allocation") || strings.Contains(path, "custody") || strings.Contains(path, "secrets") { + t.Fatal(path) + } + } + }) + } +} +func TestSessionDoesNotBackfill(t *testing.T) { + p, _, _ := newTestPublisher(t) + r := scrape(p) + if r.Code != 200 || r.Body.Len() != 0 { + t.Fatal(r) + } + r = scrape(p) + if r.Code != 503 || strings.Contains(r.Body.String(), "datum_fleet") { + t.Fatal("old sample accepted") + } +} +func TestConcurrentScrapes(t *testing.T) { + p, _, _ := newTestPublisher(t) + prime(t, p) + var wg sync.WaitGroup + for i := 0; i < 10; i++ { + wg.Add(1) + go func() { + defer wg.Done() + r := scrape(p) + if r.Code != 200 && r.Code != 503 { + t.Errorf("status %d", r.Code) + } + }() + } + wg.Wait() +} +func TestConfigValidation(t *testing.T) { + c := fixtureConfig() + b, _ := json.Marshal(c) + if _, err := ParseConfig(b); err != nil { + t.Fatal(err) + } + for _, modify := range []func(*Config){func(c *Config) { c.PrometheusURL = "http://user:password@host" }, func(c *Config) { c.Devices = append(c.Devices, c.Devices[0]) }, func(c *Config) { c.Devices[0].Sensors = append(c.Devices[0].Sensors, c.Devices[0].Sensors[0]) }, func(c *Config) { c.TimeoutSeconds = 0 }, func(c *Config) { c.MaxResponseBytes = 1 << 30 }, func(c *Config) { c.Devices[0].EvidenceRef = "" }} { + c := fixtureConfig() + modify(&c) + if c.Validate() == nil { + t.Fatal("invalid config accepted") + } + } + if _, err := ParseConfig(append(b, []byte(` {}`)...)); err == nil { + t.Fatal("trailing JSON accepted") + } + if _, err := ParseConfig([]byte(strings.Replace(string(b), `"project":`, `"unknown":`, 1))); err == nil { + t.Fatal("unknown field accepted") + } +} +func TestHTTPBoundsAndRedirect(t *testing.T) { + c := fixtureConfig() + targetCalls := 0 + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { targetCalls++ })) + defer target.Close() + for _, mode := range []string{"redirect", "oversize", "vector", "timeout"} { + t.Run(mode, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch mode { + case "redirect": + http.Redirect(w, r, target.URL, 302) + case "oversize": + fmt.Fprint(w, strings.Repeat("x", 2048)) + case "vector": + fmt.Fprint(w, `{"status":"success","data":{"resultType":"vector","result":[]}}`) + case "timeout": + <-r.Context().Done() + } + })) + defer server.Close() + c.PrometheusURL = server.URL + c.MaxResponseBytes = 1024 + h := &http.Client{Timeout: 50 * time.Millisecond, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + if _, err := readSource(context.Background(), h, c, c.Devices[0], binding(c), time.Now()); err == nil { + t.Fatal("invalid HTTP response accepted") + } + }) + } + if targetCalls != 0 { + t.Fatal("redirect followed") + } +} + +func TestMalformedAndConflictingSource(t *testing.T) { + c := fixtureConfig() + stamp := time.Now().Add(-time.Second).Truncate(time.Millisecond) + for _, mode := range []string{"duplicate up", "duplicate success", "unordered", "bad pair", "nonmatrix", "new failed after success"} { + t.Run(mode, func(t *testing.T) { + var data map[string]any + json.Unmarshal(sourceFixture(c, stamp, nil), &data) + body := data["data"].(map[string]any) + entries := body["result"].([]any) + switch mode { + case "duplicate up": + body["result"] = append(entries[:5], entries[0]) + case "duplicate success": + body["result"] = append(entries[:5], entries[1]) + case "unordered": + entries[4].(map[string]any)["values"] = [][]any{{float64(stamp.UnixMilli()) / 1000, "1"}, {float64(stamp.Add(-time.Second).UnixMilli()) / 1000, "1"}} + case "bad pair": + entries[4].(map[string]any)["values"] = [][]any{{"not-a-time", "1"}} + case "nonmatrix": + body["resultType"] = "vector" + case "new failed after success": + entries[1].(map[string]any)["values"] = [][]any{{float64(stamp.Add(-time.Second).UnixMilli()) / 1000, "1"}, {float64(stamp.UnixMilli()) / 1000, "0"}} + } + payload, _ := json.Marshal(data) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(payload) })) + defer server.Close() + c.PrometheusURL = server.URL + if _, err := readSource(context.Background(), server.Client(), c, c.Devices[0], binding(c), time.Now()); err == nil { + t.Fatal("accepted malformed/conflicting evidence") + } + }) + } +} +func TestSelectorEscaping(t *testing.T) { + c := fixtureConfig() + c.Job = "quoted\"job\\\n" + c.Cluster = "cluster\"}" + c.Devices[0].Instance = "target\"\\" + stamp := time.Now().Add(-time.Second) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query().Get("query") + if strings.Contains(query, "\n") || !strings.Contains(query, `job="quoted\"job\\\n"`) { + t.Errorf("unsafe selector %q", query) + } + w.Write(sourceFixture(c, stamp, nil)) + })) + defer server.Close() + c.PrometheusURL = server.URL + if _, err := readSource(context.Background(), server.Client(), c, c.Devices[0], binding(c), time.Now()); err != nil { + t.Fatal(err) + } +} +func TestAuthorityEndpointBinding(t *testing.T) { + c := fixtureConfig() + for _, entry := range []struct { + host, authority string + insecure bool + wantErr bool + }{ + {"https://api.example.invalid", "api.example.invalid", false, false}, + {"https://api.example.invalid", "arbitrary-alias", false, true}, + {"https://api.example.invalid", "api.example.invalid", true, true}, + {"http://api.example.invalid", "api.example.invalid", false, true}, + {"https://api.example.invalid/path", "api.example.invalid", false, true}, + } { + cfg := fmt.Sprintf("apiVersion: v1\nkind: Config\nclusters:\n- name: root\n cluster:\n server: %s\n insecure-skip-tls-verify: %t\ncontexts:\n- name: root\n context:\n cluster: root\n user: reader\ncurrent-context: root\nusers:\n- name: reader\n user:\n token: synthetic-test-token\n", entry.host, entry.insecure) + c.MiloKubeconfig = filepath.Join(t.TempDir(), "kubeconfig") + c.ProjectAuthority = entry.authority + os.WriteFile(c.MiloKubeconfig, []byte(cfg), 0600) + _, err := newAuthority(c) + if (err != nil) != entry.wantErr { + t.Fatalf("%s authority %s: %v", entry.host, entry.authority, err) + } + } +} + +func TestStaleSourceAndTimestampDiagnostics(t *testing.T) { + for _, mode := range []string{"stale", "mismatch"} { + t.Run(mode, func(t *testing.T) { + c := fixtureConfig() + stamp := time.Now().Add(-time.Second).Truncate(time.Millisecond) + if mode == "stale" { + stamp = stamp.Add(-time.Hour) + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + payload := sourceFixture(c, stamp, func(entries []map[string]any) { + if mode == "mismatch" { + entries[2]["values"] = [][]any{{float64(stamp.Add(-time.Second).UnixMilli()) / 1000, "0"}} + } + }) + w.Write(payload) + })) + defer server.Close() + c.PrometheusURL = server.URL + _, err := readSource(context.Background(), server.Client(), c, c.Devices[0], binding(c), time.Now()) + if err == nil { + t.Fatal("stale/incoherent source accepted") + } + if mode == "mismatch" && err != ErrSourceTimestampMismatch { + t.Fatalf("missing reason: %v", err) + } + }) + } +} + +func TestPrometheusBaseURL(t *testing.T) { + for _, suffix := range []string{"/api/v1", "/api/v1/query", "/api/v1/query/", "/select/0/prometheus/api/v1/query", "/select/0/prometheus/api/v1/query_range"} { + c := fixtureConfig() + c.PrometheusURL = "http://prometheus.invalid" + suffix + if err := c.Validate(); err == nil { + t.Fatalf("accepted API endpoint as base URL: %s", suffix) + } + } + for _, prefix := range []string{"", "/select/0/prometheus", "/select/0/prometheus/"} { + t.Run(prefix, func(t *testing.T) { + c := fixtureConfig() + stamp := time.Now().Add(-time.Second).Truncate(time.Millisecond) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != strings.TrimRight(prefix, "/")+"/api/v1/query" { + t.Errorf("unexpected query path: %s", r.URL.Path) + } + w.Write(sourceFixture(c, stamp, nil)) + })) + defer server.Close() + c.PrometheusURL = server.URL + prefix + if err := c.Validate(); err != nil { + t.Fatal(err) + } + readings, err := readSource(context.Background(), server.Client(), c, c.Devices[0], binding(c), time.Now()) + if err != nil || len(readings) != 2 { + t.Fatalf("base URL source read: readings=%d err=%v", len(readings), err) + } + }) + } +} diff --git a/internal/devicehardwarepublisher/security_test.go b/internal/devicehardwarepublisher/security_test.go new file mode 100644 index 00000000..dbe486fe --- /dev/null +++ b/internal/devicehardwarepublisher/security_test.go @@ -0,0 +1,101 @@ +package devicehardwarepublisher + +import ( + "context" + "encoding/pem" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "sync/atomic" + "testing" + + "k8s.io/client-go/rest" +) + +func TestInventoryRedirectsRejected(t *testing.T) { + for _, destinationTLS := range []bool{false, true} { + for _, redirectDevice := range []bool{false, true} { + config := fixtureConfig() + var reached atomic.Bool + destination := httptest.NewUnstartedServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + reached.Store(true) + })) + if destinationTLS { + destination.StartTLS() + } else { + destination.Start() + } + api := &apiFixture{projectUID: config.ProjectUID, deviceUID: config.Devices[0].UID, revision: "1"} + origin := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if redirectDevice && request.URL.Path == "/apis/resourcemanager.miloapis.com/v1alpha1/projects/owner" { + api.ServeHTTP(writer, request) + return + } + http.Redirect(writer, request, destination.URL, http.StatusFound) + })) + ca := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: origin.Certificate().Raw}) + reader, err := authorityFromConfig(config, &rest.Config{Host: origin.URL, BearerToken: "synthetic-reader", TLSClientConfig: rest.TLSClientConfig{CAData: ca}}) + if err != nil { + t.Fatal(err) + } + _, err = reader.read(context.Background(), config) + origin.Close() + destination.Close() + if err == nil || reached.Load() { + t.Fatalf("redirect followed: device=%t tls=%t err=%v", redirectDevice, destinationTLS, err) + } + } + } +} + +func TestAllImpersonationFieldsRejected(t *testing.T) { + for _, field := range []string{"as: user", "as-uid: uid", "as-groups: [group]", "as-user-extra: {key: [value]}"} { + config := fixtureConfig() + config.ProjectAuthority = "api.example.invalid" + config.MiloKubeconfig = filepath.Join(t.TempDir(), "kubeconfig") + contents := "apiVersion: v1\nkind: Config\nclusters:\n- name: root\n cluster:\n server: https://api.example.invalid\ncontexts:\n- name: root\n context:\n cluster: root\n user: reader\ncurrent-context: root\nusers:\n- name: reader\n user:\n token: synthetic-reader\n " + field + "\n" + if err := os.WriteFile(config.MiloKubeconfig, []byte(contents), 0600); err != nil { + t.Fatal(err) + } + if _, err := newAuthority(config); err == nil { + t.Fatalf("accepted impersonation %s", field) + } + } +} + +func TestConfigChangeLatchesUntilRestart(t *testing.T) { + publisher, _, _ := newTestPublisher(t) + prime(t, publisher) + if err := os.WriteFile(publisher.configPath, append(append([]byte(nil), publisher.configBytes...), ' '), 0600); err != nil { + t.Fatal(err) + } + if response := scrape(publisher); response.Code != http.StatusServiceUnavailable { + t.Fatal("changed configuration accepted") + } + if err := os.WriteFile(publisher.configPath, publisher.configBytes, 0600); err != nil { + t.Fatal(err) + } + for attempt := 0; attempt < 3; attempt++ { + if response := scrape(publisher); response.Code != http.StatusServiceUnavailable { + t.Fatal("restored configuration cleared restart latch") + } + } +} + +func TestSharedCollectorInstanceWithDistinctDevices(t *testing.T) { + config := fixtureConfig() + second := config.Devices[0] + second.Name = "server-2" + second.UID = "device-2" + second.PhysicalID = "asset-2" + second.TargetID = "collector-2" + config.Devices = append(config.Devices, second) + if err := config.Validate(); err != nil { + t.Fatalf("distinct devices sharing a collector endpoint rejected: %v", err) + } + config.Devices[1].UID = config.Devices[0].UID + if err := config.Validate(); err == nil { + t.Fatal("duplicate Device UID accepted") + } +} diff --git a/internal/devicehardwarepublisher/source.go b/internal/devicehardwarepublisher/source.go new file mode 100644 index 00000000..4256afca --- /dev/null +++ b/internal/devicehardwarepublisher/source.go @@ -0,0 +1,188 @@ +package devicehardwarepublisher + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + projection "go.datum.net/fleet/internal/devicehardwaremetrics" +) + +const successFamily = "fleet_hardware_collection_success" +const coverageFamily = "fleet_hardware_coverage_complete" +const startedFamily = "fleet_hardware_collection_started_timestamp_seconds" + +var ErrSourceTimestampMismatch = errors.New("source_timestamp_mismatch: latest source diagnostics must retain one original scrape timestamp") +var ErrSourceConflict = errors.New("source_identity_conflict: duplicate diagnostic identity") + +type matrixSeries struct { + Metric map[string]string `json:"metric"` + Values [][]json.RawMessage `json:"values"` +} +type queryResponse struct { + Status string `json:"status"` + Data struct { + ResultType string `json:"resultType"` + Result []matrixSeries `json:"result"` + } `json:"data"` + Warnings []string `json:"warnings"` +} +type sample struct { + labels map[string]string + timestamp time.Time + value float64 +} + +// A range selector in an instant query returns original stored sample times. +// query_range and an instant vector would return evaluation times instead. +func readSource(ctx context.Context, h *http.Client, c Config, m DeviceMapping, b projection.Binding, now time.Time) ([]projection.Reading, error) { + u, _ := url.Parse(c.PrometheusURL) + u.Path = strings.TrimRight(u.Path, "/") + "/api/v1/query" + families := []string{"up", successFamily, coverageFamily, startedFamily, projection.FanFamily, projection.TemperatureFamily} + selector := fmt.Sprintf(`{__name__=~%s,job=%s,cluster=%s,device_uid=%s,instance=%s}[%ds]`, strconv.Quote(strings.Join(families, "|")), strconv.Quote(c.Job), strconv.Quote(c.Cluster), strconv.Quote(m.UID), strconv.Quote(m.Instance), c.MaxSampleAgeSeconds) + q := u.Query() + q.Set("query", selector) + q.Set("time", strconv.FormatFloat(float64(now.UnixNano())/1e9, 'f', 9, 64)) + q.Set("timeout", strconv.Itoa(c.TimeoutSeconds)+"s") + u.RawQuery = q.Encode() + req, e := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if e != nil { + return nil, e + } + response, e := h.Do(req) + if e != nil { + return nil, e + } + defer response.Body.Close() + if response.StatusCode != http.StatusOK { + return nil, ErrInvalid + } + data, e := io.ReadAll(io.LimitReader(response.Body, c.MaxResponseBytes+1)) + if e != nil || int64(len(data)) > c.MaxResponseBytes { + return nil, ErrInvalid + } + var result queryResponse + if json.Unmarshal(data, &result) != nil || result.Status != "success" || result.Data.ResultType != "matrix" || len(result.Warnings) != 0 || len(result.Data.Result) > len(m.Sensors)+4 { + return nil, ErrInvalid + } + latest := make([]sample, 0, len(result.Data.Result)) + diagnostics := map[string]sample{} + for _, series := range result.Data.Result { + labels := series.Metric + family := labels["__name__"] + if labels["job"] != c.Job || labels["cluster"] != c.Cluster || labels["device_uid"] != m.UID || labels["instance"] != m.Instance { + return nil, ErrInvalid + } + allowed := false + for _, f := range families { + if family == f { + allowed = true + } + } + if !allowed || len(series.Values) == 0 || len(series.Values) > 10000 { + return nil, ErrInvalid + } + var last sample + for _, pair := range series.Values { + if len(pair) != 2 { + return nil, ErrInvalid + } + var ts float64 + var value string + if json.Unmarshal(pair[0], &ts) != nil || json.Unmarshal(pair[1], &value) != nil || math.IsNaN(ts) || math.IsInf(ts, 0) || ts <= 0 || ts > float64(now.UnixNano())/1e9 { + return nil, ErrInvalid + } + parsed, e := strconv.ParseFloat(value, 64) + if e != nil { + return nil, ErrInvalid + } + // Prometheus storage timestamps have millisecond precision. Round the + // floating JSON seconds before conversion to avoid losing one millisecond. + t := time.UnixMilli(int64(math.Round(ts * 1000))) + if !last.timestamp.IsZero() && !t.After(last.timestamp) { + return nil, ErrInvalid + } + last = sample{labels: labels, timestamp: t, value: parsed} + } + latest = append(latest, last) + if family != projection.FanFamily && family != projection.TemperatureFamily { + if _, exists := diagnostics[family]; exists { + return nil, ErrSourceConflict + } + diagnostics[family] = last + } + } + up, ok := diagnostics["up"] + if !ok || up.value != 1 || !freshSource(now, up.timestamp, c) { + return nil, ErrInvalid + } + success, ok := diagnostics[successFamily] + if !ok || success.value != 1 { + return nil, ErrInvalid + } + coverage, ok := diagnostics[coverageFamily] + if !ok || (coverage.value != 0 && coverage.value != 1) { + return nil, ErrInvalid + } + started, ok := diagnostics[startedFamily] + if !ok || math.IsNaN(started.value) || math.IsInf(started.value, 0) || started.value <= 0 || started.value > float64(now.UnixNano())/1e9 { + return nil, ErrInvalid + } + if !success.timestamp.Equal(up.timestamp) || !coverage.timestamp.Equal(up.timestamp) || !started.timestamp.Equal(up.timestamp) { + return nil, ErrSourceTimestampMismatch + } + collectionStart := secondsTime(started.value) + // Prometheus stamps a scrape at request start, which can precede the + // collector's own start by milliseconds. Both clocks must be fresh and later + // than this observation session; neither proves BMC measurement freshness. + if !freshSource(now, collectionStart, c) || !collectionStart.After(b.Device.OwnedSince) || !collectionStart.After(b.Mapping.ValidSince) || math.Abs(collectionStart.Sub(up.timestamp).Seconds()) > float64(c.TimeoutSeconds) { + return nil, ErrInvalid + } + readings := []projection.Reading{} + seen := map[projection.Sensor]bool{} + for _, s := range latest { + f := s.labels["__name__"] + if f != projection.FanFamily && f != projection.TemperatureFamily { + continue + } + // Missing sensors remain in matrix lookback. Only this exact scrape's + // samples may be paired with its successful diagnostics. + if !s.timestamp.Equal(up.timestamp) { + continue + } + var match *SensorMapping + for i := range m.Sensors { + v := &m.Sensors[i] + if v.Family == f && v.ID == s.labels["id"] && v.Name == s.labels["name"] && v.Units == s.labels["units"] && v.Context == s.labels["context"] { + match = v + break + } + } + if match == nil { + return nil, ErrInvalid + } + sensor := projection.Sensor{Family: f, Component: match.Component} + if seen[sensor] { + return nil, ErrInvalid + } + seen[sensor] = true + value := s.value + readings = append(readings, projection.Reading{DeviceUID: m.UID, OwnershipID: b.Device.OwnershipID, MappingRevision: m.Revision, ProjectUID: b.Project.UID, ProjectAuthority: b.Project.AuthorityID, Sensor: sensor, Value: &value, ObservedAt: s.timestamp}) + } + return readings, nil +} +func secondsTime(s float64) time.Time { + whole, frac := math.Modf(s) + return time.Unix(int64(whole), int64(frac*1e9)) +} +func freshSource(now, t time.Time, c Config) bool { + return !t.IsZero() && !t.After(now) && now.Sub(t) < time.Duration(c.MaxSampleAgeSeconds)*time.Second +}