diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3c2db02a..a269d940 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -140,6 +140,8 @@ jobs: run: sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ripgrep - run: ./hack/test-run-standalone-smoke.sh - run: ./hack/validate-site-dhcp-render.sh + - run: bash hack/dhcp/validate-producer.sh + - run: python3 hack/dhcp/staging-proof-test.py - run: ./hack/validate-network-boot-inactive.sh - run: ./hack/validate-doc-links.sh - run: ./hack/multiplane/test-harness.sh diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5e99dee5..cb33c355 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,6 +18,18 @@ jobs: platforms: linux/amd64,linux/arm64 secrets: inherit + publish-site-runtime-image: + permissions: + id-token: write + contents: read + packages: write + uses: datum-cloud/actions/.github/workflows/publish-docker.yaml@v1.21.0 + with: + image-name: fleet-site-runtime + dockerfile-path: build/site-runtime.Dockerfile + platforms: linux/amd64,linux/arm64 + secrets: inherit + # The plugin images are deployed by config/components/{consumer,provider}-ui-plugin # in the same kustomize bundle. publish-consumer-ui-plugin-image: diff --git a/build/site-runtime.Dockerfile b/build/site-runtime.Dockerfile new file mode 100644 index 00000000..a2fcfd54 --- /dev/null +++ b/build/site-runtime.Dockerfile @@ -0,0 +1,13 @@ +FROM --platform=$BUILDPLATFORM golang:1.26.4-alpine@sha256:3ad57304ad93bbec8548a0437ad9e06a455660655d9af011d58b993f6f615648 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-multiplane ./cmd/fleet-multiplane + +FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab +COPY --from=build /out/fleet-multiplane /usr/local/bin/fleet-multiplane +ENV FLEET_SITE_PROVIDER=redfish +ENTRYPOINT ["/usr/local/bin/fleet-multiplane"] diff --git a/config/site/dhcp/producer/README.md b/config/site/dhcp/producer/README.md new file mode 100644 index 00000000..70992563 --- /dev/null +++ b/config/site/dhcp/producer/README.md @@ -0,0 +1,24 @@ +# Real site producer for an isolated DHCP proof + +This opt-in base runs the existing Redfish boot service and authenticated DHCP feed against the actual worker's shared journal and boot evidence. It does not create admissions, worker assignments, IPAM claims, or installer-success evidence. No default overlay includes it. + +Use the Go-only `fleet-site-runtime` image built by `build/site-runtime.Dockerfile`, pinned by digest through `FLEET_SITE_IMAGE`. It includes the existing `fleet-multiplane` executable, but no shell, QEMU, libvirt, host sockets, or installer artifacts. This image supports the Redfish Go roles; it is not the privileged local-VM runtime image. Packaging alone does not establish that a worker is enrolled or running. + +## Required environment inputs + +- An isolated namespace and a disposable emulator identity, never an existing physical server. +- `fleet-site-state`: the **same PVC used by the real worker**, with `journal`, `boot-evidence`, and `artifacts` subdirectories. Provision the test-owned directories for UID/GID 65532 and run the test worker with that identity. Do not change ownership of another site's retained state. The journal mounts read-only in the producer; only the real worker writes admissions. Boot evidence is shared writable state. +- Pinned, verified kernel/initrd/checksum artifacts in `artifacts`, matching the real operation image. The boot service verifies these; no dummy artifact or fabricated completion substitutes for them. +- `fleet-site-runtime` ConfigMap, key `boot-origin`: the approved reachable boot origin. Discover the isolated Service's allocated IP when preparing the runtime; do not choose a site address in this base. +- `fleet-site-redfish-enrollment` ConfigMap, key `enrollment`: the exact real worker enrollment, `dhcp: synced`, and `dhcpInstances: [fleet-dhcp-proof-0]` when using the isolated consumer. Targets must reference only the disposable emulator. A mismatched instance set is not accepted. +- `fleet-site-delivery` ConfigMap, key `methods`: the same real network-boot offer used by the worker. This base deliberately supplies no offer. +- `fleet-site-dhcp-sync` Secret, key `token`; `fleet-site-dhcp-feed-tls` Secret, keys `tls.crt`, `tls.key`, and `ca.crt`. The isolated consumer's Secret names differ: provision matching token and CA contents through environment-managed secret references, never Git. The server certificate must match the feed origin used by the consumer. +- NetworkPolicy admitting only the test consumer to TLS port 8081 and the test client/relay runtime to boot port 8080, with the necessary return paths. No public Service, host networking, or host ports are included. + +The source, producer, and consumer remain inactive until these inputs and real worker delivery are reviewed. A listening feed with an empty journal is not an integration proof. An actual worker may power off and reset its target before opening the test window, so accepting a real Device here is unsafe. + +## Outcome boundaries + +The proof must correlate a real operation with its bound IPAM claim, open worker admission, authenticated feed revision, Kea application, and DHCP packet exchange. Test unknown-client denial, acquisition, renewal, and a fresh attempt after withdrawal. Removing a reservation does not revoke an existing lease. Deadline-induced withdrawal does not establish completed installation, settled custody, or permission to delete the claim: uncertain worker effects retain custody and address ownership until recovery is resolved. + +An isolated cluster pass does not validate any real site's relay, WAN route, or physical client path. Nothing in this preparation changes those systems. diff --git a/config/site/dhcp/producer/boot.yaml b/config/site/dhcp/producer/boot.yaml new file mode 100644 index 00000000..93c93f1a --- /dev/null +++ b/config/site/dhcp/producer/boot.yaml @@ -0,0 +1,81 @@ +apiVersion: v1 +kind: Service +metadata: + name: fleet-site-boot +spec: + selector: + app.kubernetes.io/name: fleet-site-boot + ports: + - name: http + port: 8080 + targetPort: http +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-site-boot +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + app.kubernetes.io/name: fleet-site-boot + template: + metadata: + labels: + app.kubernetes.io/name: fleet-site-boot + spec: + automountServiceAccountToken: false + securityContext: + runAsNonRoot: true + runAsUser: 65532 + runAsGroup: 65532 + fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch + seccompProfile: + type: RuntimeDefault + containers: + - name: boot + image: "${FLEET_SITE_IMAGE}" + command: [fleet-multiplane, boot-service] + env: + - name: FLEET_SITE_PROVIDER + value: redfish + - name: FLEET_BOOT_EVIDENCE + value: /var/lib/fleet-boot + - name: FLEET_BOOT_ORIGIN + valueFrom: + configMapKeyRef: + name: fleet-site-runtime + key: boot-origin + ports: + - name: http + containerPort: 8080 + readinessProbe: + tcpSocket: + port: http + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + resources: + requests: {cpu: 20m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: + - name: state + mountPath: /var/lib/fleet-local + subPath: journal + readOnly: true + - name: state + mountPath: /var/lib/fleet-boot + subPath: boot-evidence + - name: state + mountPath: /opt/fleet-local/artifacts + subPath: artifacts + readOnly: true + volumes: + - name: state + persistentVolumeClaim: + claimName: fleet-site-state diff --git a/config/site/dhcp/producer/kustomization.yaml b/config/site/dhcp/producer/kustomization.yaml new file mode 100644 index 00000000..c63c3e5d --- /dev/null +++ b/config/site/dhcp/producer/kustomization.yaml @@ -0,0 +1,31 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: fleet-site +resources: + - boot.yaml +components: + - ../feed +patches: + - target: + kind: Deployment + name: fleet-site-boot + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: fleet-site-boot + spec: + template: + spec: + containers: + - name: dhcp-feed + securityContext: + runAsUser: 65532 + runAsNonRoot: true + volumes: + - name: dhcp-sync-token + secret: + defaultMode: 0440 + - name: dhcp-feed-tls + secret: + defaultMode: 0440 diff --git a/hack/dhcp/staging-proof-test.py b/hack/dhcp/staging-proof-test.py new file mode 100755 index 00000000..949078d5 --- /dev/null +++ b/hack/dhcp/staging-proof-test.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +"""Synthetic fixtures only; no API, DHCP or namespace calls.""" +import hashlib +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest +from unittest import mock + +spec = importlib.util.spec_from_file_location("proof", Path(__file__).with_name("staging-proof.py")) +proof = importlib.util.module_from_spec(spec) +spec.loader.exec_module(proof) + + +def feed(rows, issued): + return {"reservations": rows, "revision": hashlib.sha256(json.dumps(rows, separators=(",", ":")).encode()).hexdigest(), "issued": issued} + + +class ProofTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.c = dict(schema=1, context="isolated-example", namespace="proof", site="proof", emulator="synthetic", runtime="linux-netns-relay", netns="fleet-proof-one", interface="eth0", ipamClass="reviewed-class", ipamScope="reviewed-scope", isolated=True, syntheticEmulator=True, noPhysicalHosts=True, noPublicDHCP=True, relayReturnRouteReviewed=True, directRenewalRouteReviewed=True, reviewedCommit="a" * 40, seconds=10, mac="02:00:00:00:00:01", expectedInstances=["kea-0", "kea-1"]) + self.c["images"] = {k: k + "@sha256:" + "b" * 64 for k in ("worker", "emulator", "kea", "synchronizer", "client")} + (self.root / "reviewed").write_text("synthetic fixture") + self.c["artifacts"] = {k: {"path": "reviewed", "sha256": hashlib.sha256(b"synthetic fixture").hexdigest()} for k in ("topology", "emulatorConfig", "keaConfig", "enrollment")} + self.c["excludedSites"] = ["excluded-example"] + self.c["ipamScope"] = {"site": {"apiGroup": "fleet.datumapis.com", "kind": "Site", "name": "reviewed-scope"}} + self.write("manifest.json", self.c) + meta = {"name": "op", "namespace": "proof", "uid": "operation-uid", "creationTimestamp": "2026-11-30T00:00:01Z"} + self.op = {"metadata": meta, "spec": {"bootNetwork": {"address": "192.0.2.42", "addressClaim": {"apiGroup": "ipam.miloapis.com", "kind": "IPClaim", "name": "op-boot"}}}, "status": {"admission": {"fence": 7}}} + self.claim = {"metadata": dict(meta, name="op-boot", uid="claim-uid", labels={"fleet.datumapis.com/operation": "op"}, creationTimestamp="2026-11-30T00:00:00Z"), "status": {"phase": "Bound", "address": "192.0.2.42", "allocatedCIDR": "192.0.2.42/32", "boundAllocationRef": {"name": "allocation"}}} + self.allocation = {"metadata": dict(meta, name="allocation", uid="allocation-uid"), "spec": {"claimRef": {"name": "op-boot"}}, "status": {"address": "192.0.2.42", "allocatedCIDR": "192.0.2.42/32"}} + self.claim["spec"] = {"className": "reviewed-class", "scope": json.loads(json.dumps(self.c["ipamScope"])), "reclaimPolicy": "Delete"} + self.claim["status"]["poolRef"] = {"name": "fixture-pool"} + self.allocation["spec"].update(purpose="Claim", poolRef={"name": "fixture-pool"}) + self.allocation["status"]["phase"] = "Ready" + self.op["kind"] = "DeviceInstallation" + self.boot = {"operation": "deviceinstallation.op.7", "fence": 7, "mac": self.c["mac"], "address": "192.0.2.42", "created": "2026-11-30T00:00:02Z", "published": "2026-11-30T00:00:03Z", "expires": "2026-11-30T00:01:00Z"} + self.rows = [{"mac": self.c["mac"], "address": self.boot["address"], "expires": self.boot["expires"]}] + self.reports = [{"at": "2026-11-30T00:00:05Z", "instance": "kea-0", "feed": feed(self.rows, "2026-11-30T00:00:04Z")}] + self.reports += [{"at": "2026-11-30T00:01:02Z", "instance": k, "feed": feed([], "2026-11-30T00:01:01Z")} for k in self.c["expectedInstances"]] + + def write(self, name, value): + (self.root / name).write_text(json.dumps(value)) + + def verify(self): + for name, value in (("operation.json", self.op), ("claim.json", self.claim), ("allocation.json", self.allocation), ("boot-summary.json", self.boot)): + self.write(name, value) + (self.root / "dhcp-applied.log").write_text("\n".join(json.dumps(r) for r in self.reports)) + return proof.verify(self.c, self.root) + + def test_positive_is_only_partial(self): + result = self.verify() + self.assertEqual(result["status"], "PARTIAL_EVIDENCE_ONLY") + self.assertFalse(result["existingLeaseRevoked"]) + self.assertIn("T1 direct renewal", result["notProven"]) + + def test_preflight_and_pinned_artifacts(self): + proof.preflight(self.root / "manifest.json") + (self.root / "reviewed").write_text("changed") + with self.assertRaisesRegex(proof.Refused, "digest"): + proof.preflight(self.root / "manifest.json") + + def test_preflight_refusals(self): + for field, value in (("site", "EXCLUDED-EXAMPLE"), ("excludedSites", []), ("excludedSites", [""]), ("excludedSites", "example"), ("netns", "host"), ("runtime", "ordinary-pod"), ("isolated", False), ("syntheticEmulator", False), ("seconds", 121), ("mac", "00:00:00:00:00:01"), ("reviewedCommit", "main"), ("directRenewalRouteReviewed", False)): + with self.subTest(field=field): + changed = dict(self.c, **{field: value}) + self.write("manifest.json", changed) + with self.assertRaises(proof.Refused): + proof.preflight(self.root / "manifest.json") + + def test_exact_binding_and_admission(self): + cases = [(self.claim["status"], "phase", "Pending"), (self.claim["status"], "allocatedCIDR", "192.0.2.0/24"), (self.claim["status"]["boundAllocationRef"], "name", "other"), (self.allocation["spec"]["claimRef"], "name", "other"), (self.allocation["status"], "address", "192.0.2.43"), (self.boot, "fence", 8), (self.boot, "operation", "other"), (self.op["spec"]["bootNetwork"], "address", "192.0.2.43")] + for obj, key, value in cases: + with self.subTest(key=key): + old = obj[key] + obj[key] = value + with self.assertRaises(proof.Refused): + self.verify() + obj[key] = old + + def test_missing_instance_blocks_withdrawal(self): + self.reports.pop() + with self.assertRaisesRegex(proof.Refused, "missing expected"): + self.verify() + + def test_latest_report_still_serves(self): + self.reports[-1]["feed"] = feed(self.rows, "2026-11-30T00:01:01Z") + with self.assertRaisesRegex(proof.Refused, "withdrawal"): + self.verify() + + def test_stale_empty_feed_does_not_prove_withdrawal(self): + self.reports[-1]["feed"] = feed([], "2026-11-30T00:00:02Z") + with self.assertRaisesRegex(proof.Refused, "withdrawal"): + self.verify() + + def test_rejected_or_retired_report_cannot_count(self): + for field in ("rejected", "retired"): + self.reports[-1][field] = True + with self.assertRaisesRegex(proof.Refused, "missing expected"): + self.verify() + del self.reports[-1][field] + + def test_feed_revision_is_verified(self): + self.reports[0]["feed"]["reservations"][0]["address"] = "192.0.2.43" + with self.assertRaisesRegex(proof.Refused, "revision"): + self.verify() + + def test_no_serving_report_cannot_pass(self): + self.reports.pop(0) + with self.assertRaisesRegex(proof.Refused, "no applied"): + self.verify() + + def test_hand_selected_claim_is_refused(self): + self.claim["spec"]["address"] = "192.0.2.42" + with self.assertRaisesRegex(proof.Refused, "allocator-selected"): + self.verify() + + def test_secrets_not_accepted_in_summary(self): + for field, value in (("token", "secret-fixture"), ("credentials", {"password": "secret-fixture"})): + with self.subTest(field=field): + self.boot[field] = value + with self.assertRaisesRegex(proof.Refused, "omit secrets"): + self.verify() + del self.boot[field] + + def test_complete_scope_reference_required(self): + for scope in ("reviewed-scope", {}, {"site": {"name": "reviewed-scope"}}): + self.write("manifest.json", dict(self.c, ipamScope=scope)) + with self.assertRaises(proof.Refused): + proof.preflight(self.root / "manifest.json") + + def test_scope_role_group_kind_and_name_must_match(self): + for field in ("apiGroup", "kind", "name"): + with self.subTest(field=field): + reference = self.claim["spec"]["scope"]["site"] + original = reference[field] + reference[field] = "unrelated" + with self.assertRaisesRegex(proof.Refused, "scope mismatch"): + self.verify() + reference[field] = original + self.claim["spec"]["scope"] = {"unrelated": self.claim["spec"]["scope"]["site"]} + with self.assertRaisesRegex(proof.Refused, "scope mismatch"): + self.verify() + + def test_probe_never_runs_on_non_linux(self): + with mock.patch.object(proof.sys, "platform", "darwin"), mock.patch.object(proof.subprocess, "run") as run: + with self.assertRaises(proof.Refused): + proof.probe(self.c, self.root / "capture") + run.assert_not_called() + + def test_probe_refuses_host_namespace_before_capture(self): + with mock.patch.object(proof.sys, "platform", "linux"), mock.patch.object(proof.Path, "exists", return_value=True), mock.patch.object(proof.os, "readlink", return_value="net:[123]"), mock.patch.object(proof.subprocess, "run", return_value=mock.Mock(stdout=b"net:[123]\n")), mock.patch.object(proof.subprocess, "Popen") as popen: + with self.assertRaisesRegex(proof.Refused, "host networking"): + proof.probe(self.c, self.root / "capture") + popen.assert_not_called() + + def test_probe_stops_owned_processes_on_timeout_and_preserves_files(self): + capture = mock.Mock(pid=100, poll=mock.Mock(return_value=None)) + client = mock.Mock(pid=101, poll=mock.Mock(return_value=None)) + client.wait.side_effect = [proof.subprocess.TimeoutExpired("fixture", 1), 0] + link = json.dumps([{"address": self.c["mac"], "flags": ["UP"]}]).encode() + destination = self.root / "capture" + real_readlink = proof.os.readlink + def popen(command, **kwargs): + if "tcpdump" in command: + self.assertEqual(command[command.index("-w") + 1], "-") + self.assertEqual(Path(kwargs["stdout"].name), destination.resolve() / "client.pcap") + self.assertEqual(Path(kwargs["stderr"].name), destination.resolve() / "capture.log") + kwargs["stdout"].write(b"pcap-fixture") + kwargs["stderr"].write(b"diagnostic-fixture") + return capture + return client + def readlink(path, *args, **kwargs): + return "net:[123]" if str(path) == "/proc/self/ns/net" else real_readlink(path, *args, **kwargs) + with mock.patch.object(proof.sys, "platform", "linux"), mock.patch.object(proof.Path, "exists", return_value=True), mock.patch.object(proof.os, "readlink", side_effect=readlink), mock.patch.object(proof.subprocess, "run", side_effect=[mock.Mock(stdout=b"net:[456]\n"), mock.Mock(stdout=link)]), mock.patch.object(proof.subprocess, "Popen", side_effect=popen), mock.patch.object(proof.time, "sleep"), mock.patch.object(proof.os, "killpg") as kill: + result = proof.probe(self.c, destination) + self.assertEqual(result["status"], "RAW_EVIDENCE_ONLY") + self.assertEqual({c.args[0] for c in kill.call_args_list}, {100, 101}) + self.assertIsNone(json.loads((destination / "probe.json").read_text())["clientExit"]) + self.assertTrue((destination / "client.log").is_file()) + self.assertEqual((destination / "client.pcap").read_bytes(), b"pcap-fixture") + self.assertEqual((destination / "capture.log").read_bytes(), b"diagnostic-fixture") + self.assertEqual(destination.stat().st_mode & 0o777, 0o700) + + +if __name__ == "__main__": + unittest.main() diff --git a/hack/dhcp/staging-proof.md b/hack/dhcp/staging-proof.md new file mode 100644 index 00000000..c0ef1495 --- /dev/null +++ b/hack/dhcp/staging-proof.md @@ -0,0 +1,132 @@ +# Isolated staging DHCP proof tools (partial) + +`staging-proof.py` is executable Python 3 with no third-party dependencies. It +provides offline input checks, captured IPAM/feed consistency checks and a bounded +fresh DHCP client capture. **It is not an end-to-end cluster proof runner.** No command +creates an operation, claims an address, writes a reservation, deploys a runtime, +or deletes a resource. Exit zero means only the explicitly reported partial check +or capture completed. It never reports installation success or lease revocation. + +```sh +python3 hack/dhcp/staging-proof-test.py +hack/dhcp/staging-proof.py preflight --manifest /private/path/reviewed.json +hack/dhcp/staging-proof.py verify --manifest /private/path/reviewed.json --evidence /private/path/export +# Linux only, inside the reviewed isolated client runtime: +hack/dhcp/staging-proof.py probe --manifest /private/path/reviewed.json --evidence /private/path/new-capture +``` + +## Reviewed inputs + +The manifest is a private JSON object with the following required fields. There +are intentionally no default cluster, site, pool, subnet, route, interface or +image values. Example addresses in tests are synthetic documentation addresses. + +| Fields | Required values | +| --- | --- | +| `schema` | `1` | +| `context`, `namespace`, `site`, `emulator` | Explicit isolated runtime identities; configured site exclusions are refused | +| `excludedSites` | Required nonempty array of real-site identifiers supplied privately by the operator; case-insensitive substring exclusions for runtime identities and scope reference values | +| `runtime` | `linux-netns-relay` | +| `netns`, `interface`, `mac` | Dedicated `fleet-proof-...` namespace, non-loopback interface, canonical locally administered unicast client MAC | +| `ipamClass` | Reviewed existing provisioning class; no pool is created | +| `ipamScope` | Complete nonempty scope map keyed by role, each reference containing exactly `apiGroup`, `kind`, and `name`; must match the claim scope exactly | +| `seconds` | Probe deadline, integer 1–120 | +| `reviewedCommit` | Reviewed 40-character lowercase commit SHA | +| `isolated`, `syntheticEmulator`, `noPhysicalHosts`, `noPublicDHCP` | Explicit `true` attestations | +| `relayReturnRouteReviewed`, `directRenewalRouteReviewed` | Explicit `true` attestations | +| `expectedInstances` | Nonempty exact enrollment instance-name array, no duplicates | +| `images` | Object with `worker`, `emulator`, `kea`, `synchronizer`, `client`, each a full image reference with `@sha256:` digest | +| `artifacts` | Object with `topology`, `emulatorConfig`, `keaConfig`, `enrollment`; each has `path` and lowercase `sha256` digest | + +Artifact paths resolve relative to the manifest. Do not commit private inputs. +Preflight checks artifact bytes and pin syntax, **not reviewer approval, deployed +image identity, API permissions, network isolation or route reachability**. Those +remain execution prerequisites for the responsible operator. The topology review +must exclude physical BMCs, real hosts, public DHCP, real-site routers and switch ports, +and prove both the relay return path and direct server-identifier route. Ordinary +Pod broadcast is not a valid path to the prepared Kea UDP listener. + +Run `probe` only within that reviewed Linux runtime with `ip`, `readlink`, +`tcpdump`, `udhcpc` and `/bin/true` installed and appropriate namespace/capture +privileges. The tool does not enter an image itself or verify running image pins. +The named namespace must already exist, differ from the caller's network +namespace, and contain the specified UP interface with the exact MAC. The tool +does not create or modify namespaces, interfaces, addresses, routes or firewall +rules. A name and attestations alone cannot establish isolation. + +## Captured input contract + +`verify` reads these local exports (each at most 8 MiB): + +- `operation.json`: actual DeviceInstallation API object, including immutable + `spec.bootNetwork`, metadata UID/timestamp and `status.admission.fence`. +- `claim.json`: actual IPClaim for `-boot`, with operation label, + class/scope, allocator-selected address (no `spec.address`), Delete reclaim + policy, Bound status, address, exact `/32`, pool and bound allocation reference. +- `allocation.json`: referenced actual IPAllocation, its Claim purpose, Ready + status, claim back-reference, pool, address and exact `/32`. +- `boot-summary.json`: allowlisted worker admission fields `operation`, `fence`, + `mac`, `address`, `created`, `published`, `expires`. Export only those fields; + never copy the boot token, seed or receipt into this summary. +- `dhcp-applied.log`: retained producer JSONL with `at`, `instance`, `feed`, as + written by the real authenticated feed handler. Retired/rejected contacts + cannot establish applied or withdrawn reservations. + +The verifier checks exact address and fence correlation, canonical feed revision +hashes, an applied admission feed during the admission window, and a latest +post-publication withdrawal feed from every expected instance. It does not +authenticate exports or prove their collection provenance, custody, handoff, +historical Device reservations, Kea configuration, packets or client outcomes. +It reports these limitations as `notProven`. Keep source exports, Kubernetes UIDs +and resourceVersions, timestamps, operation/custody/handoff IDs, feed revisions, +Kea configuration/lease state and packet captures together in private evidence. + +The existing feed must remain the genuine TLS endpoint +`GET /dhcp/v1/reservations`, with bearer authentication and +`X-Fleet-DHCP-Instance`. Never use insecure TLS, pass tokens on command lines, +print kubeconfigs, or substitute a fake feed. This tool does not fetch the feed; +adding read-only authenticated collection is remaining work. + +## Client evidence and remaining orchestration + +`probe` starts an owned packet capture before bounded `udhcpc` acquisition. It +writes `client.log`, `client.pcap`, `capture.log` and `probe.json` into a new private +directory. Python opens the PCAP before starting tcpdump and supplies its stdout +descriptor, allowing tcpdump to drop privileges without reopening a private path. +Capture diagnostics use a separate log. It preserves all files on failure and stops only its own child process +groups. It never deletes Kubernetes resources, a claim, a lease or a namespace. +An udhcpc error, timeout or absence of a lease is **not** interpreted as denial: +the capture may expose no relay, dropped replies, an invalid subnet or no server. +Repeated probes require new directories. They must be bracketed with a working +admitted-client positive control and correlated server/relay captures before +negative outcomes can be asserted. PCAPs and logs are private evidence; inspect +before sharing. There is no automated packet assertion yet. + +The hook is `/bin/true`, so the client does not configure its leased address or +routes. This tests fresh acquisition only. Real T1 renewal requires keeping a +client alive with the lease configured and capturing a unicast DHCPREQUEST with +`ciaddr` and a matching ACK. Relayed T2 rebind requires separate broadcast/relay +packet evidence. A second fresh acquisition or relayed rebind must never be +reported as T1 renewal. The runner does not implement either renewal assertion. + +A complete runner still needs reviewed synthetic emulator packaging, isolated +relay/client return routing, and real admission orchestration: +`fleet-multiplane admit-install -config ` must use +`Allocator.Install` and custody delivery; then `fleet-multiplane site-worker` +must consume the real delivered handoff. Do not invoke a unit admission helper, +`lab open -address`, manual reservations or fake installer completion. The +repository's state-only `fake_virsh.py` can model BMC effects but does not prove +installer success. Producer and worker must share actual journal/boot evidence. + +The remaining end-to-end assertions are unknown-MAC denial, exact claim-address +lease acquisition, direct T1 renewal, separately classified relayed rebind, and +no **fresh grant** after every expected Kea instance applies withdrawal. A +deadline can withdraw the reservation while custody outcome remains unknown: +retain the claim and recovery hold until recovery establishes release safety. +Reservation withdrawal does not revoke an existing lease. No automatic claim +deletion or cleanup-by-label sweep is provided. A future runner must record +ownership by exact UID before cleaning only its own safely releasable resources. + +Related contracts: [boot network proposal](../../docs/enhancements/boot-network/README.md), +[existing local full harness](../multiplane/run.sh), and +[DHCP client lab](../boot-network/kea-lab.sh) (client mechanics only). diff --git a/hack/dhcp/staging-proof.py b/hack/dhcp/staging-proof.py new file mode 100755 index 00000000..bef39f8f --- /dev/null +++ b/hack/dhcp/staging-proof.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +"""Partial, offline evidence checks and isolated client capture; never a proof runner.""" +import argparse +import datetime as dt +import hashlib +import ipaddress +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import time + + +class Refused(Exception): + pass + + +def require(ok, message): + if not ok: + raise Refused(message) + + +def read(path): + require(Path(path).stat().st_size <= 8 * 1024 * 1024, "input exceeds size limit") + return json.loads(Path(path).read_text()) + + +def stamp(value): + value = dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + require(value.tzinfo is not None and value.year > 2000, "invalid evidence timestamp") + return value + + +def preflight(path): + c = read(path) + require(c["schema"] == 1, "unsupported manifest schema") + excluded = c["excludedSites"] + require(isinstance(excluded, list) and excluded, "reviewed site exclusions required") + require(all(isinstance(site, str) and re.fullmatch(r"[a-zA-Z0-9_.:-]+", site) for site in excluded), "invalid site exclusion") + for key in ("context", "namespace", "site", "emulator", "runtime", "netns", "interface", "ipamClass"): + require(isinstance(c[key], str) and re.fullmatch(r"[a-zA-Z0-9_.:-]+", c[key]), "missing or invalid runtime identity") + require(not any(site.lower() in c[key].lower() for site in excluded), "excluded site identity") + require(isinstance(c["ipamScope"], dict) and c["ipamScope"], "complete IPAM scope required") + for role, reference in c["ipamScope"].items(): + require(re.fullmatch(r"[a-zA-Z0-9_.:-]+", role), "invalid scope role") + require(isinstance(reference, dict) and set(reference) == {"apiGroup", "kind", "name"}, "complete scope reference required") + for field, value in reference.items(): + require(isinstance(value, str) and (value == "" and field == "apiGroup" or re.fullmatch(r"[a-zA-Z0-9_.:-]+", value)), "invalid scope reference") + require(not any(site.lower() in value.lower() for site in excluded), "excluded site identity") + require(c["netns"].startswith("fleet-proof-"), "client requires a dedicated fleet-proof namespace") + require(c["interface"] != "lo", "client interface cannot be loopback") + require(c["runtime"] == "linux-netns-relay", "a prepared isolated Linux relay runtime is required") + for key in ("isolated", "syntheticEmulator", "noPhysicalHosts", "noPublicDHCP", "relayReturnRouteReviewed", "directRenewalRouteReviewed"): + require(c[key] is True, "isolation and return-path review is incomplete") + require(re.fullmatch(r"[0-9a-f]{40}", c["reviewedCommit"]), "reviewed commit pin required") + require(type(c["seconds"]) is int and 1 <= c["seconds"] <= 120, "probe duration must be an integer 1..120 seconds") + require(re.fullmatch(r"[0-9a-f]{2}(:[0-9a-f]{2}){5}", c["mac"]), "canonical client MAC required") + require(int(c["mac"][:2], 16) & 3 == 2, "client MAC must be local unicast") + require(set(c["images"]) == {"worker", "emulator", "kea", "synchronizer", "client"}, "all runtime images need reviewed pins") + for value in c["images"].values(): + require(re.fullmatch(r"[^\s]+@sha256:[0-9a-f]{64}", value), "immutable image digest required") + require(set(c["artifacts"]) == {"topology", "emulatorConfig", "keaConfig", "enrollment"}, "reviewed runtime artifacts required") + for artifact in c["artifacts"].values(): + p = Path(path).resolve().parent / artifact["path"] + require(p.is_file() and p.stat().st_size <= 8 * 1024 * 1024, "reviewed artifact unavailable") + require(hashlib.sha256(p.read_bytes()).hexdigest() == artifact["sha256"], "reviewed artifact digest mismatch") + require(c["expectedInstances"] and len(set(c["expectedInstances"])) == len(c["expectedInstances"]), "expected DHCP instance set required") + for instance in c["expectedInstances"]: + require(re.fullmatch(r"[a-z0-9]([a-z0-9.-]{0,61}[a-z0-9])?", instance), "invalid DHCP instance") + return c + + +def verify_feed(feed): + rows = feed["reservations"] + require(isinstance(rows, list), "invalid feed reservations") + canonical = [] + for row in rows: + require(re.fullmatch(r"[0-9a-f]{2}(:[0-9a-f]{2}){5}", row["mac"]), "noncanonical feed MAC") + address = ipaddress.ip_address(row["address"]) + require(str(address) == row["address"] and not address.is_unspecified, "noncanonical feed address") + expires = stamp(row["expires"]) + require(expires.strftime("%Y-%m-%dT%H:%M:%SZ") == row["expires"], "noncanonical feed expiry") + canonical.append({"mac": row["mac"], "address": row["address"], "expires": row["expires"]}) + require(canonical == sorted(canonical, key=lambda r: r["mac"]), "unordered feed") + require(len({r["mac"] for r in rows}) == len(rows) == len({r["address"] for r in rows}), "duplicate reservation") + digest = hashlib.sha256(json.dumps(canonical, separators=(",", ":")).encode()).hexdigest() + require(feed["revision"] == digest, "feed revision mismatch") + issued = stamp(feed["issued"]) + require(issued.strftime("%Y-%m-%dT%H:%M:%SZ") == feed["issued"], "noncanonical feed issue time") + return issued + + +def verify(c, root): + """Verify captured IPAM and feed consistency, not custody or packet delivery.""" + root = Path(root) + op, claim, allocation, boot = [read(root / p) for p in ("operation.json", "claim.json", "allocation.json", "boot-summary.json")] + name = op["metadata"]["name"] + require(op["kind"] == "DeviceInstallation", "expected a real installation object") + require(op["metadata"]["uid"] and claim["metadata"]["uid"] and allocation["metadata"]["uid"], "API object UIDs required") + require(op["metadata"]["namespace"] == claim["metadata"]["namespace"] == allocation["metadata"]["namespace"] == c["namespace"], "IPAM namespace mismatch") + require(claim["metadata"]["name"] == name + "-boot", "claim is not operation-derived") + require(claim["metadata"]["labels"]["fleet.datumapis.com/operation"] == name, "claim operation label mismatch") + require(claim["spec"]["className"] == c["ipamClass"] and claim["spec"]["scope"] == c["ipamScope"], "claim class or scope mismatch") + require(claim["spec"]["reclaimPolicy"] == "Delete" and not claim["spec"].get("address"), "claim must use allocator-selected address and Fleet reclaim policy") + require(stamp(claim["metadata"]["creationTimestamp"]) <= stamp(op["metadata"]["creationTimestamp"]), "claim postdates operation") + status = claim["status"] + require(status["phase"] == "Bound", "claim is not Bound") + address = ipaddress.IPv4Address(status["address"]) + require(status["allocatedCIDR"] == str(address) + "/32", "claim must hold exact /32") + require(status["boundAllocationRef"]["name"] == allocation["metadata"]["name"], "allocation reference mismatch") + require(allocation["spec"]["claimRef"]["name"] == claim["metadata"]["name"], "allocation back-reference mismatch") + require(allocation["spec"]["purpose"] == "Claim" and allocation["status"]["phase"] == "Ready", "allocation is not a ready claim allocation") + require(allocation["spec"]["poolRef"] == status["poolRef"], "allocation pool mismatch") + require(allocation["status"]["address"] == str(address) and allocation["status"]["allocatedCIDR"] == status["allocatedCIDR"], "allocation address mismatch") + network = op["spec"]["bootNetwork"] + require(network["addressClaim"] == {"apiGroup": "ipam.miloapis.com", "kind": "IPClaim", "name": name + "-boot"}, "operation claim reference mismatch") + require(network["address"] == boot["address"] == str(address), "operation/admission/IPAM address mismatch") + fence = boot["fence"] + require(type(fence) is int and fence > 0, "invalid admission fence") + operation_key = f"deviceinstallation.{name}.{fence}" + if len(operation_key) > 128: + operation_key = f"deviceinstallation.{hashlib.sha256(name.encode()).hexdigest()[:32]}.{fence}" + require(boot["operation"] == operation_key and boot["mac"] == c["mac"], "boot admission identity mismatch") + require(op["status"]["admission"]["fence"] == boot["fence"], "operation admission fence mismatch") + require(set(boot) == {"operation", "fence", "mac", "address", "created", "published", "expires"}, "boot summary must use only allowlisted fields and omit secrets") + created, published, expires = [stamp(boot[k]) for k in ("created", "published", "expires")] + require(created <= published < expires, "invalid admission window") + reports = root / "dhcp-applied.log" + require(reports.stat().st_size <= 8 * 1024 * 1024, "report log exceeds size limit") + served, latest = set(), {} + previous = None + for line in reports.read_text().splitlines(): + r = json.loads(line) + at = stamp(r["at"]) + require(previous is None or at >= previous, "out-of-order report log") + previous = at + if r.get("retired") or r.get("rejected"): + continue + issued = verify_feed(r["feed"]) + require(issued <= at, "report precedes feed issuance") + instance = r["instance"] + require(instance in c["expectedInstances"], "unexpected applied DHCP instance") + rows = r["feed"]["reservations"] + matching = [v for v in rows if v["mac"] == boot["mac"] and v["address"] == str(address)] + if published < issued < expires and at < expires and matching: + require(stamp(matching[0]["expires"]) == expires.replace(microsecond=0), "feed admission expiry mismatch") + served.add(instance) + latest[instance] = (issued, rows) + require(served, "no applied admission feed") + for instance in c["expectedInstances"]: + require(instance in latest, "missing expected instance report") + issued, rows = latest[instance] + require(issued > published and not any(v["mac"] == boot["mac"] or v["address"] == str(address) for v in rows), "withdrawal unproven") + return {"status": "PARTIAL_EVIDENCE_ONLY", "operation": name, "claim": claim["metadata"]["name"], "address": str(address), "checks": ["IPAM binding", "admission feed applied", "latest expected feeds withdrawn"], "notProven": ["custody and handoff provenance", "TLS/authenticated collection", "Kea state", "unknown MAC denial", "exact client lease", "T1 direct renewal", "relayed rebind", "fresh grant denied after withdrawal"], "existingLeaseRevoked": False} + + +def stop(process): + if process and process.poll() is None: + os.killpg(process.pid, signal.SIGTERM) + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired: + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=3) + + +def probe(c, destination): + require(sys.platform == "linux", "probe requires Linux and a prepared isolated netns") + require(Path("/run/netns", c["netns"]).exists(), "reviewed network namespace is missing") + base = ["ip", "netns", "exec", c["netns"]] + target = subprocess.run(base + ["readlink", "/proc/self/ns/net"], capture_output=True, timeout=5, check=True).stdout.decode().strip() + require(target != os.readlink("/proc/self/ns/net"), "client namespace aliases host networking") + link = json.loads(subprocess.run(base + ["ip", "-j", "link", "show", "dev", c["interface"]], capture_output=True, timeout=5, check=True).stdout) + require(len(link) == 1 and link[0]["address"] == c["mac"] and "UP" in link[0]["flags"], "client interface identity or state mismatch") + dest = Path(destination).resolve() + dest.mkdir(mode=0o700) + capture = client = None + try: + with (dest / "capture.log").open("xb") as caplog, (dest / "client.log").open("xb") as clientlog, (dest / "client.pcap").open("xb") as pcap: + capture = subprocess.Popen(base + ["tcpdump", "-U", "-n", "-i", c["interface"], "-w", "-", "udp and (port 67 or port 68)"], stdout=pcap, stderr=caplog, start_new_session=True) + time.sleep(0.5) + require(capture.poll() is None, "packet capture failed to start") + client = subprocess.Popen(base + ["udhcpc", "-i", c["interface"], "-n", "-q", "-f", "-t", "4", "-T", "2", "-s", "/bin/true"], stdout=clientlog, stderr=clientlog, start_new_session=True) + try: + code = client.wait(timeout=c["seconds"]) + except subprocess.TimeoutExpired: + code = None + require(capture.poll() is None, "packet capture ended during probe") + (dest / "probe.json").write_text(json.dumps({"status": "RAW_EVIDENCE_ONLY", "mac": c["mac"], "netns": c["netns"], "clientExit": code, "seconds": c["seconds"], "renewalTested": False}) + "\n") + finally: + stop(client) + stop(capture) + return {"status": "RAW_EVIDENCE_ONLY", "renewalTested": False} + + +def main(): + os.umask(0o077) + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("command", choices=("preflight", "verify", "probe")) + p.add_argument("--manifest", required=True) + p.add_argument("--evidence", help="existing captured evidence for verify; NEW private directory for probe") + args = p.parse_args() + try: + c = preflight(args.manifest) + if args.command == "preflight": + result = {"status": "INPUTS_CHECKED_ONLY", "liveIsolationVerified": False, "orchestrationImplemented": False} + else: + require(args.evidence, "--evidence is required") + result = verify(c, args.evidence) if args.command == "verify" else probe(c, args.evidence) + print(json.dumps(result, sort_keys=True)) + except Refused as e: + print("REFUSED: " + str(e), file=sys.stderr) + return 1 + except (OSError, ValueError, KeyError, TypeError, AttributeError, IndexError, OverflowError, subprocess.SubprocessError): + print("REFUSED: missing, malformed or unavailable input/runtime (contents suppressed)", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/hack/dhcp/validate-producer.sh b/hack/dhcp/validate-producer.sh new file mode 100644 index 00000000..b8d8357a --- /dev/null +++ b/hack/dhcp/validate-producer.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/../.." +render=$(mktemp) +trap 'rm -f "$render"' EXIT +kustomize build config/site/dhcp/producer > "$render" +python3 - "$render" <<'PY' +import pathlib, sys, yaml + +docs = list(yaml.safe_load_all(pathlib.Path(sys.argv[1]).read_text())) +assert all(doc['kind'] not in ('Secret', 'ConfigMap', 'PersistentVolumeClaim') for doc in docs) +deployments = [doc for doc in docs if doc['kind'] == 'Deployment'] +assert len(deployments) == 1 +deployment = deployments[0] +assert deployment['metadata']['name'] == 'fleet-site-boot' +assert deployment['spec']['replicas'] == 1 +assert deployment['spec']['strategy']['type'] == 'Recreate' +pod = deployment['spec']['template']['spec'] +assert pod['automountServiceAccountToken'] is False +assert not pod.get('hostNetwork') +assert pod['securityContext']['runAsUser'] == 65532 +assert pod['securityContext']['runAsNonRoot'] is True +assert pod['securityContext']['fsGroup'] == 65532 +containers = {container['name']: container for container in pod['containers']} +assert set(containers) == {'boot', 'dhcp-feed'} +assert containers['boot']['command'] == ['fleet-multiplane', 'boot-service'] +assert containers['dhcp-feed']['command'][:2] == ['fleet-multiplane', 'dhcp-feed'] +volumes = {volume['name']: volume for volume in pod['volumes']} +assert volumes['state']['persistentVolumeClaim']['claimName'] == 'fleet-site-state' +for name in ('dhcp-sync-token', 'dhcp-feed-tls'): + assert volumes[name]['secret']['defaultMode'] == 0o440 +for container in containers.values(): + assert container['image'] == '${FLEET_SITE_IMAGE}' + security = container['securityContext'] + assert security['allowPrivilegeEscalation'] is False + assert security['readOnlyRootFilesystem'] is True + assert security['capabilities'] == {'drop': ['ALL']} + assert not security.get('privileged') + assert not any(port.get('hostPort') for port in container.get('ports', [])) + mounts = {mount['mountPath']: mount for mount in container['volumeMounts']} + assert mounts['/var/lib/fleet-local'] == {'name': 'state', 'mountPath': '/var/lib/fleet-local', 'subPath': 'journal', 'readOnly': True} + assert mounts['/var/lib/fleet-boot']['subPath'] == 'boot-evidence' + assert not mounts['/var/lib/fleet-boot'].get('readOnly') + assert all('libvirt' not in mount for mount in mounts) + assert {'name': 'FLEET_SITE_PROVIDER', 'value': 'redfish'} in container['env'] +feed = containers['dhcp-feed'] +assert feed['securityContext']['runAsUser'] == 65532 +assert feed['securityContext']['runAsNonRoot'] is True +assert '-tls-cert' in feed['command'] and '-tls-key' in feed['command'] +assert '-sync-token-file' in feed['command'] and '-delivery-methods' in feed['command'] +enrollment = next(env for env in feed['env'] if env['name'] == 'FLEET_REDFISH_ENROLLMENT') +assert enrollment['valueFrom']['configMapKeyRef'] == {'name': 'fleet-site-redfish-enrollment', 'key': 'enrollment'} +assert not any('hostPath' in volume for volume in volumes.values()) +for service in [doc for doc in docs if doc['kind'] == 'Service']: + assert service['spec'].get('type', 'ClusterIP') == 'ClusterIP' + assert not service['spec'].get('externalIPs') +print('PASS inactive producer: real roles, shared journal/evidence, external enrollment and secrets, no hypervisor or public endpoint') +PY diff --git a/hack/validate-network-boot-inactive.sh b/hack/validate-network-boot-inactive.sh index dfd91e21..bc857183 100755 --- a/hack/validate-network-boot-inactive.sh +++ b/hack/validate-network-boot-inactive.sh @@ -19,6 +19,7 @@ opt_in=( config/site/dhcp/feed config/site/dhcp/isolated config/site/dhcp/isolated-example + config/site/dhcp/producer config/site/redfish/synced/graph config/site/redfish/synced/services )