diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d15c3ed..fe3403f7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,14 @@ jobs: with: {go-version-file: go.mod, cache: true} - uses: imranismail/setup-kustomize@v2 with: {kustomize-version: 5.8.1} + - name: Verify session and coordination CRD generation + run: | + go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.23.0 crd paths="./internal/api/session/...;./internal/api/coordination/..." output:crd:artifacts:config=config/crd/bases + git diff --exit-code -- config/crd/bases + - run: kustomize build config/crd >/dev/null + - run: kustomize build config/federation >/dev/null + - run: kustomize build config/manager >/dev/null + - run: kustomize build config/location >/dev/null - run: go test ./... - run: go test -race ./... - run: go vet ./... diff --git a/.github/workflows/test-e2e.yml b/.github/workflows/test-e2e.yml new file mode 100644 index 00000000..96e3f6c2 --- /dev/null +++ b/.github/workflows/test-e2e.yml @@ -0,0 +1,89 @@ +name: machine-management-e2e + +on: + pull_request: + push: + branches: + - main + +permissions: + contents: read + +jobs: + virtual-bmc: + runs-on: ubuntu-24.04 + timeout-minutes: 50 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version-file: go.mod + cache: true + - name: Install pinned tools + run: | + set -euxo pipefail + tools_bin="${RUNNER_TEMP}/fleet-tools" + mkdir -p "${tools_bin}" + curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/v0.33.0/kind-linux-amd64 -o "${tools_bin}/kind" + curl -fsSL https://github.com/kubernetes-sigs/kind/releases/download/v0.33.0/kind-linux-amd64.sha256sum -o /tmp/kind.sha256 + sed "s#kind-linux-amd64#${tools_bin}/kind#" /tmp/kind.sha256 | sha256sum -c - + chmod 0755 "${tools_bin}/kind" + curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl -o "${tools_bin}/kubectl" + curl -fsSL https://dl.k8s.io/release/v1.37.0/bin/linux/amd64/kubectl.sha256 -o /tmp/kubectl.sha256 + echo "$(cat /tmp/kubectl.sha256) ${tools_bin}/kubectl" | sha256sum -c - + chmod 0755 "${tools_bin}/kubectl" + helm_version=v3.17.3 + curl -fsSL "https://get.helm.sh/helm-${helm_version}-linux-amd64.tar.gz" -o /tmp/helm.tgz + curl -fsSL "https://get.helm.sh/helm-${helm_version}-linux-amd64.tar.gz.sha256sum" -o /tmp/helm.sha256 + helm_sha=$(awk '{print $1}' /tmp/helm.sha256) + echo "${helm_sha} /tmp/helm.tgz" | sha256sum -c - + tar -xzf /tmp/helm.tgz -C /tmp + install -m 0755 /tmp/linux-amd64/helm "${tools_bin}/helm" + GOBIN="${tools_bin}" go install github.com/go-task/task/v3/cmd/task@v3.41.0 + echo "${tools_bin}" >>"${GITHUB_PATH}" + "${tools_bin}/kind" version + "${tools_bin}/kubectl" version --client + "${tools_bin}/helm" version + "${tools_bin}/task" --version + - name: Portable tests + run: | + task test + bash hack/e2e/test-common.sh + - name: Start virtual-BMC environment + run: task e2e:up + - name: End-to-end scenarios + run: | + set -o pipefail + task e2e:test 2>&1 | tee .e2e/e2e-test.log + - name: Collect diagnostics + if: always() + run: task e2e:diagnostics || true + - name: Summarize failure + if: failure() + run: | + if [[ -f .e2e/e2e-test.log ]]; then + tail -n 100 .e2e/e2e-test.log + { + tail -n 20 .e2e/e2e-test.log + if [[ -f .e2e/proxy.log ]]; then + echo "proxy log:" + tail -n 20 .e2e/proxy.log + fi + } >"${RUNNER_TEMP}/fleet-e2e-error.txt" + message=$(tr '\n' ' ' <"${RUNNER_TEMP}/fleet-e2e-error.txt" | sed 's/%/%25/g; s/\r/%0D/g; s/\n/%0A/g') + echo "::error title=E2E failure::${message}" + fi + - name: Upload diagnostics and validator reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: fleet-machine-management-evidence + path: | + .e2e/diagnostics + .e2e/validators + .e2e/*.log + include-hidden-files: true + if-no-files-found: ignore + - name: Tear down + if: always() + run: task e2e:down diff --git a/.gitignore b/.gitignore index d105526d..cc01a490 100644 --- a/.gitignore +++ b/.gitignore @@ -17,10 +17,18 @@ /servers.com.txt # Local outputs and scratch work +/bin/ +/.e2e/ +/.task/ /tmp/ /dist/ /coverage/ /worktrees/ +coverage.out +*.kubeconfig +credentials.json +ready.json +ca.pem /milo-acceptance-evidence/ **/milo-acceptance-config.json diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..646490e2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM golang:1.26.4-bookworm AS build +WORKDIR /src +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +ARG PACKAGE +ARG BINARY +RUN CGO_ENABLED=0 go build -trimpath -ldflags='-s -w' -o /out/${BINARY} ${PACKAGE} + +FROM debian:12.12-slim +ARG BINARY +COPY --from=build /out/${BINARY} /usr/local/bin/app +USER 65532:65532 +ENTRYPOINT ["/usr/local/bin/app"] diff --git a/README.md b/README.md index 63c3661b..3a22164a 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,17 @@ rejects work that requires those integrations and makes no provider changes. See [implementation status](docs/development/README.md) for the implemented subset and remaining gaps. +The repository also contains a deliberately narrow prototype for +allocation-scoped customer Redfish access. Its lifecycle integration consumes +service-owned Secret custody and serializes sessions against installation and +release, rather than trusting pre-bound allocation CRDs. Production access +authorization, trusted observation resolution, and executor fencing remain +unwired; the session controller defaults to unready and denies new sessions. +An explicit [synthetic fixture mode](docs/implementation/synthetic-bmc-fixture.md) +wires the runnable prototype to real Coordinator custody without enabling a +production fallback. +See the [implemented lifecycle contract](docs/implementation/secure-bmc-lifecycle.md). + ## What Fleet is for - Plan, register, and verify physical infrastructure and its connections. @@ -46,3 +57,8 @@ today. Then choose a topic: Contributors should also read the [repository guidance](AGENTS.md) and [implementation roadmap](docs/development/roadmap.md). + +## Secure BMC prototype + +See the [prototype guide](docs/implementation/machine-management-prototype.md) for +build commands, the Linux E2E harness, and exact validation limits. diff --git a/Taskfile.yaml b/Taskfile.yaml index 55ffedb5..b2cb0fa1 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -1,6 +1,64 @@ version: '3' +vars: + GO_CACHE: '{{default "/tmp/fleet-go-cache" .GO_CACHE}}' + tasks: + generate: + desc: Regenerate the provisional CRDs from Kubebuilder markers + cmds: + - go run sigs.k8s.io/controller-tools/cmd/controller-gen@v0.23.0 crd paths="./internal/api/session/...;./internal/api/coordination/..." output:crd:artifacts:config=config/crd/bases + + test: + desc: Run portable unit and API/controller integration tests + cmds: + - env GOCACHE={{.GO_CACHE}} go test ./... + - git diff --check + + build: + desc: Build every prototype executable + cmds: + - mkdir -p bin + - env GOCACHE={{.GO_CACHE}} go build -o bin/datumctl-fleet ./cmd/datumctl-fleet + - env GOCACHE={{.GO_CACHE}} go build -o bin/fleet-controller ./cmd/fleet-controller + - env GOCACHE={{.GO_CACHE}} go build -o bin/fleet-gateway ./cmd/fleet-gateway + - env GOCACHE={{.GO_CACHE}} go build -o bin/fleet-relay ./cmd/fleet-relay + + e2e:up: + desc: Create Karmada management/member Kind clusters and the real sushy/libvirt BMC environment + cmds: + - ./hack/e2e/up.sh + + e2e:test: + desc: Run every machine-management scenario and both DMTF validators + cmds: + - ./hack/e2e/test.sh + + e2e:test:path: + desc: Run one E2E path (currently DIR=machine-management) + requires: + vars: [DIR] + preconditions: + - sh: test '{{.DIR}}' = machine-management + msg: 'the only implemented E2E path is DIR=machine-management' + cmds: + - ./hack/e2e/test.sh + + e2e:diagnostics: + desc: Collect cluster, gateway, libvirt, and PXE evidence + cmds: + - ./hack/e2e/diagnostics.sh + + e2e:down: + desc: Remove only the named Fleet E2E resources + cmds: + - ./hack/e2e/down.sh + + e2e:openvpn:up: + desc: Replace the default private route with the separate OpenVPN qualification profile + cmds: + - ./hack/e2e/openvpn-up.sh + manifests:validate: desc: Render and validate the production Fleet and Milo manifest roots. cmds: diff --git a/cmd/datumctl-fleet/main.go b/cmd/datumctl-fleet/main.go new file mode 100644 index 00000000..293df11a --- /dev/null +++ b/cmd/datumctl-fleet/main.go @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "errors" + "fmt" + "os" + + "go.datum.net/datumctl/plugin" + + fleetcmd "go.datum.net/fleet/internal/cmd/fleet" +) + +var version = "dev" + +func main() { + plugin.ServeManifest(plugin.Manifest{Name: "fleet", Version: version, Description: "Manage Datum Fleet machines and secure management sessions", APIVersion: 1, MinAPIVersion: 1}) + if err := fleetcmd.Command().Execute(); err != nil { + var exit *fleetcmd.ExitError + if errors.As(err, &exit) { + fmt.Fprintln(os.Stderr, "Error:", exit.Err) + os.Exit(exit.Code) + } + fmt.Fprintln(os.Stderr, "Error:", err) + os.Exit(1) + } +} diff --git a/cmd/fleet-controller/main.go b/cmd/fleet-controller/main.go new file mode 100644 index 00000000..2e8392a9 --- /dev/null +++ b/cmd/fleet-controller/main.go @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "flag" + "log/slog" + "net/http" + "os" + "time" + + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/clientcmd" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/healthz" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/staging/sessionfixture" +) + +func main() { + federationKubeconfig := flag.String("federation-kubeconfig", "", "kubeconfig for the Karmada federation API") + webhookCertDir := flag.String("webhook-cert-dir", "/var/run/fleet-webhook", "webhook serving certificate directory") + metrics := flag.String("metrics-bind-address", ":8080", "metrics address") + probe := flag.String("health-probe-bind-address", ":8081", "probe address") + authorityFreshness := flag.Duration("authority-freshness", 2*time.Minute, "maximum cached allocation-authority lifetime at a location") + perClaimLimit := flag.Int("per-claim-session-limit", 1, "maximum concurrent sessions for one claim") + perProjectLimit := flag.Int("per-project-session-limit", 5, "maximum concurrent sessions for one consumer project") + lifecycleMode := flag.String("lifecycle-mode", "production", "production (unready) or synthetic (test-only private fixture grants)") + privateNamespace := flag.String("private-namespace", controller.SystemNamespace, "private Coordinator Secret namespace") + flag.Parse() + if *federationKubeconfig == "" { + slog.Error("--federation-kubeconfig is required") + os.Exit(2) + } + scheme := runtime.NewScheme() + must(clientgoscheme.AddToScheme(scheme)) + must(fleetv1.AddToScheme(scheme)) + must(fleetv1alpha1.AddToScheme(scheme)) + must(coordinationv1.AddToScheme(scheme)) + federationConfig, err := clientcmd.BuildConfigFromFlags("", *federationKubeconfig) + must(err) + federationClient, err := client.New(federationConfig, client.Options{Scheme: scheme}) + must(err) + wh := webhook.NewServer(webhook.Options{CertDir: *webhookCertDir}) + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{Scheme: scheme, Metrics: metricsserver.Options{BindAddress: *metrics}, HealthProbeBindAddress: *probe, WebhookServer: wh}) + must(err) + privateClient, err := client.New(mgr.GetConfig(), client.Options{Scheme: scheme}) + must(err) + lifecycle, readiness, err := lifecycleWiring(*lifecycleMode, privateClient, *privateNamespace) + must(err) + mgr.GetWebhookServer().Register("/mutate-metal-datumapis-com-v1alpha1-machinemanagementsession", &admission.Webhook{Handler: controller.SessionAdmission{}}) + must((&controller.SessionReconciler{Lifecycle: lifecycle, PerClaimLimit: *perClaimLimit, PerProjectLimit: *perProjectLimit}).SetupWithManager(mgr)) + must((&controller.ProjectionReconciler{Lifecycle: lifecycle, FederationClient: federationClient, Freshness: *authorityFreshness}).SetupWithManager(mgr)) + must(mgr.AddHealthzCheck("healthz", healthz.Ping)) + must(mgr.AddReadyzCheck("lifecycle-authority", readiness)) + slog.Info("starting Fleet session controllers") + must(mgr.Start(ctrl.SetupSignalHandler())) +} + +func lifecycleWiring(mode string, kube client.Client, namespace string) (controller.SessionLifecycle, healthz.Checker, error) { + switch mode { + case "production": + return nil, func(*http.Request) error { return controller.ErrUnsupported }, nil + case "synthetic": + authority, err := sessionfixture.NewAuthority(kube, namespace) + if err != nil { + return nil, nil, err + } + slog.Warn("SYNTHETIC TEST ONLY: fixture grants replace production authorization and provider observations", "privateNamespace", namespace) + return authority, healthz.Ping, nil + default: + return nil, nil, controller.ErrUnsupported + } +} + +func must(err error) { + if err != nil { + slog.Error("fatal", "error", err) + os.Exit(1) + } +} diff --git a/cmd/fleet-controller/main_test.go b/cmd/fleet-controller/main_test.go new file mode 100644 index 00000000..2a3b8054 --- /dev/null +++ b/cmd/fleet-controller/main_test.go @@ -0,0 +1,38 @@ +package main + +import ( + "errors" + "testing" + + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + "go.datum.net/fleet/internal/controller" +) + +func TestLifecycleModeIsExplicitAndFailClosed(t *testing.T) { + scheme := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + kube := fake.NewClientBuilder().WithScheme(scheme).Build() + authority, ready, err := lifecycleWiring("production", kube, "private") + if err != nil || authority != nil || !errors.Is(ready(nil), controller.ErrUnsupported) { + t.Fatalf("production did not fail closed: %v %v", authority, err) + } + if _, _, err := lifecycleWiring("typo", kube, "private"); err == nil { + t.Fatal("unrecognized mode was accepted") + } + authority, ready, err = lifecycleWiring("synthetic", kube, "private") + if err != nil || ready(nil) != nil { + t.Fatalf("synthetic wiring: %v", err) + } + concrete, ok := authority.(*controller.LifecycleSessionAuthority) + if !ok || concrete.Coordinator == nil || concrete.Resolver == nil { + t.Fatalf("missing real custody or resolver: %T", authority) + } + if _, _, err := lifecycleWiring("synthetic", kube, ""); err == nil { + t.Fatal("accepted missing private namespace") + } +} diff --git a/cmd/fleet-gateway/main.go b/cmd/fleet-gateway/main.go new file mode 100644 index 00000000..547eebe8 --- /dev/null +++ b/cmd/fleet-gateway/main.go @@ -0,0 +1,70 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "flag" + "log/slog" + "os" + "strings" + + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/healthz" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/gateway" +) + +func main() { + var cfg gateway.Config + var tokenFile string + flag.StringVar(&cfg.RelayAddress, "relay-address", "fleet-relay.machine-access-system.svc:8443", "relay address") + flag.StringVar(&cfg.RelayPublicURL, "relay-public-url", "tcp://127.0.0.1:8443", "client-visible relay URL") + flag.StringVar(&tokenFile, "relay-token-file", "/var/run/secrets/fleet/relay-token", "relay registration token") + flag.StringVar(&cfg.Audience, "audience", "fleet-gateway/location-prototype/r1", "proof audience") + flag.StringVar(&cfg.SupportedAdapter, "supported-adapter", "sushy-libvirt-v1", "qualified local enrollment adapter") + flag.StringVar(&cfg.EnrollmentNamespace, "enrollment-namespace", "machine-access-system", "namespace containing safe capacity copies and private enrollments") + flag.StringVar(&cfg.JournalDir, "journal-dir", "/var/lib/fleet", "durable journal directory") + flag.StringVar(&cfg.StateDir, "state-dir", "/var/lib/fleet/sessions", "gateway state directory") + flag.BoolVar(&cfg.DropResetResponseOnce, "fault-drop-reset-response-once", false, "test-only lost response injection") + metrics := flag.String("metrics-bind-address", ":8080", "metrics address") + probe := flag.String("health-probe-bind-address", ":8081", "probe address") + flag.Parse() + cfg.RelayGatewayToken = readSecret(tokenFile) + scheme := runtime.NewScheme() + must(clientgoscheme.AddToScheme(scheme)) + must(fleetv1.AddToScheme(scheme)) + must(fleetv1alpha1.AddToScheme(scheme)) + must(coordinationv1.AddToScheme(scheme)) + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + Scheme: scheme, + Cache: cache.Options{DefaultNamespaces: map[string]cache.Config{ + "machine-access-system": {}, + }}, + Metrics: metricsserver.Options{BindAddress: *metrics}, + HealthProbeBindAddress: *probe, + }) + must(err) + must((&gateway.Reconciler{Config: cfg}).SetupWithManager(mgr)) + must(mgr.AddHealthzCheck("healthz", healthz.Ping)) + must(mgr.AddReadyzCheck("readyz", healthz.Ping)) + slog.Info("starting location gateway", "audience", cfg.Audience, "supportedAdapter", cfg.SupportedAdapter) + must(mgr.Start(ctrl.SetupSignalHandler())) +} +func readSecret(path string) string { + b, err := os.ReadFile(path) + must(err) + return strings.TrimSpace(string(b)) +} +func must(err error) { + if err != nil { + slog.Error("fatal", "error", err) + os.Exit(1) + } +} diff --git a/cmd/fleet-relay/main.go b/cmd/fleet-relay/main.go new file mode 100644 index 00000000..6c10b731 --- /dev/null +++ b/cmd/fleet-relay/main.go @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "flag" + "log/slog" + "net" + "os" + "strings" + + "go.datum.net/fleet/internal/relay" +) + +func main() { + addr := flag.String("listen", ":8443", "relay TCP listen address") + tokenFile := flag.String("gateway-token-file", "/var/run/secrets/fleet/relay-token", "gateway registration token file") + flag.Parse() + token, err := os.ReadFile(*tokenFile) + if err != nil { + slog.Error("read gateway token", "error", err) + os.Exit(1) + } + l, err := net.Listen("tcp", *addr) + if err != nil { + slog.Error("listen", "error", err) + os.Exit(1) + } + slog.Info("relay listening", "address", l.Addr().String()) + if err := relay.NewServer(strings.TrimSpace(string(token))).Serve(l); err != nil { + slog.Error("serve relay", "error", err) + os.Exit(1) + } +} diff --git a/cmd/fleet-session-fixture/main.go b/cmd/fleet-session-fixture/main.go new file mode 100644 index 00000000..e5ed0135 --- /dev/null +++ b/cmd/fleet-session-fixture/main.go @@ -0,0 +1,116 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "path/filepath" + "syscall" + "time" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/clientcmd" + "sigs.k8s.io/controller-runtime/pkg/client" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/simulator" + "go.datum.net/fleet/internal/staging/sessionfixture" +) + +func main() { + if err := run(os.Args[1:]); err != nil && !errors.Is(err, flag.ErrHelp) { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } +} + +func run(args []string) error { + // controller-runtime registers kubeconfig globally; keep this CLI isolated. + flags := flag.NewFlagSet("fleet-session-fixture", flag.ContinueOnError) + synthetic := flags.Bool("synthetic", false, "required acknowledgment: test-only admission, observations and cleanup; never use with real assets") + kubeconfig := flags.String("kubeconfig", "", "management kubeconfig") + phase := flags.String("phase", "allocate", "allocate or release") + namespace := flags.String("namespace", "default", "Machine namespace") + machine := flags.String("machine", "db-01", "Machine name") + uid := flags.String("machine-uid", "", "exact retained Machine UID, required for release") + capacityNamespace := flags.String("capacity-namespace", "fleet-provider", "MachineCapacity namespace") + capacity := flags.String("capacity", "", "MachineCapacity name, required for allocation") + principal := flags.String("principal", "", "exact authenticated username authorized by this synthetic fixture") + member := flags.String("member-cluster", "", "synthetic member route") + privateNamespace := flags.String("private-namespace", "fleet-system", "Coordinator and immutable synthetic grant Secret namespace") + state := flags.String("state", "", "persistent synthetic executor file; retain across all release retries and reuse") + if err := flags.Parse(args); err != nil { + return err + } + if !*synthetic || *kubeconfig == "" || *state == "" || (*phase != "allocate" && *phase != "release") { + return errors.New("--synthetic, --kubeconfig, --state and --phase=allocate|release are required") + } + if *phase == "allocate" && (*capacity == "" || *principal == "" || *member == "") { + return errors.New("allocation requires --capacity, --principal and --member-cluster") + } + if *phase == "release" && *uid == "" { + return errors.New("release requires --machine-uid (never inferred from a possibly recreated name)") + } + if err := os.MkdirAll(filepath.Dir(*state), 0700); err != nil { + return err + } + lock, err := os.OpenFile(*state+".lock", os.O_CREATE|os.O_RDWR, 0600) + if err != nil { + return err + } + defer lock.Close() + if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil { + return fmt.Errorf("synthetic executor is already in use: %w", err) + } + defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) + store, err := simulator.Open(*state) + if err != nil { + return err + } + scheme := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(scheme); err != nil { + return err + } + if err := fleetv1.AddToScheme(scheme); err != nil { + return err + } + config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) + if err != nil { + return err + } + kube, err := client.New(config, client.Options{Scheme: scheme}) + if err != nil { + return err + } + coordinator, err := controller.NewCoordinator(kube, *privateNamespace, sessionfixture.StoreExecutor{Store: store}, controller.LocalDigestImageResolver{}, nil, time.Minute) + if err != nil { + return err + } + fixture := sessionfixture.Fixture{Client: kube, Coordinator: coordinator, PrivateNamespace: *privateNamespace} + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + key := client.ObjectKey{Namespace: *namespace, Name: *machine} + var result any + if *phase == "allocate" { + asset, allocateErr := fixture.Allocate(ctx, key, client.ObjectKey{Namespace: *capacityNamespace, Name: *capacity}, *principal, *member) + err = allocateErr + if asset != nil { + result = struct { + MachineUID types.UID `json:"machineUID"` + Epoch int64 `json:"epoch"` + }{asset.ClaimUID, asset.Epoch} + } + } else { + result, err = fixture.Release(ctx, key, types.UID(*uid)) + } + if encodeErr := json.NewEncoder(os.Stdout).Encode(result); encodeErr != nil { + return encodeErr + } + return err +} diff --git a/cmd/fleet-session-fixture/main_test.go b/cmd/fleet-session-fixture/main_test.go new file mode 100644 index 00000000..bff136f9 --- /dev/null +++ b/cmd/fleet-session-fixture/main_test.go @@ -0,0 +1,24 @@ +package main + +import ( + "errors" + "flag" + "strings" + "testing" +) + +func TestFixtureFlagsAreIndependentOfGlobalKubeconfig(t *testing.T) { + // Imported controller-runtime already owns this global flag in the executable. + if flag.Lookup("kubeconfig") == nil { + t.Fatal("expected controller-runtime global kubeconfig flag") + } + for i := 0; i < 2; i++ { + err := run([]string{"--kubeconfig", "/synthetic/test-config"}) + if err == nil || !strings.Contains(err.Error(), "--synthetic") { + t.Fatalf("expected safety validation before accessing a cluster: %v", err) + } + } + if err := run([]string{"--help"}); !errors.Is(err, flag.ErrHelp) { + t.Fatalf("help: %v", err) + } +} diff --git a/config/README.md b/config/README.md index 3c36eb1c..8c5c8755 100644 --- a/config/README.md +++ b/config/README.md @@ -18,6 +18,17 @@ API servers and must be reconciled independently. | `config/overlays/management-plane` | Fleet management cluster | Fleet CRDs, the manager workload and RBAC, private-record namespaces, and admission fences | | `config/overlays/synthetic-staging` | Fleet management cluster (non-production only) | Management-plane resources plus an explicit synthetic allocator/provider integration | +The secure machine-management prototype additionally applies +`config/federation` to the Karmada API. It contains the projected-session status +interpreter and least-privilege hub RBAC; the generated projected-session CRD is +applied to the Karmada API separately. This component is not yet part of either +published production root because environment-owned Karmada identity and member +registration have not been selected. Its public session and private binding CRDs +use `metal.datumapis.com`; the projected-session CRD and hub RBAC use +`coordination.fleet.datumapis.com`. The prototype RBAC grants session creation +separately from Machine viewing. It adds no Milo service, session IAM registration, +or production release integration. See the [prototype integration gaps](../docs/implementation/machine-management-prototype.md#prototype-choices-and-remaining-production-gaps). + `config/standalone` remains a synthetic, same-cluster test environment. It must not be referenced by either production root. diff --git a/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml b/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml new file mode 100644 index 00000000..94ec057f --- /dev/null +++ b/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml @@ -0,0 +1,185 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: projectedmachinemanagementsessions.coordination.fleet.datumapis.com +spec: + group: coordination.fleet.datumapis.com + names: + kind: ProjectedMachineManagementSession + listKind: ProjectedMachineManagementSessionList + plural: projectedmachinemanagementsessions + singular: projectedmachinemanagementsession + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ProjectedMachineManagementSession is the least-privileged Karmada-delivered + location copy. Its generated name is the location session identity. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + accessProfile: + type: string + authorityFreshUntil: + format: date-time + type: string + clientPublicKey: + type: string + connectBefore: + format: date-time + type: string + desiredState: + enum: + - Active + - Revoked + type: string + expiresAt: + format: date-time + type: string + machineCapacityRef: + properties: + name: + type: string + required: + - name + type: object + protocol: + type: string + required: + - accessProfile + - authorityFreshUntil + - clientPublicKey + - connectBefore + - desiredState + - expiresAt + - machineCapacityRef + - protocol + type: object + x-kubernetes-validations: + - message: projected authority inputs are immutable + rule: self.machineCapacityRef == oldSelf.machineCapacityRef && self.protocol + == oldSelf.protocol && self.accessProfile == oldSelf.accessProfile + && self.clientPublicKey == oldSelf.clientPublicKey && self.connectBefore + == oldSelf.connectBefore && self.expiresAt == oldSelf.expiresAt + - message: revocation is terminal + rule: oldSelf.desiredState == 'Active' || self.desiredState == 'Revoked' + - message: authority freshness may only advance within expiry + rule: timestamp(self.authorityFreshUntil) >= timestamp(oldSelf.authorityFreshUntil) + && timestamp(self.authorityFreshUntil) <= timestamp(self.expiresAt) + status: + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + connectedAt: + format: date-time + type: string + connection: + description: SessionConnection contains non-secret rendezvous information + only. + properties: + gatewayAudience: + type: string + gatewayCertSHA256: + type: string + protocolVersion: + type: string + relayURL: + type: string + routeID: + type: string + required: + - gatewayAudience + - gatewayCertSHA256 + - protocolVersion + - relayURL + - routeID + type: object + endedAt: + format: date-time + type: string + teardownSpecDigest: + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/metal.datumapis.com_machinemanagementsessionbindings.yaml b/config/crd/bases/metal.datumapis.com_machinemanagementsessionbindings.yaml new file mode 100644 index 00000000..d202f840 --- /dev/null +++ b/config/crd/bases/metal.datumapis.com_machinemanagementsessionbindings.yaml @@ -0,0 +1,225 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: machinemanagementsessionbindings.metal.datumapis.com +spec: + group: metal.datumapis.com + names: + kind: MachineManagementSessionBinding + listKind: MachineManagementSessionBindingList + plural: machinemanagementsessionbindings + singular: machinemanagementsessionbinding + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + MachineManagementSessionBinding is protected admission evidence. Local UIDs + are retained only as same-API-server recreation preconditions and are never + projected through Karmada. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + accessProfile: + type: string + allocationName: + type: string + allocationUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + clientPublicKey: + type: string + connectBefore: + format: date-time + type: string + consumerProject: + type: string + deviceName: + type: string + expiresAt: + format: date-time + type: string + locationName: + type: string + machineCapacityName: + type: string + machineCapacityNamespace: + type: string + machineCapacityUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + machineName: + type: string + machineNamespace: + type: string + machineUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + memberCluster: + type: string + operationCorrelationID: + type: string + protocol: + type: string + providerProject: + type: string + requestingPrincipal: + type: string + sessionCorrelationID: + type: string + sessionName: + type: string + sessionNamespace: + type: string + sessionUID: + description: |- + UID is a type that holds unique ID values, including UUIDs. Because we + don't ONLY use UUIDs, this is an alias to string. Being a type captures + intent and helps make sure that UIDs and names do not get conflated. + type: string + required: + - accessProfile + - allocationName + - allocationUID + - clientPublicKey + - connectBefore + - consumerProject + - deviceName + - expiresAt + - locationName + - machineCapacityName + - machineCapacityNamespace + - machineCapacityUID + - machineName + - machineNamespace + - machineUID + - memberCluster + - operationCorrelationID + - protocol + - providerProject + - requestingPrincipal + - sessionCorrelationID + - sessionName + - sessionNamespace + - sessionUID + type: object + x-kubernetes-validations: + - message: admitted binding inputs are immutable + rule: self == oldSelf + status: + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + connection: + description: SessionConnection contains non-secret rendezvous information + only. + properties: + gatewayAudience: + type: string + gatewayCertSHA256: + type: string + protocolVersion: + type: string + relayURL: + type: string + routeID: + type: string + required: + - gatewayAudience + - gatewayCertSHA256 + - protocolVersion + - relayURL + - routeID + type: object + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/metal.datumapis.com_machinemanagementsessions.yaml b/config/crd/bases/metal.datumapis.com_machinemanagementsessions.yaml new file mode 100644 index 00000000..51a8ebaf --- /dev/null +++ b/config/crd/bases/metal.datumapis.com_machinemanagementsessions.yaml @@ -0,0 +1,168 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: machinemanagementsessions.metal.datumapis.com +spec: + group: metal.datumapis.com + names: + kind: MachineManagementSession + listKind: MachineManagementSessionList + plural: machinemanagementsessions + singular: machinemanagementsession + scope: Namespaced + versions: + - name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + MachineManagementSession is a short-lived public request for the Machine's + current allocation. Provider and location details never enter this object. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + properties: + accessProfile: + enum: + - Provisioning + type: string + clientPublicKey: + pattern: ^[0-9a-f]{64}$ + type: string + machineRef: + properties: + name: + type: string + required: + - name + type: object + protocol: + enum: + - Redfish + type: string + ttl: + type: string + x-kubernetes-validations: + - message: ttl must be between 1m and 15m + rule: duration(self) >= duration('1m') && duration(self) <= duration('15m') + required: + - accessProfile + - clientPublicKey + - machineRef + - protocol + - ttl + type: object + x-kubernetes-validations: + - message: spec is immutable + rule: self == oldSelf + status: + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + connectBefore: + format: date-time + type: string + connection: + description: SessionConnection contains non-secret rendezvous information + only. + properties: + gatewayAudience: + type: string + gatewayCertSHA256: + type: string + protocolVersion: + type: string + relayURL: + type: string + routeID: + type: string + required: + - gatewayAudience + - gatewayCertSHA256 + - protocolVersion + - relayURL + - routeID + type: object + expiresAt: + format: date-time + type: string + type: object + required: + - spec + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml new file mode 100644 index 00000000..86e318cf --- /dev/null +++ b/config/crd/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - bases/metal.datumapis.com_machinemanagementsessions.yaml + - bases/metal.datumapis.com_machinemanagementsessionbindings.yaml + - bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml diff --git a/config/federation/interpreter.yaml b/config/federation/interpreter.yaml new file mode 100644 index 00000000..1b70cb17 --- /dev/null +++ b/config/federation/interpreter.yaml @@ -0,0 +1,68 @@ +# The gateway writes status only on its cell-local copy. Karmada reflects all +# member statuses and this interpreter accepts only the member identity pinned +# into the protected allocation binding and hub-copy label. A claimed route can +# only be replaced by status for the same route. +apiVersion: config.karmada.io/v1alpha1 +kind: ResourceInterpreterCustomization +metadata: + name: fleet-projected-machine-management-session +spec: + target: + apiVersion: coordination.fleet.datumapis.com/v1alpha1 + kind: ProjectedMachineManagementSession + customizations: + statusReflection: + luaScript: | + function ReflectStatus(observedObj) + if observedObj.status == nil then + return nil + end + return observedObj.status + end + statusAggregation: + luaScript: | + local function weight(status) + if status == nil then return 0 end + if status.conditions ~= nil then + for i = 1, #status.conditions do + if status.conditions[i].type == "CleanupConfirmed" and status.conditions[i].status == "True" then + return 4 + end + end + end + if status.connection ~= nil then return 3 end + if status.conditions == nil then return 0 end + for i = 1, #status.conditions do + if status.conditions[i].type == "Ready" and status.conditions[i].status == "False" then + return 2 + end + end + if #status.conditions > 0 then return 1 end + return 0 + end + + function AggregateStatus(desiredObj, statusItems) + if statusItems == nil or desiredObj.metadata == nil or desiredObj.metadata.labels == nil then + return desiredObj + end + local member = desiredObj.metadata.labels["fleet.datumapis.com/member-cluster"] + if member == nil or member == "" then return desiredObj end + local claimed = nil + if desiredObj.status ~= nil and desiredObj.status.connection ~= nil then + claimed = desiredObj.status.connection.routeID + end + local best = nil + local bestWeight = 0 + for i = 1, #statusItems do + local item = statusItems[i] + local status = item.status + local sameClaim = claimed == nil or status == nil or status.connection == nil or status.connection.routeID == claimed + if item.clusterName == member and sameClaim and weight(status) > bestWeight then + best = status + bestWeight = weight(status) + end + end + if best == nil or bestWeight < weight(desiredObj.status) then return desiredObj end + desiredObj.status = best + return desiredObj + end diff --git a/config/federation/kustomization.yaml b/config/federation/kustomization.yaml new file mode 100644 index 00000000..01954f61 --- /dev/null +++ b/config/federation/kustomization.yaml @@ -0,0 +1,5 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - interpreter.yaml + - rbac.yaml diff --git a/config/federation/rbac.yaml b/config/federation/rbac.yaml new file mode 100644 index 00000000..b1bf1067 --- /dev/null +++ b/config/federation/rbac.yaml @@ -0,0 +1,27 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-federation-projector +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [projectedmachinemanagementsessions] + verbs: [get, list, watch, create, update, patch, delete] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [projectedmachinemanagementsessions/status] + verbs: [get] + - apiGroups: [policy.karmada.io] + resources: [propagationpolicies] + verbs: [get, list, watch, create, update, patch, delete] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: fleet-federation-projector +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: fleet-federation-projector +subjects: + - kind: ServiceAccount + name: fleet-controller + namespace: fleet-system diff --git a/config/location/access.yaml b/config/location/access.yaml new file mode 100644 index 00000000..8a49d790 --- /dev/null +++ b/config/location/access.yaml @@ -0,0 +1,105 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-relay + namespace: machine-access-system +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-relay} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-relay} + spec: + automountServiceAccountToken: false + securityContext: {seccompProfile: {type: RuntimeDefault}, runAsNonRoot: true, fsGroup: 65532, fsGroupChangePolicy: OnRootMismatch} + containers: + - name: relay + image: fleet-relay:e2e + imagePullPolicy: IfNotPresent + args: ["--listen=:8443", "--gateway-token-file=/var/run/secrets/fleet/relay-token"] + ports: [{name: relay, containerPort: 8443}] + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65532 + resources: + requests: {cpu: 10m, memory: 32Mi} + limits: {memory: 128Mi} + volumeMounts: [{name: relay-token, mountPath: /var/run/secrets/fleet, readOnly: true}] + volumes: [{name: relay-token, secret: {secretName: fleet-relay-token, defaultMode: 0440}}] +--- +apiVersion: v1 +kind: Service +metadata: + name: fleet-relay + namespace: machine-access-system +spec: + type: NodePort + selector: {app.kubernetes.io/name: fleet-relay} + ports: [{name: relay, port: 8443, targetPort: relay, nodePort: 30443}] +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-gateway + namespace: machine-access-system +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-gateway} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-gateway} + spec: + serviceAccountName: fleet-gateway + securityContext: {seccompProfile: {type: RuntimeDefault}, runAsNonRoot: true, fsGroup: 65532, fsGroupChangePolicy: OnRootMismatch} + containers: + - name: gateway + image: fleet-gateway:e2e + imagePullPolicy: IfNotPresent + args: + - --relay-address=fleet-relay.machine-access-system.svc:8443 + - --relay-public-url=tcp://127.0.0.1:30443 + - --relay-token-file=/var/run/secrets/fleet/relay-token + - --audience=fleet-gateway/location-prototype/r1 + - --supported-adapter=sushy-libvirt-v1 + - --enrollment-namespace=machine-access-system + - --journal-dir=/var/lib/fleet + ports: [{name: metrics, containerPort: 8080}, {name: health, containerPort: 8081}] + livenessProbe: {httpGet: {path: /healthz, port: health}} + readinessProbe: {httpGet: {path: /readyz, port: health}} + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65532 + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: credentials, mountPath: /var/run/secrets/fleet, readOnly: true} + - {name: journal, mountPath: /var/lib/fleet} + - {name: tmp, mountPath: /tmp} + volumes: + - name: credentials + projected: + defaultMode: 0440 + sources: + - secret: {name: fleet-relay-token} + - name: journal + persistentVolumeClaim: {claimName: fleet-gateway-journal} + - name: tmp + emptyDir: {} +--- +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: fleet-gateway-journal + namespace: machine-access-system +spec: + accessModes: [ReadWriteOnce] + resources: {requests: {storage: 256Mi}} diff --git a/config/location/kustomization.yaml b/config/location/kustomization.yaml new file mode 100644 index 00000000..6a8df324 --- /dev/null +++ b/config/location/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../machine-management/base + - access.yaml + - networkpolicy.yaml diff --git a/config/location/networkpolicy.yaml b/config/location/networkpolicy.yaml new file mode 100644 index 00000000..af95f126 --- /dev/null +++ b/config/location/networkpolicy.yaml @@ -0,0 +1,43 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: default-deny + namespace: machine-access-system +spec: + podSelector: {} + policyTypes: [Ingress, Egress] +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: relay + namespace: machine-access-system +spec: + podSelector: {matchLabels: {app.kubernetes.io/name: fleet-relay}} + policyTypes: [Ingress, Egress] + ingress: + - ports: [{protocol: TCP, port: 8443}] + egress: [] +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: gateway + namespace: machine-access-system +spec: + podSelector: {matchLabels: {app.kubernetes.io/name: fleet-gateway}} + policyTypes: [Ingress, Egress] + ingress: [] + egress: + - to: [{podSelector: {matchLabels: {app.kubernetes.io/name: fleet-relay}}}] + ports: [{protocol: TCP, port: 8443}] + - to: [{ipBlock: {cidr: 172.30.0.10/32}}] + ports: [{protocol: TCP, port: 8000}] + - to: [{ipBlock: {cidr: 10.88.0.1/32}}] + ports: [{protocol: TCP, port: 8000}] + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}} + podSelector: {matchLabels: {k8s-app: kube-dns}} + ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}] + - to: [{ipBlock: {cidr: 10.96.0.1/32}}] + ports: [{protocol: TCP, port: 443}] diff --git a/config/machine-management/base/kustomization.yaml b/config/machine-management/base/kustomization.yaml new file mode 100644 index 00000000..a1eee58b --- /dev/null +++ b/config/machine-management/base/kustomization.yaml @@ -0,0 +1,4 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - namespaces.yaml diff --git a/config/machine-management/base/namespaces.yaml b/config/machine-management/base/namespaces.yaml new file mode 100644 index 00000000..45453bda --- /dev/null +++ b/config/machine-management/base/namespaces.yaml @@ -0,0 +1,19 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: fleet-system + annotations: + fleet.datumapis.com/shared-with-standalone: "true" + labels: + pod-security.kubernetes.io/enforce: restricted + pod-security.kubernetes.io/audit: restricted + pod-security.kubernetes.io/warn: restricted +--- +apiVersion: v1 +kind: Namespace +metadata: + name: machine-access-system + labels: + pod-security.kubernetes.io/enforce: restricted + pod-security.kubernetes.io/audit: restricted + pod-security.kubernetes.io/warn: restricted diff --git a/config/manager/controller.yaml b/config/manager/controller.yaml new file mode 100644 index 00000000..9ddd431b --- /dev/null +++ b/config/manager/controller.yaml @@ -0,0 +1,90 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fleet-controller + namespace: fleet-system +spec: + replicas: 1 + selector: + matchLabels: {app.kubernetes.io/name: fleet-controller} + template: + metadata: + labels: {app.kubernetes.io/name: fleet-controller} + spec: + serviceAccountName: fleet-controller + securityContext: + seccompProfile: {type: RuntimeDefault} + runAsNonRoot: true + fsGroup: 65532 + fsGroupChangePolicy: OnRootMismatch + containers: + - name: controller + image: fleet-controller:e2e + imagePullPolicy: IfNotPresent + args: + - --lifecycle-mode=synthetic + - --private-namespace=fleet-system + - --federation-kubeconfig=/var/run/fleet-federation/kubeconfig + - --webhook-cert-dir=/var/run/fleet-webhook + # Test-only short window; the binary's product-oriented default is 2m. + - --authority-freshness=15s + # Lower than the product-oriented default so E2E can prove the limit. + - --per-project-session-limit=2 + ports: + - {name: webhook, containerPort: 9443} + - {name: metrics, containerPort: 8080} + - {name: health, containerPort: 8081} + livenessProbe: {httpGet: {path: /healthz, port: health}} + readinessProbe: {httpGet: {path: /readyz, port: health}} + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + readOnlyRootFilesystem: true + runAsNonRoot: true + runAsUser: 65532 + resources: + requests: {cpu: 25m, memory: 64Mi} + limits: {memory: 256Mi} + volumeMounts: + - {name: federation, mountPath: /var/run/fleet-federation, readOnly: true} + - {name: webhook, mountPath: /var/run/fleet-webhook, readOnly: true} + - {name: tmp, mountPath: /tmp} + volumes: + - name: federation + secret: {secretName: fleet-federation-kubeconfig, defaultMode: 0440} + - name: webhook + secret: {secretName: fleet-webhook-tls, defaultMode: 0440} + - name: tmp + emptyDir: {} +--- +apiVersion: v1 +kind: Service +metadata: + name: fleet-webhook + namespace: fleet-system +spec: + selector: {app.kubernetes.io/name: fleet-controller} + ports: + - {name: https, port: 443, targetPort: webhook} +--- +apiVersion: admissionregistration.k8s.io/v1 +kind: MutatingWebhookConfiguration +metadata: + name: fleet-machine-management-session +webhooks: + - name: mmssessions.metal.datumapis.com + admissionReviewVersions: [v1] + sideEffects: None + failurePolicy: Fail + matchPolicy: Equivalent + clientConfig: + service: + namespace: fleet-system + name: fleet-webhook + path: /mutate-metal-datumapis-com-v1alpha1-machinemanagementsession + rules: + - apiGroups: [metal.datumapis.com] + apiVersions: [v1alpha1] + operations: [CREATE, UPDATE] + resources: [machinemanagementsessions] + scope: Namespaced diff --git a/config/manager/kustomization.yaml b/config/manager/kustomization.yaml new file mode 100644 index 00000000..d67a61fa --- /dev/null +++ b/config/manager/kustomization.yaml @@ -0,0 +1,6 @@ +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: + - ../machine-management/base + - controller.yaml + - networkpolicy.yaml diff --git a/config/manager/networkpolicy.yaml b/config/manager/networkpolicy.yaml new file mode 100644 index 00000000..b1747cc1 --- /dev/null +++ b/config/manager/networkpolicy.yaml @@ -0,0 +1,23 @@ +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: fleet-controller + namespace: fleet-system +spec: + podSelector: {matchLabels: {app.kubernetes.io/name: fleet-controller}} + policyTypes: [Ingress, Egress] + ingress: + - from: [{ipBlock: {cidr: 172.16.0.0/12}}] + ports: [{protocol: TCP, port: 9443}] + egress: + - to: [{ipBlock: {cidr: 10.96.0.1/32}}] + ports: [{protocol: TCP, port: 443}] + - to: [{ipBlock: {cidr: 172.16.0.0/12}}] + ports: [{protocol: TCP, port: 6443}] + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: karmada-system}} + ports: [{protocol: TCP, port: 5443}] + - to: + - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}} + podSelector: {matchLabels: {k8s-app: kube-dns}} + ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}] diff --git a/config/rbac/controller.yaml b/config/rbac/controller.yaml new file mode 100644 index 00000000..f8783b27 --- /dev/null +++ b/config/rbac/controller.yaml @@ -0,0 +1,129 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-controller + namespace: fleet-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-session-controller +rules: + - apiGroups: [metal.datumapis.com] + resources: [machinemanagementsessions, machines, machinecapacities] + verbs: [get, list, watch] + # The controller writes only metadata finalizers on the public object. CEL + # validation keeps the customer-authored spec immutable. + - apiGroups: [metal.datumapis.com] + resources: [machinemanagementsessions] + verbs: [update, patch] + - apiGroups: [metal.datumapis.com] + resources: [machinemanagementsessions/status] + verbs: [get, update, patch] + - apiGroups: [""] + resources: [namespaces] + verbs: [get] + - apiGroups: [metal.datumapis.com] + resources: [machinemanagementsessions/finalizers] + verbs: [update, patch] + - apiGroups: [metal.datumapis.com] + resources: [machinemanagementsessionbindings] + verbs: [get, list, watch, create, update, patch] + - apiGroups: [metal.datumapis.com] + resources: [machinemanagementsessionbindings/status] + verbs: [get, update, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-session-custody + namespace: fleet-system +rules: + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, update] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-session-custody + namespace: fleet-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-session-custody +subjects: + - kind: ServiceAccount + name: fleet-controller + namespace: fleet-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: fleet-session-controller +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: fleet-session-controller +subjects: + - kind: ServiceAccount + name: fleet-controller + namespace: fleet-system +--- +# Machine read and management-session creation are deliberately separate grants. +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-machine-viewer +rules: + - apiGroups: [metal.datumapis.com] + resources: [machines] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: fleet-machine-management-session-creator +rules: + - apiGroups: [metal.datumapis.com] + resources: [machinemanagementsessions] + verbs: [create, get, list, watch, delete] +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: fleet-gateway + namespace: machine-access-system +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: fleet-gateway + namespace: machine-access-system +rules: + - apiGroups: [coordination.fleet.datumapis.com] + resources: [projectedmachinemanagementsessions] + verbs: [get, list, watch] + - apiGroups: [coordination.fleet.datumapis.com] + resources: [projectedmachinemanagementsessions/status] + verbs: [get, update, patch] + - apiGroups: [metal.datumapis.com] + resources: [machinecapacities] + verbs: [get, list, watch] + - apiGroups: [""] + resources: [secrets] + verbs: [get, list, watch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: fleet-gateway + namespace: machine-access-system +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: fleet-gateway +subjects: + - kind: ServiceAccount + name: fleet-gateway + namespace: machine-access-system diff --git a/config/redfish/FleetProvisioning.v1_0_0.json b/config/redfish/FleetProvisioning.v1_0_0.json new file mode 100644 index 00000000..6b61a1e5 --- /dev/null +++ b/config/redfish/FleetProvisioning.v1_0_0.json @@ -0,0 +1,50 @@ +{ + "SchemaDefinition": "RedfishInteroperabilityProfile.v1_9_0", + "ProfileName": "FleetProvisioning", + "ProfileVersion": "1.0.0", + "OwningEntity": "Datum Technology, Inc.", + "Purpose": "Allocation-scoped virtual Redfish for one-time PXE or local-disk boot and bounded power operations.", + "License": "Apache-2.0", + "Protocol": { + "MinVersion": "1.18.0" + }, + "Resources": { + "ServiceRoot": { + "MinVersion": "1.15.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/"], + "PropertyRequirements": { + "RedfishVersion": {"ReadRequirement": "Mandatory"}, + "Systems": {"ReadRequirement": "Mandatory"}, + "SessionService": {"ReadRequirement": "Mandatory"}, + "Tasks": {"ReadRequirement": "Mandatory"}, + "Links": {"ReadRequirement": "Mandatory", "PropertyRequirements": { + "Sessions": {"ReadRequirement": "Mandatory"} + }} + } + }, + "ComputerSystem": { + "MinVersion": "1.20.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/Systems/{ComputerSystemId}"], + "PropertyRequirements": { + "PowerState": {"ReadRequirement": "Mandatory"}, + "Boot": {"ReadRequirement": "Mandatory"}, + "Actions": {"ReadRequirement": "Mandatory"} + }, + "ActionRequirements": { + "Reset": {"ReadRequirement": "Mandatory"} + } + }, + "SessionService": { + "MinVersion": "1.2.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/SessionService"] + }, + "TaskService": { + "MinVersion": "1.2.0", + "ReadRequirement": "Mandatory", + "URIs": ["/redfish/v1/TaskService"] + } + } +} diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 510c6d48..a07d3e79 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -57,9 +57,9 @@ processes or service-catalog entries. | Group | Resources and responsibility | Status | | --- | --- | --- | -| `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six alpha CRDs at `v1alpha1`. Production admission and real providers remain incomplete. | +| `metal.datumapis.com` | `MachineClass`: offerings and consumer references. `MachineProfile`: hardware requirements. `MachineCapacity`: provider supply. `Machine`: customer allocation and runtime intent. `MachineAllocation`: protected allocation identity. `Installation`: immutable OS installation or reinstall request. | Six lifecycle alpha CRDs at `v1alpha1`, plus separately packaged prototype `MachineManagementSession` and protected `MachineManagementSessionBinding` CRDs. Production admission and real providers remain incomplete. | | `fleet.datumapis.com` | Physical inventory: `Facility`, `Rack`, `DeviceClaim`, `Device`, `Cable`, and `PowerFeed`. Physical preparation and provider execution remain operator responsibilities. | Proposed inventory APIs; no physical inventory CRDs or real provider executor are implemented here. | -| `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | Architecture decision only on the current main implementation: no coordination CRD or cell controller is packaged. Replaces the earlier prototype name `internal.fleet.datumapis.com`. | +| `coordination.fleet.datumapis.com` | Intended management-to-location execution handoff, retaining exact allocation identity, location, admitted inputs, release intent, and execution evidence. `MachineAllocationHandoff` is a candidate resource. | The separate BMC prototype implements `ProjectedMachineManagementSession` with a Karmada projector and location gateway. Allocation handoff remains proposed. Replaces `internal.fleet.datumapis.com`. | MachineCapacity and MachineAllocation belong to the Metal allocation contract but remain provider- or service-owned. Membership in the customer service's API @@ -105,8 +105,10 @@ Networking/IPAM and Galactic retain authority over attachments, addresses, switch configuration, and routing. A coordination reference is neither a customer source-use grant nor independent provider execution authority. -Current main implements location resolution and event routing, not this complete -federation topology. Standalone namespaces are project stand-ins; synthetic +The lifecycle manager implements location resolution and event routing, not this complete +federation topology. The separately packaged BMC prototype exercises session +federation with pre-bound synthetic allocations; it is not wired to lifecycle +admission or release custody. Standalone namespaces are project stand-ins; synthetic staging is a test mode. Neither establishes production federation or hardware readiness. See the [implementation status](../development/README.md). diff --git a/docs/architecture/design.md b/docs/architecture/design.md index 125d7209..3ff2e54b 100644 --- a/docs/architecture/design.md +++ b/docs/architecture/design.md @@ -5,6 +5,12 @@ Reviewed on 2026-10-27. This is a synthesis for implementation planning, not a replacement for the source proposals or a claim that their APIs exist. +The [secure machine-management prototype](implementation/machine-management-prototype.md) +is a separate implementation alongside the [lifecycle library](implementation.md). +It intentionally uses synthetic, +pre-bound allocation input and does not turn the proposal's illustrative APIs +into accepted product contracts. + ## Source proposals | Source | Reviewed revision | Contribution | @@ -32,7 +38,8 @@ and coordinated changes above that shared service. ## Subsystem boundaries -All names below describe proposed resources, not implemented schemas. +The table summarizes subsystem contracts; the [API architecture](architecture.md) +distinguishes implemented lifecycle/session schemas from proposed resources. | Subsystem | Responsibilities and principal resources | | --- | --- | @@ -157,7 +164,9 @@ inventory remains finite and reports `InsufficientCapacity` when exhausted. - **Repository ownership:** The service proposal and implementation will live in `datum-cloud/fleet`; environment-specific rollout configuration remains in `datum-cloud/infra`. Imported implementation references are updated accordingly. - Module path, license, and any future provider repository split remain open. + The prototype selects `go.datum.net/fleet` to match Datum Go conventions without + asserting stable API imports. License policy and any future provider repository + split remain open. The [review of #7705][node-review] requested clarity on readiness, regional rollout, fencing, and procurement policy. Its latest text addresses those points with the diff --git a/docs/development/README.md b/docs/development/README.md index f8bd6ab9..1d529297 100644 --- a/docs/development/README.md +++ b/docs/development/README.md @@ -22,6 +22,11 @@ admission, replayable Milo event adapters, and real providers are not implemente Production Kustomize roots now package the implemented manager, admission, API, Milo IAM, service, and quota boundaries; packaging is not runtime readiness. +The separately packaged [BMC access prototype](implementation/machine-management-prototype.md) +adds Metal management sessions and coordination-group location projections. +It still uses pre-bound synthetic allocation records and is not integrated with +the lifecycle library's admission, execution serialization, or release barrier. + ## API group naming The allocation APIs now use `metal.datumapis.com/v1alpha1`. Milo registers the diff --git a/docs/development/roadmap.md b/docs/development/roadmap.md index c3d7282b..d8a020f6 100644 --- a/docs/development/roadmap.md +++ b/docs/development/roadmap.md @@ -3,9 +3,16 @@ [Documentation overview](../README.md) · [Architecture guide](../architecture/README.md) This proposed sequence follows the [reviewed Fleet designs](../architecture/design.md). Milestones -are unimplemented. Owned-metal qualification and rented/managed adoption can +remain proposed. Owned-metal qualification and rented/managed adoption can progress independently while sharing allocation and installation contracts. +An implemented [machine-management vertical slice](../implementation/machine-management-prototype.md) +now supplies evidence for a subset of milestones 1 and 3: immutable session +admission, retained allocation identity, location projection, bounded Redfish, +durable operation admission, revocation, and a real virtual-BMC path. It does +not implement allocator commits, installation, cleanup qualification, or a +production relay and therefore does not complete either milestone. + ## 1. Define the service contracts The [Machine lifecycle enhancement](../enhancements/machine-lifecycle/README.md) defines the five diff --git a/docs/enhancements/secure-bmc-access.md b/docs/enhancements/secure-bmc-access.md new file mode 100644 index 00000000..cb7c5871 --- /dev/null +++ b/docs/enhancements/secure-bmc-access.md @@ -0,0 +1,780 @@ +--- +status: provisional +stage: alpha +latest-milestone: "unplanned" +--- + +# Secure customer BMC access + +This enhancement proposes allocation-scoped customer access to a narrow Redfish +API without exposing a BMC, its management network, or its credentials directly. +It extends the provisional [Fleet design context](../design.md) and the pinned +[bare-metal provisioning proposal][fleet-provisioning]. No API or behavior in +this document is an accepted production contract. The repository contains a +[working prototype](../implementation/machine-management-prototype.md) aligned +with the Machine, MachineAllocation and MachineCapacity identity model below. +Its synthetic allocation, location registration and enrollment records remain +prototype fixtures and must not be treated as accepted product APIs. + +The architecture borrows the session and data-path separation used by Datum +Compute's provisional [instance shell sessions][compute-shell]: the platform +authenticates and authorizes a short-lived session, binds it to an authoritative +placement, and then keeps the central control plane out of the request data path. +The transport and resource names below remain design proposals; adopting this +pattern does not require Fleet to reuse Compute resources or deployment +components. + +The [current API architecture](../architecture.md) supersedes the pinned source's +resource names: public sessions and private central bindings use +`metal.datumapis.com`; location projections use `coordination.fleet.datumapis.com`. +The implementation calls the location resource `ProjectedMachineManagementSession` +and its freshness field `authorityFreshUntil`; the illustrative shape below uses +`LocationMachineManagementSession` and `freshUntil`. Neither creates another +customer service registration. Physical inventory remains `fleet.datumapis.com`. + +## Summary + +Customers with an active consumer `Machine` can request a short-lived management +session. Datum authenticates the caller with the normal platform identity, +authorizes the requested capability against the Machine's current immutable +allocation, and resolves it to one provider `MachineCapacity` and location. +Kubernetes UIDs remain private admission evidence in the API server that issued +them; binding identifiers, binding epochs and cross-cluster UIDs are not part of +the session contract. + +After admission, Redfish traffic travels through an encrypted relay path to a +location-local Redfish gateway. The gateway exposes a small, provider-neutral +Redfish profile, resolves the private BMC target for the retained allocation, +and reaches the BMC through the location's management network. For the initial +Supermicro integration, that network is expected to be reachable through an +operator-managed OpenVPN connection. Customers do not receive VPN access, a BMC +address, or BMC credentials. + +The central API handles session admission, allocation resolution, status, audit +and revocation. It does not proxy each Redfish request. Relay capacity and +location gateways +scale independently, and a location can continue serving already admitted, +still-valid sessions during a bounded control-plane interruption. + +## Motivation + +Some customers already operate bare-metal provisioning systems and need to keep +using them while Fleet's installation and cluster automation is developed. PXE +boot, power control and machine inspection are enough to integrate many of these +systems, but direct BMC or management-VPN access would expose a large and +vendor-specific administrative surface. + +A central Redfish reverse proxy would hide BMC credentials, but it would also +place every hardware request and response on a global service. That creates an +unnecessary availability, latency and scaling dependency and requires the global +service to maintain routes into every management network. + +Fleet instead needs an access contract that: + +- reuses the existing customer Machine allocation authority; +- preserves a standard Redfish API for customer provisioning software; +- keeps BMC endpoints, credentials and management networks private; +- routes once when a session is admitted instead of globally routing every + Redfish request; +- fences stale sessions when a machine is released or reassigned; and +- retains exact authority and inputs before power or boot effects. + +## Goals + +- Let an authorized human or service identity operate its active customer + `Machine` through a documented Redfish interoperability + profile. +- Support customer-controlled PXE provisioning through one-time boot selection + and bounded power actions before full Fleet installation automation exists. +- Use Datum identity and IAM for session admission without requiring customer + accounts to be created on each BMC. +- Keep the central Fleet API out of the Redfish data path. +- Keep location management connections outbound-only where the selected relay + transport permits it. +- Prevent a session, delayed request or recovered worker from affecting a later + allocation of the same machine. +- Record mutating operation authority before effects and report uncertain + outcomes as unknown. +- Provide the same public contract across qualified BMC vendors while allowing + vendor-specific adapters behind the location gateway. + +## Non-goals + +- General BMC administration or unrestricted pass-through to a vendor API. +- Customer access to the BMC web UI, SSH service, IPMI, management VPN, OEM + endpoints, account management, firmware update or BMC network configuration. +- Selecting a final relay implementation, state store, API group version, + provisioning engine or Supermicro model matrix. +- Replacing brokered serial or graphical console access. Console remains a + separately authorized capability with its own transport and recording policy. +- Making Redfish the internal contract for every Fleet hardware provider. +- Treating BMC command acceptance as proof that a requested hardware state was + reached. + +## Consumer experience + +### Prerequisites + +The consumer has: + +- an active `Machine` allocated through Fleet's allocator; +- an IAM grant that permits creation of management sessions for that Machine; +- a machine offering that advertises the requested Redfish access profile; and +- a supported client connector, supplied as a CLI command, sidecar or SDK + component. + +The caller supplies only the customer Machine name. It never supplies the +provider `MachineCapacity`, `Device`, BMC address, location route or provider +credential. Fleet resolves those from protected allocation state. + +### Manual access + +The first supported connector is the first-party `datumctl-fleet` plugin and is +dispatched through the real `datumctl` executable: + +```console +$ datumctl fleet machine-management proxy db-01 +Session db-01-k7m2p is ready until 2026-11-11T19:15:00Z +Redfish endpoint: https://127.0.0.1:9443/redfish/v1 +``` + +The connector creates an ephemeral key pair in memory, creates a management +session containing the public key, waits for the location endpoint, and opens an +encrypted tunnel. It exposes a loopback Redfish endpoint for ordinary Redfish +tools. Closing the connector deletes or closes the session and clears the private +key. + +The loopback TLS and Redfish login-session behavior must be qualified with the +initial client tools. The connector may issue a one-time local login credential +and a per-session CA bundle, then implement Redfish `SessionService` locally and +return an `X-Auth-Token`. Those credentials authorize only the local connector; +they are never forwarded to or created on the BMC. The connector must not write +the transport private key or a reusable BMC credential to disk by default. + +### Customer provisioning automation + +An automated provisioner uses a Datum service identity to create a session for a +Machine in its project. A connector sidecar owns the ephemeral transport +key and presents the provisioner with the same Redfish base URL for the session's +lifetime. The provisioner can then: + +1. read the Redfish service root and computer-system state; +2. set a one-time PXE boot override; +3. request a supported reset or power transition; +4. follow a returned Redfish task when the operation is asynchronous; and +5. return boot selection to local disk if its workflow requires it. + +The customer continues to own its PXE, DHCP, image and installation workflow. +This enhancement supplies only the admitted hardware-management operations. +Networking and IPAM remain responsible for customer and provisioning network +attachments. + +### Compatibility boundary + +The HTTP resources and payloads exposed after connection follow Redfish. Session +admission, location rendezvous and the encrypted relay are Datum-specific. A +generic Redfish tool therefore works through the connector, not by connecting +directly to a BMC or to a global Fleet proxy. + +If requiring a connector proves incompatible with important customer tooling, a +future deployment may expose the same gateway through regional HTTPS ingress and +short-lived scoped credentials. That is a transport alternative, not a reason to +change the allocation, authorization, operation or Redfish contracts. + +### Control-plane ownership + +| State | Authoritative control plane | +| --- | --- | +| Customer `Machine` and `MachineManagementSession` | Customer Milo project API | +| Provider `Device` and `MachineCapacity` | Provider Milo project API | +| Immutable `MachineAllocation` and private admission evidence | Fleet management GKE cluster | +| Karmada policy and hub copies | Karmada control plane in the Fleet management cluster | +| Safe `Device`, `MachineCapacity` and session copies | Selected location member cluster | +| Owned-hardware enrollment, operation journal and materialized Secrets | Selected location member cluster | +| Authoritative BMC credential and trust material | Regional environment secret manager | + +Milo supplies project identity, IAM, service enablement and quota. The Fleet +management GKE cluster runs the trusted controllers and Karmada hub; it is not a +customer Kubernetes API and has no BMC-network route. A location cluster has no +consumer-project credential and cannot make or change the global allocation +decision. + +## Proposed Redfish profile + +The gateway presents a virtual Redfish service rather than forwarding the BMC's +entire resource tree. Resource identifiers are stable within the session and do +not reveal private device identifiers. The initial profile is intentionally +small: + +| Method and resource | Initial behavior | +| --- | --- | +| `GET /redfish/v1/` | Service discovery for the exposed profile. | +| `GET /redfish/v1/SessionService` and its session collection | Redfish login-session discovery. | +| `POST /redfish/v1/SessionService/Sessions` and `DELETE` of the resulting member | A session local to the connector or virtual gateway; no account or session is created on the BMC. | +| `GET /redfish/v1/Systems` | A collection containing the one allocated system. | +| `GET /redfish/v1/Systems/{id}` | Permitted system, power and boot observations. | +| `PATCH /redfish/v1/Systems/{id}` | One-time boot override for qualified targets such as PXE or local disk. Other fields are rejected. | +| `POST /redfish/v1/Systems/{id}/Actions/ComputerSystem.Reset` | Qualified reset and power actions. Unsupported `ResetType` values are rejected rather than substituted. | +| `GET /redfish/v1/TaskService` and task members | Progress and outcome for asynchronous gateway operations. | + +The gateway does not expose `AccountService`, `Managers`, `UpdateService`, BMC +network configuration, virtual media, log deletion, OEM actions, arbitrary +`Actions` targets or links outside the allowlisted virtual resource tree. Later +profiles require explicit review, capability publication and authorization. + +The initial `Provisioning` profile accepts one-time `Pxe` and `Hdd` boot targets. +It accepts `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart` and +`ForceRestart` reset types only after the owned-hardware adapter qualifies the +corresponding BMC behavior. An unsupported target or reset type returns a +Redfish extended error; the gateway never substitutes a more disruptive action. + +Redfish supports HTTP Basic, Redfish login sessions, and optional delegated +OAuth 2.0 bearer authentication. This proposal does not depend on the physical +BMC implementing Datum OAuth. Platform identity authorizes creation of the Fleet +session; possession of its ephemeral private key authorizes the location data +path; the gateway authenticates to the BMC with operator-held credentials. + +## Architecture + +### Request and data paths + +```text + control and status path + client ── OAuth ──> Fleet project API ──> session admission + │ │ + │ Fleet management GKE v + │ Karmada hub ──> exact location member + │ │ + │ encrypted Redfish data path v + └─────────> Datum relay ──────────────> location Redfish gateway + │ + │ owned-hardware adapter + v + private management network + │ + v + BMC +``` + +Karmada is the selected control-plane delivery mechanism. Fleet creates a +minimal location representation of the admitted session in the Karmada hub and +an exact-member propagation policy selected from protected Location +configuration. Karmada delivers the session and revocations without giving the +location credentials to the consumer project API. A Fleet resource interpreter +accepts status only from the selected member. The member cannot choose itself, +change centrally owned session input or redirect the session through status. +Karmada `Work`, `ResourceBinding` and propagation resources are federation +implementation details, not Fleet product resources. + +### Responsibilities + +- **Fleet project API:** authenticates the user or service identity, authorizes + the requested session, validates immutable input and exposes lifecycle status. +- **Management-session admission:** resolves the active customer Machine through + its immutable allocation to one provider `MachineCapacity`, checks current + capability and conflicts, retains private admission evidence, and chooses the + authoritative location from trusted allocation state. +- **Karmada session delivery:** carries the least-privileged resolved session and + revocation state to exactly one location. It is not another authorization + decision and is not the Redfish request path. +- **Relay endpoint:** maintains outbound connectivity from the location and + forwards an end-to-end encrypted stream. It has no BMC credential and may + reach only the location gateway. +- **Location Redfish gateway:** verifies possession of the session key, consumes + or attaches the session, enforces its profile, virtualizes Redfish resources, + retains mutating operations and calls the selected adapter. +- **Datum owned-hardware adapter:** resolves the selected `MachineCapacity` + through its immutable `Device`, verifies the enrolled physical identity, + translates the profile to a qualified BMC, obtains credentials from + location-scoped secret custody, and normalizes observations and results. +- **Operation journal:** durably records admitted mutating requests, exact + session and asset preconditions, normalized request body, idempotency + identity, privately resolved target and evidence before effects. + +The gateway and adapter may be one deployment initially, but their responsibilities +and credential boundaries remain distinct. The relay endpoint must not become an +unrestricted HTTP CONNECT service to the management network. + +### End-to-end sequence + +1. `datumctl-fleet` generates an ephemeral Ed25519 key pair and creates a public + `MachineManagementSession` referring to the customer Machine by name. +2. Milo authenticates the project context and authorizes the distinct session + create permission. Ordinary Machine read access is insufficient. +3. Fleet resolves the exact live customer Machine through its immutable + `MachineAllocation` to one provider `MachineCapacity`, its immutable Device + and authoritative Location. It retains the decision before reporting + admission success. +4. Fleet creates a minimal `LocationMachineManagementSession` in the Karmada + hub and targets the Location's exact member cluster through protected + configuration. +5. The cell verifies that its safe MachineCapacity and Device copies match and + that the owned-hardware adapter currently reports management availability for + that physical identity. +6. The gateway registers a one-use outbound relay route and returns only + non-secret rendezvous status through Karmada. Fleet reflects that status to + the public session. +7. The connector pins the gateway certificate, presents a timestamped signed + proof for the route and keeps the private key in memory. The first valid + connector consumes the route. +8. The gateway exposes the virtual Redfish profile. Before each mutation, the + location journals the exact accepted request and physical preconditions; the + adapter then resolves local enrollment and reaches the BMC. +9. Expiry, public deletion or Machine release changes the location session to + `Revoked`. The cell closes the stream and reports cleanup; missing confirmation + remains `Unknown` and prevents unsafe capacity reuse. + +### Authentication and authorization + +The [production authorization implementation plan](../implementation/secure-bmc-authorization.md) +expands the proposed IAM, caller-preservation, durable limits, and acceptance +contracts. These integrations are not yet production-verified. + +Session admission uses Datum's existing human and service identity flows. IAM +defines a management-session create permission separately from ordinary +Machine read or update. Admission evaluates that permission against the +consumer project and target Machine and then resolves its private allocation; +possession of a Machine name or locally observed UID is not authorization. + +The client generates an ephemeral Ed25519 key pair. The private key remains in +client memory and only the public key enters the session resource. On +connection, the gateway verifies a domain-separated signature covering at least +the one-use route ID, protocol version, timestamp, nonce and gateway audience. +The first accepted connection consumes the connection window. Replay, a changed +rendezvous or a second concurrent connector is rejected. + +The admitted access profile is selected from provider-published capabilities and +the caller's grant. The caller cannot supply an arbitrary path allowlist or ask +the gateway to forward unknown Redfish resources. A narrower request can be +accepted; it cannot expand the offering. + +The physical BMC sees only the gateway's location-scoped identity. BMC credentials +must never appear in the public session, its status, audit events, client errors +or relay configuration. Credential rotation does not change the customer +Machine, provider `MachineCapacity` or physical Device identity and does not +create a customer session. + +### Allocation resolution and routing + +Routing is a one-time admission decision, not a lookup on each Redfish request. +The customer Machine's allocation is an immutable, service-owned resource whose +generated Kubernetes name is its identity. Release is terminal; Fleet never +reactivates or retargets that allocation, so the session contract needs neither +a duplicated binding ID nor an epoch. + +For Datum-owned hardware, the selected provider `MachineCapacity` has an +immutable `deviceRef`. Hardware replacement creates a new `Device` and +`MachineCapacity`; Fleet never redirects the old capacity name to another +physical asset. Credential, certificate, endpoint and private-route rotation may +change while the same enrolled Device identity remains. These implementation +changes do not require a management revision in the session. + +Admission privately retains the authenticated principal, consumer and provider +project identities, the exact local source-object identities used during the +decision, the allocation resource name, selected `MachineCapacity` and +`Device`, client public key, deadlines and audit correlation. Local Kubernetes +UIDs may be used as same-API-server recreation preconditions, but they are not +authored references and never cross through Karmada. + +The Karmada-delivered location session contains only the provider +`MachineCapacity` name, access profile, client public key, deadlines and desired +state. The owned-hardware adapter resolves the capacity through its immutable +Device relationship and private enrollment. Neither the public nor location +session contains a BMC endpoint, physical system identifier, Secret reference, +adapter route or Karmada member name. + +If the allocation is released, the session is revoked. Hardware replacement +requires new capacity, allocation and session resources. The old endpoint cannot +be rebound to a successor, and provider discovery cannot silently redirect an +active session. + +### Owned-hardware enrollment and secret custody + +The Fleet management cluster intentionally has no route to location BMC +networks. Each location's Datum owned-hardware adapter maintains private +enrollment keyed by the provider `MachineCapacity` and its immutable `Device`. +Enrollment retains the BMC endpoint, physical Redfish system identifier, +qualified adapter configuration and verified physical identity. These values are +provider-backend state, not Fleet product resources. + +Before a capacity can become eligible, Fleet mirrors a safe, read-only location +copy of its provider `MachineCapacity` and registered `Device` through Karmada +to the authoritative member. The provider-project objects remain authoritative; +the copies preserve names and immutable `deviceRef` but have their own local +Kubernetes metadata and no cross-cluster UID relationship. The location writes +only management observations, which Karmada returns through a constrained status +interpreter. This gives the adapter the MachineCapacity-to-Device association without +placing provider-project credentials in the cell. + +BMC credentials and trust material are authoritative in the environment's +regional secret manager. External Secrets Operator may materialize them into a +protected namespace in the location cluster. Only the owned-hardware adapter or +another explicitly selected provider executor may read those Secrets. The +gateway submits typed operations to the adapter and cannot read physical BMC +credentials itself. Relay credentials, gateway transport identity and BMC +credentials are separate. + +The materialized management Secret is associated with the local Device copy by +a service-owned label or adapter index, not by a customer-authored reference. +It may contain the private endpoint, physical system identifier, credential and +CA bundle. Secret names, contents and resource versions remain local provider +state and never enter MachineCapacity or session specs. + +Enrollment is observational until explicitly enabled for management. The +adapter verifies that BMC-reported physical identity matches the registered +Device before reporting `ManagementAvailable`. Registration, credential +materialization or a successful observation does not authorize a power, boot, +cleaning or installation effect; the adapter executes only a retained admitted +operation. + +Endpoint, certificate, credential and private-route rotation may update the +same enrollment while physical identity remains unchanged. If the enrolled BMC +reports a different Device identity, management becomes `Unknown` or `False`, +active sessions close, and mutations fail closed. The adapter never follows a +customer URL, Host header, returned BMC link or guessed Redfish identifier to +select a physical target. + +### Session lifecycle + +A session progresses through `Pending`, `Ready` and `Connected`, then reaches one +terminal reason. Proposed terminal reasons include `Completed`, `Expired`, +`Revoked`, `NotConnected`, `AllocationEnded`, `LocationUnavailable`, `Rejected`, +`Disconnected` and `CleanupUnconfirmed`. + +`Ready` means a gateway accepted the projected session and published a usable +endpoint before the connection deadline. It does not mean the BMC is healthy or +that any requested hardware state was reached. `Connected` means the ephemeral +client key was accepted. Session expiry and command outcome remain separate. + +Deleting or closing a session immediately denies new central admission and +propagates revocation to the location. Release of the customer Machine has +higher priority: it fences new operations, revokes all sessions for its +allocation and waits for active gateways to confirm teardown or records the +result as unknown. The allocator must not make the `MachineCapacity` available +to a later consumer until the release contract has accounted for those sessions. + +The gateway fails closed when its allocation/session projection exceeds its +freshness limit. A partition does not turn cached authorization into an +indefinite management grant. An already admitted operation may continue only +under its retained authority and bounded expiry. + +### Mutating operations + +Read-only Redfish requests can be served from current BMC observations within +the session profile. Before forwarding a boot or power mutation, the gateway +retains a protected operation containing: + +- the location session resource name; +- the selected `MachineCapacity` and immutable `Device` names; +- the normalized Redfish method, virtual target and exact accepted body; +- the physical target and enrolled identity resolved privately by the adapter; +- an idempotency key derived from the operation resource name; +- current session, asset and conflict preconditions; and +- execution evidence without secret material. + +The operation journal is the authority for the effect. A gateway process lease +or an open relay stream is not sufficient. Installation, release, power intent +and other hardware operations serialize through the same asset-level conflict +contract. + +If the BMC response is lost, the result is `Unknown`. Recovery queries the +existing operation and physical state before deciding whether another request +is safe. The gateway must not translate an uncertain failure into a successful +Redfish response or blindly submit the same reset again. A Redfish task can +remain incomplete or finish with an explicit exception while recovery continues. + +### Availability and scaling + +Central load is proportional to session creation, status transitions, revocation +and audit events, not to Redfish request volume or response size. Relays provide +generic transport capacity and can scale independently. Each location gateway +handles only sessions for machines managed in that location. + +The location gateway and its operation state must be recoverable independently +of the workload machines it manages. The management path cannot depend on a +guest OS, customer cluster or the server being powered on. A location that +cannot establish current allocation authority stops accepting new connections +and mutations rather than falling back to raw BMC access. + +### Audit and observability + +The project activity log records session creation with the requesting human or +service identity. Lifecycle events record the session resource name, project, +customer Machine name, access profile, bound location, start and end times, and +terminal reason. Private same-API-server object identities may be retained in +protected admission evidence but are not customer audit fields. Audit must not +record private keys, session-local bearer values, BMC credentials, raw provider +endpoints or secret-bearing response bodies. + +Every mutating request creates an operation with a generated Kubernetes name; +that name is also its audit correlation value rather than being duplicated in +spec. Audit records include its normalized operation type and outcome. Request +bodies are +retained in protected operation state when needed for recovery; customer-facing +activity uses a safe summary. Session byte streams and Redfish response bodies +are not recorded by default. + +Metrics cover admission latency and denial reasons, session readiness, active +connections, revocation latency, gateway/BMC reachability, operation outcome and +age of unknown results. Metrics must not label by customer-controlled high-cardinality +values or expose machine-management addresses. + +## Proposed API design + +All names, groups and fields in this section are illustrative. The proposal uses +`MachineManagementSession` to distinguish the customer contract from a BMC login +session. It is a consumer-project resource and does not expose a raw BMC handle. + +### MachineManagementSession + +Each resource represents one short-lived connection for one active customer +Machine. The spec is immutable; changing the Machine, key, profile or TTL +requires a new resource. + +```yaml +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineManagementSession +metadata: + generateName: db-01- + namespace: acme +spec: + machineRef: + name: db-01 + protocol: Redfish + accessProfile: Provisioning + clientPublicKey: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + ttl: 15m +status: + connection: + relayURL: https://relay.us-central-1.example.invalid + routeID: abcdef0123456789abcdef0123456789 + gatewayAudience: fleet-redfish-iad1 + gatewayCertSHA256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + protocolVersion: redfish-v1alpha1 + connectBefore: "2026-11-11T19:01:00Z" + expiresAt: "2026-11-11T19:15:00Z" + conditions: + - type: Ready + status: "True" + reason: SessionReady + message: Connect before 2026-11-11T19:01:00Z + observedGeneration: 1 + lastTransitionTime: "2026-11-11T19:00:01Z" +``` + +`machineRef.name` identifies the customer Machine in the authenticated project; +the consumer does not supply or manage allocation or provider identities. During +session admission, Fleet resolves the exact live Machine and its immutable +allocation before the session can become Ready or authorize an effect. If the +Machine or allocation changes before that commit, admission fails or restarts +resolution rather than following stale state. A later Machine that reuses the +same name cannot receive an already admitted session because local object +identity is checked during admission and the old allocation is terminal. + +`protocol` is initially only `Redfish`. `accessProfile` refers to a versioned +platform-defined profile; arbitrary methods or paths are not accepted in the +spec. `ttl` begins no later than connection acceptance and is capped by policy. + +`status.connection` is rendezvous information, not a bearer capability. Holding +the matching ephemeral private key is required to connect. The rendezvous +reaches a virtual gateway service and must not contain a BMC address. Generally +readable +status contains neither the private allocation nor credentials. + +Deleting the resource requests revocation. Finalization or equivalent retained +service state keeps the private admission evidence until the location confirms +teardown or the platform records that confirmation as unknown. Deletion alone +is not teardown evidence. + +### Private admission evidence and location representation + +Admission durably retains private evidence outside the consumer project's +deletion domain. That persistence is a service implementation boundary, not a +customer API or a second access grant. It records the authenticated decision and +the exact immutable allocation and provider capacity selected at that time. Only +the admission service writes it. + +Fleet then creates one internal `LocationMachineManagementSession` in the +Karmada hub. Its spec contains only `machineCapacityRef.name`, `accessProfile`, +`clientPublicKey`, `connectBefore`, `expiresAt`, a shorter refreshed +`freshUntil`, and monotonic `desiredState: Active|Revoked`. The authority fields +are immutable; only `freshUntil` may advance within `expiresAt`, and +`desiredState` may move from `Active` to `Revoked`. The selected location can +write conditions and non-secret rendezvous status but cannot alter spec. + +```yaml +apiVersion: coordination.fleet.datumapis.com/v1alpha1 +kind: LocationMachineManagementSession +metadata: + name: session-01jcc5 + namespace: machine-access-system +spec: + machineCapacityRef: + name: iad1-r12-srv01 + protocol: Redfish + accessProfile: Provisioning + clientPublicKey: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + connectBefore: "2026-11-11T19:01:00Z" + expiresAt: "2026-11-11T19:15:00Z" + freshUntil: "2026-11-11T19:02:00Z" + desiredState: Active +status: + connection: + relayURL: https://relay.us-central-1.example.invalid + routeID: abcdef0123456789abcdef0123456789 + gatewayAudience: fleet-redfish-iad1 + gatewayCertSHA256: 0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef + protocolVersion: redfish-v1alpha1 + conditions: + - type: Ready + status: "True" + reason: RelayRegistered + observedGeneration: 1 + lastTransitionTime: "2026-11-11T19:00:01Z" +``` + +The propagation policy, member-cluster name and private admission evidence are +not fields on this resource. Fleet owns those in its management-plane delivery +configuration. Fleet generates a globally unique Kubernetes name for the +location copy; it does not duplicate that name as a `sessionID` field. The +profile name is an immutable versioned contract within the API version; +incompatible profile behavior requires a new profile name or API version rather +than a mutable revision field. + +Private evidence survives long enough to complete revocation, release and audit +even if the public session or customer project is deleted. Creating a session +cannot alter the Machine allocation or lifecycle. + +### Permission model + +The initial permission model should distinguish at least: + +- reading session status; +- creating a provisioning-profile session; +- revoking one's own or project sessions; +- operator inspection of protected routing and operation evidence; and +- operator override or recovery actions. + +Default viewer access does not imply session creation. Service identities receive +an explicit grant. The admission service rechecks current source capability, +Machine authority and allocation state at creation; an old IAM decision or copied +session object is not sufficient. + +### API and Redfish errors + +Session admission uses normal Datum API errors and conditions. Once connected, +the gateway returns Redfish status codes and extended error bodies for profile, +capability and operation failures. Errors must distinguish unsupported behavior, +conflict with another admitted operation, expired/revoked authority, unreachable +BMC and unknown execution outcome without disclosing the physical route. + +## Security considerations + +- **Compromised customer credential:** IAM limits session creation to authorized + customer Machines; quotas, short connection windows and activity alerts bound + abuse. +- **Stolen ephemeral private key:** keys live only in connector memory, have a + short lifetime and are bound to a single one-use route, gateway audience and + admitted location copy. +- **Compromised relay:** end-to-end encryption prevents the relay from reading or + modifying Redfish traffic; the relay holds no allocation or BMC credential. +- **Replay or stale allocation:** the immutable session input, first-connector + consumption, key proof, timestamps, nonce, gateway audience and current + Karmada-delivered state are checked together. Release propagates revocation and + blocks capacity reuse until sessions are accounted for. +- **Confused deputy:** the gateway resolves targets only from the trusted + location session and owned-hardware enrollment, never from a customer URL, + host header, Redfish link or BMC identifier. +- **Compromised location gateway:** network policy and credentials limit it to + machines in its location. Credential isolation and one authoritative adapter + reduce blast radius; a compromised gateway remains a high-severity management + incident requiring credential rotation and allocation review. +- **BMC response injection:** the adapter validates TLS trust and the enrolled + physical identity. Redirects or links outside the virtual allowlist are not + followed or returned as customer routes. +- **Persistent firmware state:** the narrow profile excludes account, network, + firmware and OEM mutation. Release still evaluates applicable BMC and firmware + restoration obligations before reuse. + +## Rollout plan + +1. **Contract prototype:** implement the virtual Redfish profile against a + virtualized or simulated Supermicro-compatible BMC. Exercise common Redfish + clients through a local connector and verify that unlisted resources and + fields cannot be reached. +2. **Location transport prototype:** establish outbound relay connectivity from + a lab location, project a synthetic bound session, and prove direct client-to-location + traffic without placing the central API in the Redfish data path. +3. **Physical lab qualification:** connect the gateway to disposable Supermicro + hardware over the management OpenVPN path. Verify correct-host identity, + one-time PXE boot, supported power actions, task recovery, credential rotation, + rate limits and network isolation. +4. **Allocation integration:** authorize sessions against real customer Machines + and immutable MachineAllocations. Exercise concurrent allocation/release, + project deletion, location loss, stale session replay and uncertain BMC + responses. +5. **Customer pilot:** enable an explicit IAM grant and session quota for selected + projects. Integrate one existing customer provisioner without giving it BMC + or VPN credentials. Review audit records and operational load before expansion. + +## Acceptance gates + +- A standard Redfish client, using the supported connector, can inspect the + allocated system, select one-time PXE boot and perform each offered power action. +- The central API is absent from the Redfish request and response data path. +- The customer cannot discover or reach the BMC address, management VPN, another + machine, an OEM endpoint or an unlisted Redfish field/action through the gateway. +- Human and service identities use normal Datum authentication; an explicit IAM + grant and current customer Machine allocation are required for session + creation. +- Two customer Machines, projects or overlapping classes cannot cause a session + to bind the wrong `MachineCapacity`. Reuse of a customer Machine name cannot + inherit a prior session or terminal allocation. +- Release and project deletion deny new operations, actively close sessions and + prevent capacity reuse until teardown is confirmed or represented as unknown. +- A mutating request is retained before the BMC effect. Lost responses and gateway + restarts recover the existing operation without blindly repeating it. +- Gateway, relay and BMC credential failure produce actionable but non-secret + status and never become false readiness. +- The same public Redfish profile can be implemented by another qualified adapter + without changing the consumer session contract. + +## Open questions + +- Which existing Redfish clients must be supported and what loopback TLS and + session-login behavior they require beyond the qualified DMTF client and + validators used by the prototype. +- Which Datum-owned BMC models and firmware revisions qualify each operation in + the initial `Provisioning` profile. +- Whether an established Datum Connect deployment can satisfy browser, CLI and + service automation requirements, or whether a dedicated relay profile is + needed. +- The production Karmada topology, member-registration ownership, refresh + interval and maximum `freshUntil` window during control-plane partitions. +- Durable storage and concurrency boundaries between Fleet admission, the + location operation journal and provider adapters. +- Whether future regional HTTPS ingress is needed for customers that cannot run + a connector, and how its bearer credentials would be scoped and revoked. +- Session quotas, TTLs, per-machine concurrency, request rate limits and activity + alert thresholds for the initial pilot. +- Production ownership and deployment boundaries for the gateway, relay + endpoint, owned-hardware adapter and optional management OpenVPN connection. + +## References + +- [DMTF Redfish Specification DSP0266 v1.22.1][redfish-spec] +- [DMTF Redfish schema and developer resources][redfish-resources] +- [OpenStack Ironic Redfish driver](https://docs.openstack.org/ironic/latest/admin/drivers/redfish.html): broader provisioner requirements to evaluate; the narrow profile does not claim full Ironic compatibility. +- [Datum Compute instance shell session proposal][compute-shell] +- [Datum Compute session protocol][compute-session-protocol] +- [Datum Compute client-to-location tunnel][compute-tunnel] +- [Pinned Fleet infrastructure management proposal][fleet-proposal] +- [Pinned Fleet bare-metal provisioning proposal][fleet-provisioning] + +[compute-session-protocol]: https://github.com/datum-cloud/compute/blob/fe85e3c619d2a774fc9ad45b2d362ced32a43c28/internal/consolesession/protocol.go +[compute-shell]: https://github.com/datum-cloud/compute/blob/fe85e3c619d2a774fc9ad45b2d362ced32a43c28/docs/enhancements/instance-shell-sessions/README.md +[compute-tunnel]: https://github.com/datum-cloud/compute/blob/fe85e3c619d2a774fc9ad45b2d362ced32a43c28/internal/consoleclient/tunnel.go +[fleet-proposal]: https://github.com/datum-cloud/infra/tree/51781e2456367be82281e1443ca56d0686311133/docs/enhancements/fleet-management +[fleet-provisioning]: https://github.com/datum-cloud/infra/blob/51781e2456367be82281e1443ca56d0686311133/docs/enhancements/fleet-management/bare-metal-provisioning.md +[redfish-resources]: https://redfish.dmtf.org/essentials +[redfish-spec]: https://www.dmtf.org/sites/default/files/standards/documents/DSP0266_1.22.1.pdf diff --git a/docs/implementation/machine-management-prototype.md b/docs/implementation/machine-management-prototype.md new file mode 100644 index 00000000..9b14c057 --- /dev/null +++ b/docs/implementation/machine-management-prototype.md @@ -0,0 +1,420 @@ +# Secure machine-management prototype + +Status: implemented prototype; portable tests are runnable on macOS and Linux, +while the full sushy/libvirt path is Linux-only. This document records what the +repository implements. The [enhancement](../enhancements/secure-bmc-access.md) +remains the proposed product contract and is not weakened by the shortcuts here. + +## Architecture and trust boundaries + +The customer runs the real `datumctl` binary. Its plugin dispatcher finds the +first-party `datumctl-fleet` executable. The plugin receives project context from +datumctl, obtains its bearer credential only through `plugin.Token()`, generates +an ephemeral Ed25519 key pair, and creates a public +`MachineManagementSession`. It never reads `DATUM_TOKEN`. + +The management-cluster controller authenticates through the Kubernetes delegated +request identity retained by the mutating admission webhook. Kubernetes RBAC +provides the prototype authorization decision: `machines` read and +`machinemanagementsessions` create are separate grants. The controller resolves +the customer `Machine` through service-owned claim and asset custody Secrets to a +provider `MachineCapacity` and creates a protected +`MachineManagementSessionBinding`. The latter pins the principal, consumer and +provider project identities, the Machine, allocation, MachineCapacity and +immutable `deviceRef`, an injected authoritative location and Karmada member, client key, +deadlines, and correlation IDs. Local object UIDs are retained only in that +management-API record as recreation preconditions. `AllocationUID` now identifies +the private allocation binding, not a `MachineAllocation` CRD UID. None cross through Karmada +or enter the public session. + +The controller writes a least-privileged session to the separate Karmada API and +creates an exact-cluster `PropagationPolicy` using the member identity retained +from protected allocation state. It has a Karmada-scoped credential and no cell +kubeconfig. Karmada creates a `Work` only for that member and reflects cell-written +status through a Fleet-specific `ResourceInterpreterCustomization`; the +interpreter rejects status from any other member and prevents a claimed route +from changing identity. The controller refreshes only the cached-authority +deadline while every pinned input still matches. The location gateway registers +an outbound opaque route with the relay. Public status +contains only its relay URL, random route, proof audience, protocol version, and +gateway certificate fingerprint. The central API and controllers are not in the +Redfish request/response path. + +The client consumes the route once, pins the per-session gateway TLS certificate, +and signs every request with a timestamped, nonce-bearing, domain-separated +Ed25519 proof bound to that one-use route and gateway audience. The gateway +rejects changed projected inputs, audiences, expired timestamps, nonce replay, +and stale authority. Relay registration and gateway TLS/proof credentials are +separate. The relay only pairs an opaque route; it cannot select a BMC target and +does not implement unrestricted CONNECT. + +The plugin exposes a TLS endpoint only on loopback. It writes a one-time local +username/password and CA bundle at mode `0600`, publishes a non-secret readiness +JSON file, deletes local login tokens on Redfish logout, and removes all temporary +files at shutdown. These credentials are unrelated to the gateway's private +sushy credential. + +At the location, the gateway exposes one virtual system named `allocated`. The +projected session contains only the selected MachineCapacity name and session +authority. The gateway resolves a safe location-local MachineCapacity copy +through its immutable `deviceRef`, then selects exactly one service-owned +management-enrollment Secret carrying the adapter, endpoint, physical system and +credential inputs. Its adapter selects the physical sushy system only from that +resolved enrollment. +Customer paths, Hosts, OData links, and guessed identifiers never participate in +physical routing. The only supported mutations are one-time `Pxe` or `Hdd` boot +selection and `On`, `ForceOff`, `GracefulShutdown`, `GracefulRestart`, or +`ForceRestart`. Unsupported values fail rather than being substituted. + +## Session and operation sequence + +1. `datumctl fleet machine-management proxy MACHINE` generates a key and asks the + management API for a session using only the customer Machine name. +2. Admission retains the authenticated principal. With an explicitly injected + access resolver, the controller resolves current Machine and provider identities + against protected lifecycle custody, enforces advisory limits, and acquires an + exclusive session hold in the asset Secret before publishing the binding. +3. The projector checks the authoritative allocation on every refresh, creates a + Karmada hub copy and exact-member policy, and waits for status from that member. + The gateway reads only its cell-local copy, establishes an outbound relay + route, and writes non-secret rendezvous status to that copy. +4. The plugin consumes the route, verifies the pinned TLS identity, proves its + admitted private key, and opens the loopback Redfish service. +5. Before a boot or reset effect, the gateway fsyncs an operation containing the + location-session, MachineCapacity and Device identities, normalized method + and virtual URI, exact accepted body, internally selected physical target, + idempotency key, operation epoch, conflict/freshness preconditions, and later + execution evidence. Effects for a Device are serialized across all sessions + in the gateway process. The protected central binding supplies durable + correlation back to the MachineAllocation. +6. A lost adapter response becomes `Unknown`; replaying the exact request returns + the existing task without a second adapter call. Failed or unknown effects are + never rewritten as success. +7. Expiry, public deletion, allocation release, or changed binding inputs changes + the hub copy's desired state to `Revoked`. Karmada carries the fence to the + selected cell; the gateway closes the stream and writes `CleanupConfirmed` + before the controller removes the policy and hub copy. Release also writes a + terminal revocation annotation so later Machine-name reuse or a new allocation + cannot resurrect the session. Deletion alone is never teardown proof; if the + cell cannot acknowledge the fence, central cleanup is `Unknown`. + +## API and deployment artifacts + +Kubebuilder-style session types are under `internal/api/session/v1alpha1`; public sessions and protected central bindings +use `metal.datumapis.com/v1alpha1`, alongside the canonical lifecycle types under +`internal/api/v1alpha1`. Location projections are defined separately under +`internal/api/coordination/v1alpha1` and use +`coordination.fleet.datumapis.com/v1alpha1`. The hub and location need only the +projection CRD for session delivery; neither receives customer session authority. Generated session CRDs are under `config/crd/bases`, +while the lifecycle CRD bundle remains under `config/base/crd`. CEL makes the +public spec immutable and constrains protocol, profile, key encoding, and TTL. +Conditions carry `observedGeneration`, explicit reasons, and true/false/unknown +outcomes. + +RBAC is in `config/rbac`; controller and location workloads are in +`config/manager` and `config/location`. `config/federation` contains the Karmada +status interpreter and hub-only projector RBAC. Containers run as non-root with read-only +root filesystems, no added Linux capabilities, and `RuntimeDefault` seccomp. +NetworkPolicy permits the outbound relay, the one private BMC address, DNS, and +the Kubernetes API; it does not expose gateway ingress. Metrics cover admission, +active sessions, revocation latency, BMC reachability, operations, and unknown +outcomes. Protected bindings plus structured, correlation-bearing controller logs +provide the prototype's central audit record. + +The declared DMTF interoperability profile is +`config/redfish/FleetProvisioning.v1_0_0.json`. + +## Reproducible Linux environment + +The qualified prerequisite is Linux with Docker Engine and Compose v2, Kind, +kubectl, Helm, Go 1.26.4, Task, jq, OpenSSL, and curl. KVM is used when `/dev/kvm` is available; otherwise +the same real libvirt domain runs with QEMU software emulation. There is no +in-memory or static-JSON BMC fallback. The scripts can also attempt the QEMU path +on Docker-backed macOS for development, but CI qualification remains Linux. + +`task e2e:up` builds and starts: + +- management and location Kind clusters; +- pinned Karmada 1.16.0 in the management cluster, with the location Kind + cluster registered as a member; +- locally built controller, relay, and gateway images; +- a privileged test-only Ubuntu 24.04 container running libvirt/QEMU and pinned + sushy-tools 2.2.0; +- allocated and unallocated libvirt domains on a PXE-enabled provisioning network; +- a minimal PXELINUX/initramfs fixture whose HTTP callback records the VM MAC; +- an internal Docker management network reachable only from the attached location + Kind node; and +- pinned DMTF Python Redfish client and validator tools. + +The harness is repository-local and does not currently consume +`datum-cloud/test-infra`. Production/environment installation is expected to be +owned there (or in `infra`) once hub identity, member registration, and location +registration contracts are selected. This is a prototype choice, not a proposal +change. + +The sushy port accepts only the location node address. The customer process sees +only loopback ports for the relay and local Redfish connector. The default CI +profile relies on this isolated internal network. After `e2e:up`, the separate +`task e2e:openvpn:up` profile recreates the virtual BMC with a real OpenVPN `tun` +boundary, installs a privileged test client on the location node, moves the +gateway adapter to `10.88.0.1`, and proves the direct management address is +blocked. This profile is intentionally outside default hosted-runner CI. + +Run the complete lifecycle with: + +```console +task e2e:up +task e2e:test +task e2e:down +``` + +The test calls the actual `datumctl fleet ...` command. A repository-local test +Datum session stores synthetic service-account tokens through datumctl's file +keyring format, after which the plugin must still call datumctl's credential +helper. `e2e:up` explicitly trusts the locally built plugin by its path and SHA-256 +using datumctl's unmanaged-plugin trust command. The test requires a real Karmada +`Work` in `karmada-es-fleet-location-e2e`, verifies the hub received the selected +cell's route status, and proves management has no direct location credential. It +exercises generic DMTF client login, profile narrowing, distinct RBAC, +per-Machine and per-project limits, one-shot rendezvous, real PXE and libvirt power +effects, DMTF validators, central API loss and freshness failure, release fencing, +Machine recreation, route isolation, response-loss recovery, and bounded BMC errors. + +Validator versions are `redfish` 3.4.2, +`redfish-service-validator` 3.1.8, and +`redfish-interop-validator` 3.0.3. Reports and PXE correlation evidence are under +`.e2e/validators` and `.e2e/virtual-bmc/evidence`. + +Setup downloads the DMTF Redfish-Publications 2026.2 CSDL snapshot at +`4f81814e399213c9055863ddaff42791c6b3706a`, verifies its archive SHA-256, and +extracts it into `.e2e/redfish-schemas`. The pin and checksum are in +[`prepare-schemas.sh`](../../hack/e2e/prepare-schemas.sh). Validation uses that +explicit cache with `--skipschema`; it does not download schemas while a +short-lived management session is active or change TLS trust for the loopback +service. Reports retain schema provenance and summary counts. A zero exit code +alone is insufficient: each validator must perform positive checks with zero +warnings and failures. Optional-property skips remain visible and are not +counted as successful checks. + +## Troubleshooting + +Run `task e2e:diagnostics` before teardown. It captures both clusters' resources, +events and logs, Karmada clusters/Works/bindings and hub session state, +protected/public session state, libvirt domain state/XML, virtual +BMC logs, validator reports, acceleration selection, and PXE callbacks. + +The harness writes timestamped successful scenario checkpoints to +`.e2e/checkpoints.log` and retains earlier proxy logs across session restarts. +On failure it attempts a bounded diagnostic snapshot before terminating proxies +or undoing injected outages; CI also collects diagnostics on successful runs. +Resource reads are separate so a CRD absent from one cluster does not hide that +cluster's other evidence. Workload logs target explicit deployments, and BMC +evidence is exported through Docker rather than assuming a remote bind mount is +visible on the client. Only named non-secret evidence files are exported. + +`FLEET_E2E_WAIT_SECONDS` bounds polling by elapsed seconds, not by the number of +potentially slow requests (an in-flight probe can still add its own timeout). +Proxy readiness fails when the process exits instead of waiting for the entire +polling budget. API errors do not count as confirmed session deletion. These +harness checks do not change the admitted one-minute connection window, session +expiry, or the gateway freshness fence. Portable helper regressions run with +`bash hack/e2e/test-common.sh` and in the Linux E2E workflow. + +- A gateway stuck on `RelayUnavailable` usually indicates relay DNS/token or + NetworkPolicy failure in the location cluster. +- A missing cell projection: inspect the hub `PropagationPolicy`, the Work in + `karmada-es-`, member `Ready`, and the Fleet status interpreter. +- `BMCUnavailable` is intentionally bounded; inspect the gateway and virtual-BMC + diagnostics rather than expecting a private address in the customer response. +- No PXE callback: inspect `allocated-console.log`, libvirt network state, and the + VM MAC in `pxe-callbacks.jsonl`. +- `AuthorityStale` after a controller outage is expected. The E2E deployment uses + 15 seconds so the test is fast; the binary default is two minutes. +- `task e2e:down` validates its repository-local state path and names every Docker + and Kind target before removing it. + +## Prototype choices and remaining production gaps + +Implemented-and-tested code must not be confused with a production-ready +contract. Important gaps are: + +- The [lifecycle integration](secure-bmc-lifecycle.md) now reads protected Secret + custody, retains an exclusive hardware session hold, and blocks installation, + cleanup and reuse until verified teardown. It does not trust synthetic Active + allocation annotations. Its production access resolver remains absent, so + installing CRDs does not enable BMC access. Portable tests use explicit injected + authorization and observation fixtures; they are not production IAM evidence. +- Delegated Kubernetes authentication/RBAC models the intended Compute/Milo + pattern, but the production Datum API aggregation and session IAM + registration are not wired. Sessions belong to the existing `metal` service; + default Machine read access must not imply session-create permission. +- Karmada projection and status aggregation are implemented and exercised, but + member selection now requires the injected access resolver rather than allocation + annotations. Production needs an authoritative location-to-member registration + controller, credential rotation, HA operations, failover policy, and + environment packaging in `test-infra`/`infra`. +- The relay is a small Fleet-specific opaque TCP rendezvous with inner TLS, not + Compute's maintained relay deployment. A shared public transport package and + operational ownership decision are still required; Fleet does not import + Compute internal packages. +- The gateway is intentionally single-replica with an RWO journal. Its fsynced + files and in-process per-machine lock demonstrate order and recovery, but a + production multi-replica lease/fencing store is not implemented. +- Exact request bytes form the prototype idempotency identity. Production needs a + client-visible idempotency contract and adapter-specific recovery observation. +- The default test isolates the management network with Docker and iptables; a + separate OpenVPN profile exists but is not yet a production-qualified VPN. + Credential rotation, HSM-backed location identity, multi-location PKI, and + relay denial-of-service controls remain. +- The virtual profile omits firmware, AccountService, Managers, UpdateService, + virtual media, OEM actions, and BMC networking by design. Broader capability + requires a separately reviewed profile and adapter qualification. +- No physical BMC vendor is qualified. sushy/libvirt demonstrates effects and + ambiguity handling only. + +## Synchronization with Fleet (2026-11-12) + +This branch integrates [prototype PR #42](https://github.com/datum-cloud/fleet/pull/42) +at `b7aea9023ad586c3e8c21b0508bebca78f58e0b1`, including the proposal from +[PR #41](https://github.com/datum-cloud/fleet/pull/41), with Fleet main at +`42dc39c09886078230999c5f675520aa5cc67b64` and the Bare Metal API split at +`63e2e1cc7adabc9e0c3d0fae1069c47c78738f45`. + +PR #43 simplified the identity model and PR #44 implemented it. The prototype +already followed those identities. This synchronization moves the public session, +private binding, CLI requests, webhook, RBAC, CRDs and fixtures to Metal, and the +Karmada projection and status interpreter to the coordination group. Private +Fleet labels, finalizers and binary names retain their implementation identity. +Projection refresh is capped at admitted expiry, and terminal revocation preserves +the monotonic freshness deadline instead of issuing a CEL-invalid backward update. +The service-catalog dependency is restored to Fleet's v0.13.1 baseline; the +prototype's Kubernetes/controller-runtime versions remain selected by the combined +dependency graph. + +The [review of #42](https://github.com/datum-cloud/fleet/pull/42#pullrequestreview-5882335250) +was against an earlier revision. The current route proof uses the route ID and +the allocation model has changed, but the review's remaining limitations must not +be mistaken for production guarantees: cached session-count admission is not a +durable quota transaction; transient allocation reads currently terminally revoke; +request-byte idempotency cannot distinguish repeated intentional resets; interrupted +Pending operations lack automatic provider recovery; relay registration, nonce +storage, clock bounds, and reconnect handling still need production hardening. +These are follow-up work, not resolved by the API rename. Generic DMTF client and +validator evidence from the prototype is not full provisioner or physical BMC +qualification. + +This is a breaking alpha API change, not a storage migration. Stop admitting old +sessions, revoke them using their old controller and groups, and retain private +bindings until teardown is accounted for before removing old CRDs. Do not copy +active sessions into the new groups. Recreate only disposable synthetic fixtures; +occupied provider capacity and cleanup obligations must retain their authority. + +### Validation of this synchronization + +Portable checks passed: `go test ./...`, `go test -race ./...`, `go vet ./...`, +`task build`, reproducible `task generate`, production and prototype Kustomize +renders, Milo packaging validation, the existing overlay/standalone validation +scripts, documentation links, and whitespace checks. CI now checks generated +session/coordination CRDs and renders the prototype roots. + +On macOS with an x86 Linux Docker VM, `task e2e:up` completed. Kubernetes accepted +the renamed CRDs, Karmada delivered the coordination projection, the generic DMTF +client and session-limit checks passed, and the allocated libvirt VM produced a +fresh PXE callback and powered off. The evidence harness now clears callback +files at the container writer and copies them through Docker, so verification +does not depend on host/VM bind-mount visibility. It also waits for valid authority +after the expensive emulated boot before attempting another mutation. + +The initial synchronized `task e2e:test` run did **not** pass: repeated sessions +intermittently exhausted the one-minute connection window, and a post-PXE disk-boot +request failed before journal admission. Its cause was not established by that +run. At that point the added authority wait and later validator, central-outage, +release/recreation, expiry, and lost-response scenarios remained unverified. That +environment was torn down. The follow-up below records subsequent evidence +separately rather than attributing the earlier failures to emulation. + +### E2E reliability follow-up (2026-11-12) + +A fresh run from the synchronized prototype completed every lifecycle scenario, +including disk restoration, both outages, release/recreation, expiry, and the +lost-response duplicate-reset check. However, inspection invalidated its service +validator result: version 3.1.8 returned zero with **zero schema checks and ten +warnings** after the loopback-only CA bundle prevented the external DMTF schema +download. The narrow service also has no schema metadata endpoint, so no schema +source remained. That run is lifecycle evidence, not successful schema validation. + +The pinned offline schema cache and coverage guard now fail closed on that case. +Real schema validation then exposed two ServiceRoot errors: the task-service link +was named `TaskService` instead of the standard `Tasks`, and mandatory `Links` +was missing. The root now publishes `Tasks` and `Links.Sessions`; the declared +interoperability profile and a focused regression test agree with those fields. +The next run performed 91 schema checks but failed the zero-warning guard on +three deprecated task-message `Severity` fields. Messages now use the standard +`MessageSeverity`, with regression coverage preserving success, failure, pending, +and unknown task outcomes. This intermediate result is not a validator pass. +No provider route, admitted connection deadline, expiry, freshness fence, or +operation-authority behavior changes as part of these corrections. + +The final corrected pre-lifecycle run on November 12 (November 13 UTC) did **not** +complete. Setup, RBAC denial, generic DMTF client, Karmada projection, local login +revocation, route isolation, session limits, and a fresh PXE callback with libvirt +poweroff passed. At 00:21:08 UTC the boot proof completed; the subsequent bounded +authority wait failed. At 00:23:26 the member projection still had +`authorityFreshUntil=00:15:41Z`, while the hub had `00:17:43Z` and admitted expiry +was `00:28:47Z`. Karmada's API server had restarted twice and its controller manager +six times; previous manager logs show refused connections to the Karmada API, and +API-server logs show failed etcd connectivity. These observations establish stale +authority and control-plane interruption, not the underlying cause of those +restarts. No Hdd mutation or validators were reached in this run. The gateway did +not relax its freshness fence. Diagnostics now retain pod termination status and +previous workload logs as well as current logs for this failure class. + +Evidence is retained locally under +`/tmp/fleet-bmc-reliability-evidence/run-{1,2,3}`; the final setup/test logs are +`/tmp/fleet-bmc-reliability-{up,test}-3.log`. Only allowlisted diagnostics, +validator reports, and non-secret logs are archived, not kubeconfigs or proxy +credentials. Run 1 proves the baseline lifecycle scenarios but not schema +validation; run 2 proves schema traversal and identifies the deprecated fields; +run 3 does not establish that the final schema correction passes live validation. +Portable full Go tests, targeted race tests, shell helper regressions on macOS +and Linux, schema checksum rejection, shell syntax/ShellCheck, documentation +links, and whitespace checks pass. The original intermittent connection-window +failure remains unresolved; its cause was not reproduced or established here. + +These results are for the synchronized `bccf896` pre-lifecycle baseline, **not** +the later Coordinator custody integration. Combined validation must use the +explicit synthetic fixture, real Secret-backed lifecycle custody and release, +and the updated coordination CRD. Its lost-response/unknown-operation scenario +must be last or isolated: unknown effects legitimately prevent teardown and +allocation reuse, and cannot be cleared merely to continue the test. No native +Linux/CI full run, physical BMC, or OpenVPN qualification was obtained in this +environment. A complete warning-free validator and lifecycle run remains required. + +### Combined lifecycle harness integration (2026-11-12) + +The harness now builds and invokes the explicit +[synthetic lifecycle fixture](synthetic-bmc-fixture.md), rather than creating or +patching MachineAllocation CRDs. Initial and extra allocations use real +Secret-backed Coordinator custody. Live-session release must return the specific +management-teardown blocking error and durably mark the asset Releasing. The +harness then waits for current-generation `CleanupConfirmed=True` before retrying +the exact old Machine UID's release, deleting/recreating the Machine, and proving +that capacity reuse advances its allocation epoch. + +Repeated setup attempts release retained fixture Machine lifetimes before +resetting domains or replacing workloads. They never delete custody, grants, +private session bindings, or operation journals to bypass an uncertain result. +An unresolved release fails setup; use whole-environment teardown only for these +disposable synthetic resources. Location-outage deletion must retain its session +finalizer while cleanup is Unknown, then wait for verified recovery. The final +lost-response scenario proves duplicate suppression and rejects a distinct new +mutation, release, finalizer removal, and competing allocation while the effect +remains Unknown. It intentionally leaves occupied custody for diagnostics and +whole-environment teardown rather than attempting another session on that asset. + +These combined script assertions are implemented, not yet full-harness verified. +Shell syntax/ShellCheck and helper regressions pass, including rejection of +missing/API-error custody evidence and stale-generation/Unknown cleanup. Focused +Go tests cover the fixture, controller, Redfish, and gateway. Per the integration +handoff, native Linux GitHub CI is the next full-run evidence source; no new local +emulated run was started and no CI success is claimed here. diff --git a/docs/implementation/secure-bmc-authorization.md b/docs/implementation/secure-bmc-authorization.md new file mode 100644 index 00000000..12ba6b63 --- /dev/null +++ b/docs/implementation/secure-bmc-authorization.md @@ -0,0 +1,179 @@ +# Secure BMC production authorization plan + +Status: proposed implementation contract, 2026-11-12. This plan expands the +production authorization work for Secure BMC Access. It does not enable production +admission or claim live Milo acceptance. + +Read with the [Secure BMC proposal](../enhancements/secure-bmc-access.md), +[prototype status](machine-management-prototype.md), [API architecture](../architecture/README.md), +and [pinned provisioning proposal](../proposals/fleet-management/bare-metal-provisioning.md). + +## Current implementation and gap + +`internal/controller/admission.go` copies the admission request username into a +service-owned annotation and makes the session spec immutable. Kubernetes RBAC +separates session creation from Machine reads. This is useful prototype evidence, +but a username is not a durable Milo authorization receipt, and the asynchronous +controller cannot reconstruct the original caller's authority from it. + +`internal/controller/session.go` counts cached bindings to enforce limits. That +check is not an atomic reservation across controller replicas. The existing Milo +contracts in `internal/milo/types.go` describe retained authority, admission fencing, +and protected quota custody for machine allocation; their production adapters are +not implemented. `internal/milo/quota.go` is specific to the machine quota resource +and must not be reused unchanged for sessions. + +The production admission path must retain the authenticated caller and exact +request, obtain a target-specific decision, reserve limits durably, and commit +against current allocation authority before any usable route is published. + +## Permission and audience contract + +Use the existing Bare Metal service, `metal.datumapis.com`, and its `metal` +entitlement. Do not create a second BMC catalog service. The following permission +names are proposed additions, subject to Milo integration validation: + +| Permission | Scope and purpose | +| --- | --- | +| `machinemanagementsessions.create` | Create a session request in the authenticated consumer project. | +| `machines.manageBMC` | Authorize the requested Provisioning capability against the exact target Machine in that project. | +| `machinemanagementsessions.get/list/watch` | Read safe session metadata and connection status in the project. | +| `machinemanagementsessions.delete` | Request teardown of a session in the project, including one created by another principal. | +| `machinemanagementsessions.updateStatus` | Service-only status publication. | + +All names above are prefixed with `metal.datumapis.com/` in IAM registration. +Creation requires both create and target capability permission. A generic create +grant alone cannot authorize arbitrary Machine references. If Milo cannot evaluate +the target-specific permission with the original caller, production stays disabled; +project-wide create must not silently substitute for that decision. + +Add an explicit opt-in BMC operator role containing the customer permissions above. +Do not inherit it into the existing viewer, consumer, or provider roles. Existing +Machine read, update, installation, and provider inventory grants confer no BMC +access. Retain project-wide session visibility for this initial role: the creator +is an audit identity, not an implicit owner-only ACL. A separate reader role may +be added later if needed. Customer writes to status, private admission receipts, +bindings, projections, quota custody, or finalizers remain forbidden. There is no +customer update/patch operation for changing an admitted session. + +Provider projects supply capabilities and enrollment authority; customers do not +need provider inventory permissions. Customer errors must not disclose whether a +foreign Machine or physical asset exists. Private allocation and Device details +stay out of public responses and IAM-facing customer objects. + +## Caller-preserving admission sequence + +1. Authenticate through Milo's trusted request path. Resolve the consumer project + identity and lifetime from that path, not a namespace name, annotation, or + request field. Preserve the principal's immutable identity and the authenticated + delegation context needed by the authorizer. Never persist bearer credentials. +2. Validate the immutable request and bind its digest to the target Machine UID, + consumer project lifetime, namespace UID, client public key, protocol, access + profile, and requested TTL. Reject ambiguous or unsupported profiles. Check + current Bare Metal entitlement and provider-published capability constraints. +3. Evaluate create and target capability permissions as that caller. Retain a + private receipt with decision ID, exact request digest, principal identity, + policy evidence/version and validity bound supported by the authorizer. A + controller service-account decision cannot replace a caller decision. +4. Persist a protected admission intent before quota or projection effects. Bind + it to the actual persisted session UID before creating any route. The request + admission boundary must provide a trustworthy handoff to the asynchronous + controller; an editable annotation is insufficient. Admission dry-run performs + validation only and creates no durable holds or external effects. +5. Resolve the exact current allocation through Fleet's authoritative lifecycle + custody. Retain Machine, allocation, capacity, Device and project identities + separately. Obtain the per-machine slot and project quota holds described below. +6. Commit admission under the shared lifecycle fence. Revalidate allocation + activity, project lifetime, entitlement, capability and receipt validity at the + commit boundary. A release or identity change wins over an uncommitted session. + Persist the admitted binding and its hold references before projection. +7. Publish only the existing narrow location projection. Caller credentials and + central policy receipts never enter Karmada or the gateway. Location execution + remains subject to current projected authority and the common effect fence. + +The trusted request handoff, target-decision API, and policy validity/revocation +signal are explicit Milo dependencies. Select their concrete adapters before +implementing admission; no invented endpoint or unsigned receipt is acceptable. +A webhook crash or API write failure may leave a prepared intent; recovery must +reconcile it against the persisted session UID and settle any known holds. A +missing response alone is not proof that a request or hold was never committed. + +## Durable limits and recovery + +Start with the prototype's policy defaults of one live session per Machine and +five per consumer project, configurable by service policy. Count pending admitted +sessions as well as connected ones. Session TTL is an independent maximum, not a +quota reservation mechanism. + +Use two durable controls: an allocation-scoped exclusive session slot through the +lifecycle custodian, and a Milo quota hold under a distinct proposed resource +`metal.datumapis.com/machinemanagementsessions`. Include consumer project lifetime, +Machine UID, allocation identity and session UID in the private custody record. +Retries for one session recover the same intent and holds. A second session must +not reuse them, even if its name or request body matches. + +The two stores need no assumed distributed transaction: prepare the intent, +reserve the machine slot, acquire project quota, then commit under the lifecycle +fence. Never publish a route before both holds and the commit are durable. A +partial failure remains pending or compensates through recorded settlement; it +cannot bypass one limit. A lost quota response is recovered by exact intent +identity, not by creating another quota claim. Protect hold lifetime from customer +deletions and quota claim edits. Cached list counts may be diagnostic only. + +Keep both holds until teardown is verified. Neither public session deletion, +terminal status, nor TTL expiry alone proves that a connector or admitted effect +has stopped. A proven never-projected admission may settle without contacting a +gateway; uncertain projection must take the teardown path. Persist teardown and +settlement receipts so restarts can resume without freeing a live slot. Quota +release uncertainty retains custody and reduces availability rather than allowing +oversubscription. Reconciliation must surface stuck holds for operators. + +## Revalidation and revocation + +A successful create decision is bounded authority, not permanent access. Refresh +requires current project lifetime, entitlement, allocation activity and a valid +caller-policy decision or renewal. Policy revocation, entitlement removal, +allocation release, explicit session deletion or expiry stops refresh and begins +teardown. A new positive decision cannot reactivate a terminal session. + +An unavailable authorizer or allocation reader prevents new admission and authority +extension. It is not evidence of a permanent denial: existing sessions remain +bounded by their last valid freshness deadline and enter recovery/unknown handling +where needed. Do not reset an expired deadline using cached success. Document and +measure the revocation bound as the remaining authority freshness interval plus +allowed clock uncertainty; do not promise instantaneous cancellation across a +partition. Already admitted effects require the lifecycle recovery contract and +must still block reuse until their outcome and teardown are known. + +## Implementation slices and evidence + +| Slice | Changes | Completion evidence | +| --- | --- | --- | +| IAM registration | Session ProtectedResource, Machine capability permission, explicit BMC role, narrow controller grants, separate quota resource under Bare Metal. | Render/packaging checks and role tests prove existing viewer/consumer roles gain no BMC capability. | +| Trusted admission | Milo caller adapter, protected request/decision custody, project-lifetime and target checks, immutable binding. | Original human and service-account decisions succeed; substituted controller identity, forged annotations and foreign targets fail. | +| Limits and fence | Protected project quota, allocation slot, idempotent recovery and lifecycle commit. | Concurrent admissions across two replicas never exceed either limit; crash injection at every partial commit recovers without a second hold or route. | +| Renewal and teardown | Policy renewal, bounded revocation, durable settlement and operator diagnostics. | IAM removal, project recreation, expiry, controller restart and API partition never extend stale authority or free an unverified slot. | +| Live Milo acceptance | Exercise the real project API and IAM/quota adapters with synthetic assets. | Sanitized evidence covers allow, deny, grant removal, boundary isolation and teardown; mock authorizer tests alone do not satisfy this gate. | + +Negative tests must include Machine read without session create; create without +Machine capability; wrong project with an identical Machine name; deleted and +recreated project or Machine; forged principal/receipt; changed key/profile/TTL; +replayed receipt for another session; stale entitlement; unavailable policy API; +concurrent release/admission; and customer deletion during uncertain quota or +projection writes. Dry-run must leave no custody or quota records. + +Audit records correlate principal, consumer project lifetime, request digest, +policy decision, session, allocation, quota intent, admission commit and teardown. +Keep physical identifiers in private records. Metrics expose admission denial +categories, authorization latency, held slots, unknown quota outcomes and teardown +age without principal or Machine identifiers as high-cardinality labels. + +## Dependencies and rollout + +The lifecycle integration work supplies authoritative allocation reads, the shared +commit/effect fence and verified teardown barrier. The Linux E2E work supplies +transport evidence; it does not prove production IAM. Implement registration and +contract tests first, then trusted admission and limits, and finally live Milo +acceptance. Keep production fail-closed until all adapters are available and the +acceptance gates pass. Enable an explicit pilot grant and quota only after that; +existing customers receive no new BMC permissions by default. diff --git a/docs/implementation/secure-bmc-lifecycle.md b/docs/implementation/secure-bmc-lifecycle.md new file mode 100644 index 00000000..544e5c05 --- /dev/null +++ b/docs/implementation/secure-bmc-lifecycle.md @@ -0,0 +1,118 @@ +# Secure BMC lifecycle custody + +Status: implemented library and portable tests; production wiring remains +unavailable. This supplements the [access-path prototype](machine-management-prototype.md) +and does not relax the [proposed product contract](../enhancements/secure-bmc-access.md) +or [pinned provisioning contract](../proposals/fleet-management/bare-metal-provisioning.md). + +## Authoritative inputs and writers + +`controller.LifecycleSessionAuthority` consumes the same `Coordinator` and private +Secret namespace used by standalone allocation, Milo lifecycle integration, and +synthetic staging. It resolves project-scoped claim custody to one bound, +committed asset. Public Machine status, `MachineAllocation` CRDs, and their +`machine-uid`, `member-cluster`, `location-name`, and `provider-project` annotations +are not allocation authority. No parallel allocation writer is introduced. + +The injected `ManagementAccessResolver` must authorize the retained principal for +explicit management access, verify current consumer/provider project lifetimes, +verify the live Machine and namespace lifetimes, and resolve trusted current +capacity/device and location/member observations. Its returned identities must +match retained custody. Refresh repeats resolution; failure terminally revokes +access rather than extending cached authority. Local standalone scope explicitly +uses the namespace lifetime; Milo scope uses canonical project authority and UID. +Missing integrations fail closed. + +Supply an authoritative private-record client with resource-version CAS, not a +public API cache interpreted as authority. Inject the same lifecycle authority +into `SessionReconciler.Lifecycle` and `ProjectionReconciler.Lifecycle`. The current +`fleet-controller` executable defaults to production-unavailable readiness. An +explicit [synthetic fixture mode](synthetic-bmc-fixture.md) injects private grants +and real Coordinator custody for test-only runnable integration; it is not a +production fallback. The manager and +staging handler remain allocation owners, and their shared Coordinator release +path includes this barrier. The projector checks custody on its existing bounded +refresh cadence, without allocation CRD watches or cluster-wide Secret access. + +## Exclusive effects and identities + +New private asset records use schema version 2, pinning Device name and location +alongside capacity UID. Customer Machine UID, capacity UID, physical asset key, +allocation BindingID/epoch, and installation operation identity remain separate. +In the protected binding, `AllocationName` is the asset Secret name and +`AllocationUID` is the allocation BindingID, not a CRD reference. Neither is sent +to the cell or public session. + +Admission CAS-writes the complete binding inputs into the asset before publishing +a binding or admitting projection. That same record owns the active installation +operation. One management session holds the asset effect slot, including Redfish +power/boot operations, until verified teardown. This is deliberately conservative +session-wide serialization, not an independent BMC lock. No general Machine power +controller is added; future power executors must use this same authority boundary. + +Installation requests mark the session revoking and return `ErrManagementActive` +without installation effects. Release CAS-transitions to `AssetReleasing` and +marks revocation before network/provider cleanup, quota settlement or reuse. New +sessions fail admission. CAS selects one winner among management admission, +installation activation and release; no timeout makes uncertain custody available. + +The gateway cancels the stream, drains accepted requests, rejects later requests, +and waits for its runner to exit. The durable journal must show settled successful +effects before cleanup acknowledgment. Pending, unknown, legacy failed effects, +missing session custody or a missing operation directory cannot prove cleanup. +Adapter errors without definitive evidence are Unknown. A different mutation +cannot bypass an unsettled device operation, and queued mutations recheck +authority after acquiring the device lock. + +## Recovery and teardown + +- A crash between asset CAS and binding creation recovers the exact binding, + deadlines, client key and correlation IDs, including during release. Recovery + does not create authority or renew expired deadlines. +- Projection intent is retained before federation Create. A revoked hold with no + admitted projection can settle using that positive private proof. After intent + is retained, an absent projection is unknown, not teardown proof. +- The gateway persists a session marker before route registration and a terminal + revocation marker before cleanup acknowledgment. Replayed Active projections + cannot restart durably revoked sessions. Control markers use the separate + `sessions` journal and are not exposed as Redfish tasks. +- The projector accepts cleanup only with a digest of the exact revoked projection + name/spec, not by comparing unrelated hub and cell generation counters, saving + confirmation on the binding before completing the hold and deleting federation + artifacts. Completion is replayable. Old confirmation cannot modify a newer + allocation/session hold. Public deletion retains its finalizer on timeout. +- Version 1 assets remain readable for lifecycle recovery/release but cannot admit + BMC sessions. No upgrade from mutable annotations is attempted. Older writers + reject version 2 rather than silently dropping holds. Drain old sessions and + upgrade all effect writers before enabling an injected source. Downgrade is not + a supported active-session migration. + +## Validation and production dependencies + +Portable tests cover identity binding without allocation CRDs, missing/denied +authorization, project/namespace/Machine/capacity recreation, device changes, +installation/session and release/session races, competing sessions, exact-input +recovery, projection intent, schema compatibility, stale/unknown teardown, +next-epoch reuse, obsolete completion replay, request draining, journal loss, +and unresolved mutation exclusion. + +```sh +go test ./internal/controller ./internal/gateway ./internal/redfish ./internal/standalone ./internal/manager ./internal/milo ./internal/staging +go test -race ./internal/controller ./internal/gateway ./internal/redfish +bash hack/validate-doc-links.sh +git diff --check +``` + +Production caller-preserving authorization, trusted enrollment/observation and +location registration, deployment wiring, and provider-enforced multi-executor +fencing remain absent. Private CAS and gateway tests establish a single qualified +executor contract only, not cross-replica fencing or hardware completion from an +arbitrary Redfish response. Stable protected journal storage is required. Unknown +operations still need qualified recovery evidence; this change does not auto-clear +tasks or redesign quota, nonce persistence, or general idempotency. + +Pre-bound-CRD E2E fixtures are not an integration source. The +[synthetic fixture executable](synthetic-bmc-fixture.md#exact-harness-recipe) +provides real allocation/release transitions and explicit resolver wiring. The +separate E2E owner integrates those commands into the harness. No Kind/Docker +environment or `hack/e2e` files were changed or run for this integration repair. diff --git a/docs/implementation/synthetic-bmc-fixture.md b/docs/implementation/synthetic-bmc-fixture.md new file mode 100644 index 00000000..f755d54e --- /dev/null +++ b/docs/implementation/synthetic-bmc-fixture.md @@ -0,0 +1,167 @@ +# Synthetic BMC lifecycle fixture + +Status: implemented test-only session-controller wiring and fixture executable. +Portable tests exercise actual private Coordinator custody. This is not a +production authorization adapter, provider observation source, or cleaning proof +for physical hardware. See [lifecycle custody](secure-bmc-lifecycle.md). + +## Wiring and trust boundary + +`fleet-controller` defaults to `--lifecycle-mode=production`: readiness fails and +no lifecycle authority is injected. An unknown mode fails startup. Explicit +`--lifecycle-mode=synthetic --private-namespace=fleet-system` injects the same +`LifecycleSessionAuthority` into both session and projection reconcilers. Its +Coordinator and resolver use an uncached Kubernetes client. The synthetic mode's +readiness indicates configured wiring, not that any particular fixture is ready. +Missing or invalid fixtures still deny session admission. + +The standalone prototype manifest `config/manager/controller.yaml` opts into +synthetic mode. It is not a production overlay. Its RBAC reads namespaces and +reads/lists/updates Secrets only in `fleet-system`; it no longer reads allocation +CRDs. Changing the private namespace requires a corresponding scoped Role and +RoleBinding. The session controller cannot create fixture grants. The fixture +command is an operator tool, run with dedicated test-cluster credentials. + +The fixture command reads existing Machine, MachineCapacity and namespace +lifetimes. It installs the normal Machine protection finalizer, retains an +immutable, private `synthetic-session-*` Secret grant, and calls +`EnsureClaimCustody` and `Allocate`. The grant alone never authorizes a session: +the real committed asset and bound claim custody must agree. The grant pins one +authenticated username, Machine UID/generation, namespace UIDs, capacity +UID/generation, device, location and member route. Every refresh rereads live +objects. Missing/recreated/deleting objects, changed device or generation, or a +different principal fail closed. Re-running allocation with different immutable +grant inputs is rejected. + +Admission, class/profile requirements and current eligible hardware observations +are explicitly synthetic, as in the standalone/staging fixtures. The command +accepts only powered-off, networkless Machines without initial installation. It +constructs synthetic class/profile inputs matching the Machine's reference names; +those objects need not be published. It does not write availability status or use +MachineAllocation annotations. Real Coordinator CAS decides exclusivity even when +the synthetic evidence says capacity is available. + +## Exact harness recipe + +Build alongside the existing plugin and controller images, without needing a new +container or service: + +```sh +go build -o "$E2E_DIR/bin/fleet-session-fixture" ./cmd/fleet-session-fixture +``` + +The E2E owner should apply `config/rbac/controller.yaml` and the prototype manager +manifest, create `fleet-provider`, and apply the Machine and capacity objects. +For example, the management API needs these synthetic objects: + +```yaml +apiVersion: metal.datumapis.com/v1alpha1 +kind: Machine +metadata: {name: db-01, namespace: default} +spec: + machineClassRef: {name: synthetic-libvirt} + machineProfileRef: {name: synthetic-libvirt} + locationRef: {name: location-e2e} + powerState: "Off" +--- +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineCapacity +metadata: {name: db01-capacity, namespace: fleet-provider} +spec: + deviceRef: {name: device-allocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain +``` + +Keep the existing location-local capacity/enrollment fixture aligned with the +capacity name and device. The command does not create provider enrollment or +federation registration. Then allocate: + +```sh +fixture() { + "$E2E_DIR/bin/fleet-session-fixture" --synthetic \ + --kubeconfig "$MGMT_KUBECONFIG" \ + --state "$E2E_DIR/session-executor.json" "$@" +} +fixture --phase=allocate --machine db-01 --capacity db01-capacity \ + --principal system:serviceaccount:default:fleet-authorized \ + --member-cluster fleet-location-e2e +``` + +Defaults are `--namespace=default`, `--capacity-namespace=fleet-provider` and +`--private-namespace=fleet-system`. The principal must be the exact username +retained by admission, not the local kubeconfig context name. Allocation prints +only `machineUID` and `epoch`, not the private fence token. Use equivalent calls +for db-02/db-03 rather than creating or patching MachineAllocation CRDs. + +Retain the operator-local simulator state file outside Git across every retry and +reuse. A nonblocking file lock excludes concurrent fixture processes using the +same state path. Use exactly one state path/host per test environment. The +existing persistent simulator supplies **synthetic provider cleanup only**; it +cannot acknowledge gateway sessions or settle unknown Redfish effects. + +## Release and recreation + +Capture the old Machine UID before deletion. Never infer release authority from +a reused object name: + +```sh +old_machine_uid=$(kubectl --kubeconfig "$MGMT_KUBECONFIG" -n default \ + get machine db-01 -o jsonpath='{.metadata.uid}') +fixture --phase=release --machine db-01 --machine-uid "$old_machine_uid" +``` + +With an active session, that call is expected to exit nonzero with +`management session teardown is not verified`, **after** the Coordinator has +transitioned the asset to Releasing and requested revocation. The harness must +assert this specific blocking result, not suppress arbitrary command errors. +The controller stops refresh, revokes projection, and consumes verified gateway +cleanup. Wait for stream closure and the binding's current-generation +`CleanupConfirmed=True`, then retry the exact command. Only a successful release +with `SafeToRemoveFinalizer=true` runs synthetic cleanup, settles claim custody, +and removes the Machine finalizer. No fixture command fabricates that condition. + +After successful release, delete and recreate the Machine, then run allocation +again with its new UID. Reusing the same capacity retains the physical asset +record and increments its epoch; a different capacity must first finish its own +release. Old session bindings remain pinned to their old allocation and Machine +UID. A released Machine lifetime cannot be reallocated without recreation. + +The E2E owner's script changes are: + +- Replace initial and extra MachineAllocation seed/patch blocks with fixture + allocation commands against the existing capacity objects. +- Replace release status patches with the blocked-release, verified-teardown, + retry sequence above. Preserve the exact old UID through retries. +- Before an `up.sh` reset deletes Machines/capacities, release each retained + allocation. Do not delete Coordinator Secrets, immutable grants, or binding + records to bypass cleanup. Recreate a whole disposable environment when a + deliberate unrecoverable fault prevents a subsequent clean run. +- Run unknown-operation tests last or on dedicated capacity. Unknown/pending + journal entries, missing projection/journal evidence, and unresolved accepted + mutations must block teardown, Machine finalizer removal, and reuse forever + absent qualified recovery evidence. A timed-out proxy or restarted gateway is + not such evidence. Do not restart a new session on the same occupied asset to + escape that barrier. + +## Validation and remaining gaps + +```sh +go test ./cmd/fleet-controller ./cmd/fleet-session-fixture ./internal/staging/sessionfixture ./internal/controller +go test -race ./cmd/fleet-controller ./internal/staging/sessionfixture ./internal/controller +kustomize build config/manager >/dev/null +bash hack/validate-doc-links.sh +git diff --check +``` + +Tests cover actual reconciler admission, principal and object lifetime rejection, +grant-only denial, release blocking, unknown teardown rejection, next-epoch reuse, +and production/default wiring. Lifecycle deadlines are canonicalized to the +Kubernetes timestamp precision before acquisition so returned authority matches +the exact persisted binding even before a second API round trip. + +Full Kind/Karmada/libvirt acceptance belongs to the E2E harness; it is not proved +by these portable tests. Production caller-preserving authorization, trusted +observations, provider-cleanup qualification and multi-executor fencing remain +unimplemented. Synthetic grants must never be used with real customer assets. diff --git a/go.mod b/go.mod index dfd3eb93..0bb8317b 100644 --- a/go.mod +++ b/go.mod @@ -3,15 +3,22 @@ module go.datum.net/fleet go 1.26.4 require ( + github.com/prometheus/client_golang v1.24.0 + github.com/spf13/cobra v1.10.2 + go.datum.net/datumctl v0.18.1 go.datum.net/network-services-operator v0.28.5-0.20260925153938-d7fdc43f8524 + go.miloapis.com/locations v0.0.0-20260825185141-507ac2cbd48c go.miloapis.com/milo v0.32.5 + go.miloapis.com/service-catalog v0.13.1 go.yaml.in/yaml/v3 v3.0.4 golang.org/x/sys v0.47.0 - k8s.io/api v0.36.1 - k8s.io/apimachinery v0.36.1 - k8s.io/client-go v0.36.1 - k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 - sigs.k8s.io/controller-runtime v0.24.1 + k8s.io/api v0.37.2 + k8s.io/apiextensions-apiserver v0.37.0 + k8s.io/apimachinery v0.37.2 + k8s.io/client-go v0.37.2 + k8s.io/utils v0.0.0-20260626114624-be93311217bd + sigs.k8s.io/controller-runtime v0.25.2 + sigs.k8s.io/yaml v1.6.0 ) require ( @@ -21,42 +28,40 @@ require ( github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect - github.com/fxamacker/cbor/v2 v2.9.0 // indirect + github.com/fxamacker/cbor/v2 v2.9.1 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/zapr v1.3.0 // indirect - github.com/go-openapi/jsonpointer v0.23.1 // indirect - github.com/go-openapi/jsonreference v0.21.6 // indirect - github.com/go-openapi/swag v0.25.4 // indirect - github.com/go-openapi/swag/cmdutils v0.25.4 // indirect - github.com/go-openapi/swag/conv v0.26.0 // indirect - github.com/go-openapi/swag/fileutils v0.26.0 // indirect - github.com/go-openapi/swag/jsonname v0.26.0 // indirect - github.com/go-openapi/swag/jsonutils v0.26.0 // indirect - github.com/go-openapi/swag/loading v0.26.0 // indirect - github.com/go-openapi/swag/mangling v0.26.0 // indirect - github.com/go-openapi/swag/netutils v0.25.4 // indirect - github.com/go-openapi/swag/stringutils v0.26.0 // indirect - github.com/go-openapi/swag/typeutils v0.26.0 // indirect - github.com/go-openapi/swag/yamlutils v0.26.0 // indirect + github.com/go-openapi/jsonpointer v1.0.0 // indirect + github.com/go-openapi/jsonreference v1.0.0 // indirect + github.com/go-openapi/swag v0.27.1 // indirect + github.com/go-openapi/swag/cmdutils v0.27.1 // indirect + github.com/go-openapi/swag/conv v0.27.1 // indirect + github.com/go-openapi/swag/fileutils v0.27.1 // indirect + github.com/go-openapi/swag/jsonutils v0.27.1 // indirect + github.com/go-openapi/swag/loading v0.27.1 // indirect + github.com/go-openapi/swag/mangling v0.27.1 // indirect + github.com/go-openapi/swag/netutils v0.27.1 // indirect + github.com/go-openapi/swag/pools v0.27.1 // indirect + github.com/go-openapi/swag/stringutils v0.27.1 // indirect + github.com/go-openapi/swag/typeutils v0.27.1 // indirect + github.com/go-openapi/swag/yamlutils v0.27.1 // indirect github.com/google/gnostic-models v0.7.1 // indirect github.com/google/uuid v1.6.0 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect - github.com/prometheus/client_golang v1.23.2 // indirect github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.67.5 // indirect - github.com/prometheus/procfs v0.20.1 // indirect + github.com/prometheus/common v0.70.0 // indirect + github.com/prometheus/procfs v0.21.1 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/x448/float16 v0.8.4 // indirect - go.miloapis.com/locations v0.0.0-20260825185141-507ac2cbd48c - go.miloapis.com/service-catalog v0.13.1 go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect - golang.org/x/net v0.56.0 // indirect + golang.org/x/net v0.57.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sync v0.22.0 // indirect golang.org/x/term v0.45.0 // indirect @@ -66,12 +71,10 @@ require ( google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/apiextensions-apiserver v0.36.1 // indirect k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/kube-openapi v0.0.0-20260330154417-16be699c7b31 // indirect + k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect sigs.k8s.io/gateway-api v1.5.1 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.3.2 // indirect - sigs.k8s.io/yaml v1.6.0 // indirect + sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect ) diff --git a/go.sum b/go.sum index 4f528831..71398a4c 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,7 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -16,46 +17,46 @@ github.com/evanphx/json-patch/v5 v5.9.11 h1:/8HVnzMq13/3x9TPvjG08wUGqBTmZBsCWzjT github.com/evanphx/json-patch/v5 v5.9.11/go.mod h1:3j+LviiESTElxA4p3EMKAB9HXj3/XEtnUf6OZxqIQTM= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= -github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= -github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= +github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/zapr v1.3.0 h1:XGdV8XW8zdwFiwOA2Dryh1gj2KRQyOOoNmBy4EplIcQ= github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR8/Gg= -github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0ry4d1GWg4= -github.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY= -github.com/go-openapi/jsonreference v0.21.6 h1:NZ5nGfnaM1n4I43Xjm1e5/M2GjOwQwndQz22uhxwD+Y= -github.com/go-openapi/jsonreference v0.21.6/go.mod h1:xzbgtQ3ZbWxvET3AxdzCJlJt6vkovbf+IfSPJjD0tUY= -github.com/go-openapi/swag v0.25.4 h1:OyUPUFYDPDBMkqyxOTkqDYFnrhuhi9NR6QVUvIochMU= -github.com/go-openapi/swag v0.25.4/go.mod h1:zNfJ9WZABGHCFg2RnY0S4IOkAcVTzJ6z2Bi+Q4i6qFQ= -github.com/go-openapi/swag/cmdutils v0.25.4 h1:8rYhB5n6WawR192/BfUu2iVlxqVR9aRgGJP6WaBoW+4= -github.com/go-openapi/swag/cmdutils v0.25.4/go.mod h1:pdae/AFo6WxLl5L0rq87eRzVPm/XRHM3MoYgRMvG4A0= -github.com/go-openapi/swag/conv v0.26.0 h1:5yGGsPYI1ZCva93U0AoKi/iZrNhaJEjr324YVsiD89I= -github.com/go-openapi/swag/conv v0.26.0/go.mod h1:tpAmIL7X58VPnHHiSO4uE3jBeRamGsFsfdDeDtb5ECE= -github.com/go-openapi/swag/fileutils v0.26.0 h1:WJoPRvsA7QRiiWluowkLJa9jaYR7FCuxmDvnCgaRRxU= -github.com/go-openapi/swag/fileutils v0.26.0/go.mod h1:0WDJ7lp67eNjPMO50wAWYlKvhOb6CQ37rzR7wrgI8Tc= -github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w= -github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M= -github.com/go-openapi/swag/jsonutils v0.26.0 h1:FawFML2iAXsPqmERscuMPIHmFsoP1tOqWkxBaKNMsnA= -github.com/go-openapi/swag/jsonutils v0.26.0/go.mod h1:2VmA0CJlyFqgawOaPI9psnjFDqzyivIqLYN34t9p91E= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0 h1:apqeINu/ICHouqiRZbyFvuDge5jCmmLTqGQ9V95EaOM= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.26.0/go.mod h1:AyM6QT8uz5IdKxk5akv0y6u4QvcL9GWERt0Jx/F/R8Y= -github.com/go-openapi/swag/loading v0.26.0 h1:Apg6zaKhCJurpJer0DCxq99qwmhFddBhaMX7kilDcko= -github.com/go-openapi/swag/loading v0.26.0/go.mod h1:dBxQ/6V2uBaAQdevN18VELE6xSpJWZxLX4txe12JwDg= -github.com/go-openapi/swag/mangling v0.26.0 h1:Du2YC4YLA/Y5m/YKQd7AnY5qq0wRKSFZTTt8ktFaXcQ= -github.com/go-openapi/swag/mangling v0.26.0/go.mod h1:jifS7W9vbg+pw63bT+GI53otluMQL3CeemuyCHKwVx0= -github.com/go-openapi/swag/netutils v0.25.4 h1:Gqe6K71bGRb3ZQLusdI8p/y1KLgV4M/k+/HzVSqT8H0= -github.com/go-openapi/swag/netutils v0.25.4/go.mod h1:m2W8dtdaoX7oj9rEttLyTeEFFEBvnAx9qHd5nJEBzYg= -github.com/go-openapi/swag/stringutils v0.26.0 h1:qZQngLxs5s7SLijc3N2ZO+fUq2o8LjuWAASSrJuh+xg= -github.com/go-openapi/swag/stringutils v0.26.0/go.mod h1:sWn5uY+QIIspwPhvgnqJsH8xqFT2ZbYcvbcFanRyhFE= -github.com/go-openapi/swag/typeutils v0.26.0 h1:2kdEwdiNWy+JJdOvu5MA2IIg2SylWAFuuyQIKYybfq4= -github.com/go-openapi/swag/typeutils v0.26.0/go.mod h1:oovDuIUvTrEHVMqWilQzKzV4YlSKgyZmFh7AlfABNVE= -github.com/go-openapi/swag/yamlutils v0.26.0 h1:H7O8l/8NJJQ/oiReEN+oMpnGMyt8G0hl460nRZxhLMQ= -github.com/go-openapi/swag/yamlutils v0.26.0/go.mod h1:1evKEGAtP37Pkwcc7EWMF0hedX0/x3Rkvei2wtG/TbU= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2 h1:5zRca5jw7lzVREKCZVNBpysDNBjj74rBh0N2BGQbSR0= -github.com/go-openapi/testify/enable/yaml/v2 v2.4.2/go.mod h1:XVevPw5hUXuV+5AkI1u1PeAm27EQVrhXTTCPAF85LmE= -github.com/go-openapi/testify/v2 v2.5.1 h1:TMdhCaw8fUNraVSf3Omoob1dO/AzBfhtFAPW0an6sBo= -github.com/go-openapi/testify/v2 v2.5.1/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= +github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= +github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= +github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= +github.com/go-openapi/swag v0.27.1 h1:VotvOLWW8q/EAxB0YdsBBGC8XYyeL1YwBj2ungAGPNg= +github.com/go-openapi/swag v0.27.1/go.mod h1:GTkJPwHfhJp6MWr4/rCh64HVI3Ofu+tcsbfjfHmTxpE= +github.com/go-openapi/swag/cmdutils v0.27.1 h1:I7sYqaWVl5mq0NEmNQkAmFDyNin9ufvMX/p2zwtQaOE= +github.com/go-openapi/swag/cmdutils v0.27.1/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= +github.com/go-openapi/swag/conv v0.27.1 h1:8wi9ZG+olmY1wXphl93EWniPtbSPkXM/feH7FgjsvrU= +github.com/go-openapi/swag/conv v0.27.1/go.mod h1:QbqMivkpKhC3g1B1GGGOJ6ANewI3S62dbzYu3Duowqs= +github.com/go-openapi/swag/fileutils v0.27.1 h1:QQqBSoi5mW4XpU85nS0mLcA+zAE6vLzrb0QkmLKf9oM= +github.com/go-openapi/swag/fileutils v0.27.1/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= +github.com/go-openapi/swag/jsonutils v0.27.1 h1:SVgK3i4USzCU5mibOOS/l4ea2h9UQXy7J7RNLTjuXjU= +github.com/go-openapi/swag/jsonutils v0.27.1/go.mod h1:tdlEpZqdcQ17uj6J4YdK9vd8It5qWMwjWXOs0tjpRlk= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.1 h1:mJu3COL9WEaZVp/Kf2PRMi7tPszPEJfSr/OO75ynCs8= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.27.1/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY= +github.com/go-openapi/swag/loading v0.27.1 h1:/DxUgDXKbBX4bcn7r9uEXfJyzN5XpiJmZplzQTjrRCY= +github.com/go-openapi/swag/loading v0.27.1/go.mod h1:jvGh3iA2+zyUUycB5fgJWzeHnhrpvGnJJM0RVE9ZShE= +github.com/go-openapi/swag/mangling v0.27.1 h1:yC9D0HyUE8gbP+BfmGx9+AA89ikwZTMjESK3OnnoaqA= +github.com/go-openapi/swag/mangling v0.27.1/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= +github.com/go-openapi/swag/netutils v0.27.1 h1:mICMFoS82F5TZ4Zy3cqmcQk+BFeCp3Uyq3Np7GI0/qU= +github.com/go-openapi/swag/netutils v0.27.1/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= +github.com/go-openapi/swag/pools v0.27.1 h1:9LeadcMyb2GJCbXX5hVQDbZ2Lq9TL4dCs/nx1j5DO0E= +github.com/go-openapi/swag/pools v0.27.1/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE= +github.com/go-openapi/swag/stringutils v0.27.1 h1:ZXePZ0r2p1qSjo8tD3Un4vFj8+FqlCkczxDrJIhYUp8= +github.com/go-openapi/swag/stringutils v0.27.1/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= +github.com/go-openapi/swag/typeutils v0.27.1 h1:KSTdFlfnse4r6dP9IrEnwMldjE+zs71UeEB3//PtVXc= +github.com/go-openapi/swag/typeutils v0.27.1/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ= +github.com/go-openapi/swag/yamlutils v0.27.1 h1:ftxv6xvXb1E3zohUc+okZ9nSqNb9StQX/FXnKZ98sQA= +github.com/go-openapi/swag/yamlutils v0.27.1/go.mod h1:bnxFIB1qewGRiZHypXGZ3fNgf13/0HfRgnS/iZBDrOo= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0= +github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo= +github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug= +github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= @@ -69,10 +70,12 @@ github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 h1:z2ogiKUYzX5Is6zr/v github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao= -github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ= +github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -94,26 +97,32 @@ github.com/onsi/gomega v1.39.1/go.mod h1:hL6yVALoTOxeWudERyfppUcZXjMwIMLnuSfruD2 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_golang v1.24.0 h1:5XStIklKuAtJSNpdD3s8XJj/Yv78IQmE1kbNk87JrAI= +github.com/prometheus/client_golang v1.24.0/go.mod h1:QcsNdotprC2nS4BTM2ucbcqxd2CeXTEa9jW7zHO9iDE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4= -github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw= -github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc= -github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo= +github.com/prometheus/common v0.70.0 h1:bcpru3tWPVnxGnETLgOV5jbp/JRXgYEyv65CuBLAMMI= +github.com/prometheus/common v0.70.0/go.mod h1:S/SFasQmgGiYH6C81LKCtYa8QACgthGg5zxL2udV7SY= +github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= +github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= +github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= +github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= -github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= +github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +go.datum.net/datumctl v0.18.1 h1:MP83cRkJ94aq4lYyOm5dSLU60JNnmR486LIeZnaCw8s= +go.datum.net/datumctl v0.18.1/go.mod h1:0L0BBgFfud8ZuV9sbsSmeEBUPoK2q9g4boU5yczF92o= go.datum.net/network-services-operator v0.28.5-0.20260925153938-d7fdc43f8524 h1:hMRoDncUDd29dFZik7fuWruLvmPAF/Sb/yvMWqNTNFA= go.datum.net/network-services-operator v0.28.5-0.20260925153938-d7fdc43f8524/go.mod h1:XbNdfc6aVeNcALsczJ/MJ1RiDJqE57SlPjQSquH3fzk= go.miloapis.com/locations v0.0.0-20260825185141-507ac2cbd48c h1:+BQirT3wYCgv7H2lEZtAH+dpMiWu9j/Wa+c8s4jJUIA= @@ -134,8 +143,8 @@ go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= -golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= -golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= @@ -163,29 +172,29 @@ gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -k8s.io/api v0.36.1 h1:XbL/EMj8K2aJpJtePmqUyQMsM0D4QI2pvl7YKJ20FTY= -k8s.io/api v0.36.1/go.mod h1:KOWo4ey3TINlXjeHVuwB3i+tXXnu+UcwFBHlI/9dvEo= -k8s.io/apiextensions-apiserver v0.36.1 h1:6JfYmPUsuUIHuN+3QxutXYWj492RqF5fBSx67GYK5Ks= -k8s.io/apiextensions-apiserver v0.36.1/go.mod h1:pLzZin90riwisdzKwv/GoTwENooytoIx5zWJb4Hkby8= -k8s.io/apimachinery v0.36.1 h1:G63Gjx2W+q0YD+72Vo8oY0nDnePVwnuzTmmy5ENrVSA= -k8s.io/apimachinery v0.36.1/go.mod h1:ibYOR00vW/I1kzvi5SF0dRuJ52BvKtfvRdOn35GPQ+8= -k8s.io/client-go v0.36.1 h1:FN/K8QIT2CEDt+2WB2HnWrUANZ50AP5GII43/SP2JR0= -k8s.io/client-go v0.36.1/go.mod h1:s6rAnCtTGYDQnpNjEhSaISV+2O8jwruZ6m3QOYBFbtU= +k8s.io/api v0.37.2 h1:PnxqnUFy93jr2GcpWDkKOm8wfy25kT9wa572MuQS8oc= +k8s.io/api v0.37.2/go.mod h1:+NVRLft99kx+Jg9v34GmHw867Dapim89TSyCsn2hK+M= +k8s.io/apiextensions-apiserver v0.37.0 h1:zRMQ3+/LIE5oZ0tVvXwYHC+dIkSP5cjNWju7AZU1LOI= +k8s.io/apiextensions-apiserver v0.37.0/go.mod h1:HU0PfSBwchHL5iDau6jjt9zU6ryWkDDlaVUiq91NK80= +k8s.io/apimachinery v0.37.2 h1:G4t9RGoPDbQML38hz/kQQiltttgd3egg2ODCR8aIc2o= +k8s.io/apimachinery v0.37.2/go.mod h1:qaAvSNvgU2x07wRM95MSHSJTPQ/ob/LeNAGbeDgqQJg= +k8s.io/client-go v0.37.2 h1:sgFtyRZukGkOrsu+QgS7LYnbFFJ5ut3MchdBNduD//E= +k8s.io/client-go v0.37.2/go.mod h1:bo3LFC8YbCtKFPX21Yj8puMsoJLAv/+SvuOODma0s54= k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -k8s.io/kube-openapi v0.0.0-20260330154417-16be699c7b31 h1:V+sn9a/1fEYDGwnllCmqXBk8x7obZ+hl869Q3Abumkg= -k8s.io/kube-openapi v0.0.0-20260330154417-16be699c7b31/go.mod h1:uGBT7iTA6c6MvqUvSXIaYZo9ukscABYi2btjhvgKGZ0= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5 h1:kBawHLSnx/mYHmRnNUf9d4CpjREbeZuxoSGOX/J+aYM= -k8s.io/utils v0.0.0-20260319190234-28399d86e0b5/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -sigs.k8s.io/controller-runtime v0.24.1 h1:miPEwrmirImAvgME1L9qebGHrOnGJoVmVdtOU9fRfo4= -sigs.k8s.io/controller-runtime v0.24.1/go.mod h1:vFkfY5fGt5xAC/sKb8IBFKgWPNKG9OUG29dR8Y2wImw= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad h1:oXImqH8mQNk7PmvzKhmN3ddJoY6OnyM225MXwGHPm0A= +k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad/go.mod h1:0/mqHCVhlumdJ3BhCfnjSZQE037nAhNodh1/hK0T8/I= +k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= +k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= +sigs.k8s.io/controller-runtime v0.25.2 h1:bEkK3PVOIVK9X8QWLGVhJgmFc++47vfT6wakSzAOLsQ= +sigs.k8s.io/controller-runtime v0.25.2/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= sigs.k8s.io/gateway-api v1.5.1 h1:RqVRIlkhLhUO8wOHKTLnTJA6o/1un4po4/6M1nRzdd0= sigs.k8s.io/gateway-api v1.5.1/go.mod h1:GvCETiaMAlLym5CovLxGjS0NysqFk3+Yuq3/rh6QL2o= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= sigs.k8s.io/randfill v1.0.0 h1:JfjMILfT8A6RbawdsK2JXGBR5AQVfd+9TbzrlneTyrU= sigs.k8s.io/randfill v1.0.0/go.mod h1:XeLlZ/jmk4i1HRopwe7/aU3H5n1zNUcX6TM94b3QxOY= -sigs.k8s.io/structured-merge-diff/v6 v6.3.2 h1:kwVWMx5yS1CrnFWA/2QHyRVJ8jM6dBA80uLmm0wJkk8= -sigs.k8s.io/structured-merge-diff/v6 v6.3.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= +sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= diff --git a/hack/e2e/common.sh b/hack/e2e/common.sh new file mode 100644 index 00000000..5d7e76a9 --- /dev/null +++ b/hack/e2e/common.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash + +fail() { echo "FAIL: $*" >&2; exit 1; } + +wait_for() { + local description=$1 command=$2 process_id=${3:-} + local deadline=$((SECONDS + ${FLEET_E2E_WAIT_SECONDS:-240})) + while (( SECONDS < deadline )); do + if [[ -n "${process_id}" ]] && ! kill -0 "${process_id}" 2>/dev/null; then + fail "${description}: process ${process_id} exited before readiness; inspect proxy logs" + fi + eval "${command}" && return 0 + sleep 1 + done + fail "timed out waiting for ${description}" +} + +run_timeout() { + local seconds=$1 + shift + if command -v timeout >/dev/null; then timeout "${seconds}" "$@"; return; fi + if command -v gtimeout >/dev/null; then gtimeout "${seconds}" "$@"; return; fi + perl -e '$seconds = shift; alarm $seconds; exec @ARGV' "${seconds}" "$@" +} + +checkpoint() { + printf '%s PASS: %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$*" | tee -a "${E2E_DIR}/checkpoints.log" +} + +sessions_absent() { + local kubeconfig=$1 namespace=$2 resource=$3 objects + objects=$(kubectl --request-timeout=10s --kubeconfig "${kubeconfig}" -n "${namespace}" get "${resource}" -o json) || return 1 + jq -e '(.items | type == "array") and (.items | length == 0)' <<<"${objects}" >/dev/null +} + +validator_coverage() { + awk -F '[:,]' ' + /^ - Pass:/ { resources++; passed += $2; warnings += $4; failed += $6 } + END { exit !(resources > 0 && passed > 0 && warnings == 0 && failed == 0) } + ' "$1" +} diff --git a/hack/e2e/diagnostics.sh b/hack/e2e/diagnostics.sh new file mode 100755 index 00000000..e4f7f224 --- /dev/null +++ b/hack/e2e/diagnostics.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +OUT="${E2E_DIR}/diagnostics/$(date -u +%Y%m%dT%H%M%SZ)" +mkdir -p "${OUT}" +source "${ROOT_DIR}/hack/e2e/common.sh" +for cluster in management location; do + kubeconfig="${E2E_DIR}/${cluster}.kubeconfig" + if [[ -f "${kubeconfig}" ]]; then + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" get all,events -A -o wide >"${OUT}/${cluster}-resources.txt" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" get pods -A -o json >"${OUT}/${cluster}-pods.json" 2>&1 || true + for resource in machines machinecapacities machineallocations machinemanagementsessions machinemanagementsessionbindings projectedmachinemanagementsessions; do + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" get "${resource}" -A -o yaml >"${OUT}/${cluster}-${resource}.yaml" 2>&1 || true + done + if [[ "${cluster}" == management ]]; then + workloads='fleet-system/fleet-controller karmada-system/karmada-controller-manager karmada-system/karmada-apiserver karmada-system/karmada-kube-controller-manager' + else + workloads='machine-access-system/fleet-gateway machine-access-system/fleet-relay' + fi + for workload in ${workloads}; do + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" -n "${workload%/*}" logs "deployment/${workload#*/}" \ + --all-containers --prefix --timestamps --tail=2000 >"${OUT}/${cluster}-${workload#*/}.log" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" -n "${workload%/*}" logs "deployment/${workload#*/}" \ + --all-containers --previous --prefix --timestamps --tail=500 >"${OUT}/${cluster}-${workload#*/}-previous.log" 2>&1 || true + done + if [[ "${cluster}" == location ]]; then + run_timeout 15 kubectl --request-timeout=5s --kubeconfig "${kubeconfig}" -n machine-access-system exec deployment/fleet-gateway -- \ + sh -c 'for f in /var/lib/fleet/operations/*.json; do test -f "$f" && { echo "$f"; cat "$f"; }; done' \ + >"${OUT}/operation-journal.jsonl" 2>&1 || true + fi + fi +done +if [[ -f "${E2E_DIR}/karmada.kubeconfig" ]]; then + kubectl --request-timeout=5s --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get clusters,works.work.karmada.io,resourcebindings.work.karmada.io -A -o yaml >"${OUT}/karmada-resources.yaml" 2>&1 || true + kubectl --request-timeout=5s --kubeconfig "${E2E_DIR}/karmada.kubeconfig" get projectedmachinemanagementsessions,propagationpolicies -A -o yaml >"${OUT}/karmada-fleet.yaml" 2>&1 || true +fi +docker logs fleet-e2e-virtual-bmc >"${OUT}/virtual-bmc.log" 2>&1 || true +docker exec fleet-e2e-virtual-bmc virsh list --all >"${OUT}/libvirt-domains.txt" 2>&1 || true +docker exec fleet-e2e-virtual-bmc virsh dumpxml allocated >"${OUT}/allocated-domain.xml" 2>&1 || true +if [[ -d "${E2E_DIR}/virtual-bmc/evidence" ]]; then + mkdir -p "${OUT}/evidence" + for evidence in acceleration.txt allocated-console.log pxe-callbacks.jsonl libvirtd.log virtlogd.log; do + docker cp "fleet-e2e-virtual-bmc:/evidence/${evidence}" "${OUT}/evidence/${evidence}" 2>/dev/null || true + done + cp "${E2E_DIR}/virtual-bmc/evidence/pxe-operation-correlation.json" "${OUT}/evidence/" 2>/dev/null || true +fi +echo "diagnostics: ${OUT}" diff --git a/hack/e2e/down.sh b/hack/e2e/down.sh new file mode 100755 index 00000000..29b91784 --- /dev/null +++ b/hack/e2e/down.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" +kind delete cluster --name fleet-management-e2e 2>/dev/null || true +kind delete cluster --name fleet-location-e2e 2>/dev/null || true +docker compose -p fleet-bmc-e2e -f "${TEST_DIR}/compose.yaml" down --remove-orphans 2>/dev/null || true +docker network rm fleet-management-e2e 2>/dev/null || true +case "${E2E_DIR}" in + "${ROOT_DIR}/.e2e") rm -rf -- "${E2E_DIR}" ;; + *) echo "refusing to remove unexpected path ${E2E_DIR}" >&2; exit 1 ;; +esac diff --git a/hack/e2e/lifecycle.sh b/hack/e2e/lifecycle.sh new file mode 100644 index 00000000..8a347a87 --- /dev/null +++ b/hack/e2e/lifecycle.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash + +fixture() { + "${E2E_DIR}/bin/fleet-session-fixture" --synthetic --kubeconfig "${MGMT_KUBECONFIG}" \ + --state "${E2E_DIR}/session-executor.json" "$@" +} + +allocate_fixture() { + fixture --phase=allocate --machine "$1" --capacity "$2" \ + --principal system:serviceaccount:default:fleet-authorized --member-cluster fleet-location-e2e +} + +binding_clean() { + local binding=$1 object + object=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system \ + get machinemanagementsessionbinding "${binding}" -o json) || return 1 + jq -e '.metadata.generation as $generation | any(.status.conditions[]?; + .type == "CleanupConfirmed" and .status == "True" and .observedGeneration == $generation)' <<<"${object}" >/dev/null +} + +asset_state() { + local uid=$1 state=$2 objects + objects=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system \ + get secrets -l fleet.datumapis.com/private-record=asset -o json) || return 1 + jq -e --arg uid "${uid}" --arg state "${state}" ' + [.items[].data["record.json"] | @base64d | fromjson | select(.claimUID == $uid)] | + length == 1 and all(.[]; .state == $state)' <<<"${objects}" >/dev/null +} + +release_blocked() { + local machine=$1 uid=$2 + if fixture --phase=release --machine "${machine}" --machine-uid "${uid}" \ + >"${E2E_DIR}/release-${machine}.json" 2>"${E2E_DIR}/release-${machine}.log"; then + fail "release of ${machine} bypassed active management custody" + fi + grep -q 'management session teardown is not verified' "${E2E_DIR}/release-${machine}.log" || fail "unexpected release failure for ${machine}" + jq -e '.State == "Releasing" and .SafeToRemoveFinalizer == false' "${E2E_DIR}/release-${machine}.json" >/dev/null || fail "release did not report blocked custody" + asset_state "${uid}" Releasing || fail "release did not durably mark asset Releasing" +} + +release_fixture() { + local machine=$1 uid=$2 bindings binding + if fixture --phase=release --machine "${machine}" --machine-uid "${uid}" \ + >"${E2E_DIR}/release-${machine}.json" 2>"${E2E_DIR}/release-${machine}.log"; then + jq -e '.SafeToRemoveFinalizer == true' "${E2E_DIR}/release-${machine}.json" >/dev/null + return + fi + grep -q 'management session teardown is not verified' "${E2E_DIR}/release-${machine}.log" || fail "unexpected release failure for ${machine}" + bindings=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -o json | + jq -r --arg uid "${uid}" '.items[] | select(.spec.machineUID == $uid) | .metadata.name') || return 1 + for binding in ${bindings}; do + wait_for "verified teardown for ${binding}; unresolved custody requires whole disposable environment teardown" "binding_clean '${binding}'" + done + fixture --phase=release --machine "${machine}" --machine-uid "${uid}" >"${E2E_DIR}/release-${machine}.json" + jq -e '.SafeToRemoveFinalizer == true' "${E2E_DIR}/release-${machine}.json" >/dev/null +} diff --git a/hack/e2e/openvpn-up.sh b/hack/e2e/openvpn-up.sh new file mode 100755 index 00000000..9c715b9f --- /dev/null +++ b/hack/e2e/openvpn-up.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" +export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" +[[ $(uname -s) == Linux ]] || { echo "OpenVPN qualification requires Linux" >&2; exit 1; } +[[ -f "${LOCATION_KUBECONFIG}" ]] || { echo "run task e2e:up first" >&2; exit 1; } + +docker compose -p fleet-bmc-e2e -f "${TEST_DIR}/compose.yaml" -f "${TEST_DIR}/compose.openvpn.yaml" up -d --build --force-recreate virtual-bmc +for _ in $(seq 1 60); do [[ -s "${FLEET_E2E_STATE}/evidence/openvpn.key" ]] && break; sleep 1; done +[[ -s "${FLEET_E2E_STATE}/evidence/openvpn.key" ]] || { echo "OpenVPN server key was not created" >&2; exit 1; } +docker build -t fleet-openvpn-client:e2e "${TEST_DIR}/openvpn" +kind load docker-image fleet-openvpn-client:e2e --name fleet-location-e2e +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-openvpn-key \ + --from-file=openvpn.key="${FLEET_E2E_STATE}/evidence/openvpn.key" --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${TEST_DIR}/openvpn/client.yaml" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status daemonset/fleet-openvpn-client --timeout=120s +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch secret enrollment-device-allocated --type=merge \ + -p="{\"stringData\":{\"endpoint\":\"http://10.88.0.1:8000\"}}" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout restart deployment/fleet-gateway +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s +pod=$(kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system get pod -l app.kubernetes.io/name=fleet-openvpn-client -o jsonpath='{.items[0].metadata.name}') +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system exec "${pod}" -- curl --fail --silent http://10.88.0.1:8000/redfish/v1/Systems >/dev/null +if kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system exec "${pod}" -- curl --fail --silent --connect-timeout 2 http://172.30.0.10:8000/redfish/v1/Systems >/dev/null 2>&1; then + echo "direct management route remained reachable in OpenVPN profile" >&2 + exit 1 +fi +echo "OpenVPN management boundary: PASS" diff --git a/hack/e2e/prepare-schemas.sh b/hack/e2e/prepare-schemas.sh new file mode 100755 index 00000000..261a9ba1 --- /dev/null +++ b/hack/e2e/prepare-schemas.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +SCHEMA_DIR="${ROOT_DIR}/.e2e/redfish-schemas" +REVISION=4f81814e399213c9055863ddaff42791c6b3706a +SHA256=48d1c587676f2b03d5589825653d8924d0fee67d963c5de5ba411e9a3b4b4068 +ARCHIVE="${ROOT_DIR}/.e2e/redfish-publications-${REVISION}.tar.gz" +mkdir -p "${SCHEMA_DIR}" +if [[ ! -f "${ARCHIVE}" ]]; then + curl --fail --silent --show-error --location --retry 3 --max-time 180 \ + "https://codeload.github.com/DMTF/Redfish-Publications/tar.gz/${REVISION}" -o "${ARCHIVE}.download" + mv "${ARCHIVE}.download" "${ARCHIVE}" +fi +actual=$(openssl dgst -sha256 "${ARCHIVE}" | awk '{print $NF}') +[[ "${actual}" == "${SHA256}" ]] || { echo "DMTF schema archive checksum mismatch: ${ARCHIVE}" >&2; exit 1; } +rm -rf "${SCHEMA_DIR}" +mkdir -p "${SCHEMA_DIR}" +tar -xzf "${ARCHIVE}" --strip-components=2 -C "${SCHEMA_DIR}" "Redfish-Publications-${REVISION}/csdl" +printf 'DMTF Redfish-Publications 2026.2\nrevision=%s\narchive_sha256=%s\n' "${REVISION}" "${SHA256}" >"${SCHEMA_DIR}/provenance.txt" +echo "Pinned DMTF CSDL schemas: ${SCHEMA_DIR}" diff --git a/hack/e2e/test-common.sh b/hack/e2e/test-common.sh new file mode 100755 index 00000000..e0c75d2c --- /dev/null +++ b/hack/e2e/test-common.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +set -euo pipefail +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +source "${ROOT_DIR}/hack/e2e/common.sh" +source "${ROOT_DIR}/hack/e2e/lifecycle.sh" + +wait_for "immediate success" true +if (FLEET_E2E_WAIT_SECONDS=1 wait_for "bounded failure" false) 2>/dev/null; then + fail "failed predicate passed" +fi +if (wait_for "dead proxy with stale ready file" true 2147483647) 2>/dev/null; then + fail "dead proxy accepted stale readiness" +fi +kubectl() { return 1; } +if sessions_absent ignored default sessions; then + fail "API failure counted as confirmed deletion" +fi +kubectl() { printf '%s\n' '{"items":[{"metadata":{"name":"retained"}}]}'; } +if sessions_absent ignored default sessions; then + fail "existing session counted as deleted" +fi +kubectl() { printf '%s\n' '{"items":[]}'; } +sessions_absent ignored default sessions +kubectl() { printf '%s\n' '{}'; } +if sessions_absent ignored default sessions; then + fail "missing list evidence counted as confirmed deletion" +fi +run_timeout 2 bash -c 'exit 0' +if run_timeout 1 bash -c 'sleep 5'; then + fail "timeout failed to stop command" +fi +report=$(mktemp) +trap 'rm -f "${report}"' EXIT +for summary in '' ' - Pass: 0, Warn: 0, Fail: 0, Skip: 0' ' - Pass: 0, Warn: 1, Fail: 0, Skip: 0' ' - Pass: 1, Warn: 1, Fail: 0, Skip: 0' ' - Pass: 1, Warn: 0, Fail: 1, Skip: 0'; do + printf '%s\n' "${summary}" >"${report}" + if validator_coverage "${report}"; then + fail "incomplete validator coverage accepted: ${summary}" + fi +done +printf '%s\n' ' - Pass: 12, Warn: 0, Fail: 0, Skip: 35' >"${report}" +validator_coverage "${report}" +MGMT_KUBECONFIG=ignored +kubectl() { return 1; } +if binding_clean binding; then fail "API failure counted as verified teardown"; fi +kubectl() { printf '%s\n' '{"metadata":{"generation":2},"status":{"conditions":[{"type":"CleanupConfirmed","status":"True","observedGeneration":1}]}}'; } +if binding_clean binding; then fail "old generation counted as verified teardown"; fi +kubectl() { printf '%s\n' '{"metadata":{"generation":2},"status":{"conditions":[{"type":"CleanupConfirmed","status":"Unknown","observedGeneration":2}]}}'; } +if binding_clean binding; then fail "unknown counted as verified teardown"; fi +kubectl() { printf '%s\n' '{"metadata":{"generation":2},"status":{"conditions":[{"type":"CleanupConfirmed","status":"True","observedGeneration":2}]}}'; } +binding_clean binding +kubectl() { printf '%s\n' '{"items":[]}'; } +if asset_state uid Releasing; then fail "missing custody counted as occupied"; fi +kubectl() { return 1; } +if asset_state uid Releasing; then fail "API failure counted as occupied custody"; fi +echo 'E2E harness helpers: PASS' diff --git a/hack/e2e/test.sh b/hack/e2e/test.sh new file mode 100755 index 00000000..b2e822f2 --- /dev/null +++ b/hack/e2e/test.sh @@ -0,0 +1,387 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +MGMT_KUBECONFIG="${E2E_DIR}/management.kubeconfig" +LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" +KARMADA_KUBECONFIG="${E2E_DIR}/karmada.kubeconfig" +PATH="${E2E_DIR}/bin:${PATH}" +export PATH +source "${ROOT_DIR}/hack/e2e/common.sh" +source "${ROOT_DIR}/hack/e2e/lifecycle.sh" +rm -f "${E2E_DIR}/checkpoints.log" "${E2E_DIR}/viewer-ready.json" "${E2E_DIR}/ready-2.json" + +for file in "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" "${KARMADA_KUBECONFIG}" "${E2E_DIR}/management-ca.crt"; do + [[ -f "${file}" ]] || { echo "missing ${file}; run task e2e:up" >&2; exit 1; } +done +# Each run must prove a new boot rather than accepting evidence left by an +# earlier invocation against the same idempotent environment. +rm -f "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" \ + "${E2E_DIR}/virtual-bmc/evidence/pxe-operation-correlation.json" \ + "${E2E_DIR}/virtual-bmc/evidence/allocated-console.log" + +# Docker may run in a VM whose bind mount is not mirrored to this client. +# Reset evidence at its writer as well as the local exported copy. +docker exec fleet-e2e-virtual-bmc rm -f /evidence/pxe-callbacks.jsonl /evidence/pxe-operation-correlation.json /evidence/allocated-console.log + +proxy_pid= +second_proxy_pid= +management_paused=false +location_paused=false +bmc_blocked=false +cleanup() { + local result=$? + if [[ ${result} -ne 0 ]]; then run_timeout 90 "${ROOT_DIR}/hack/e2e/diagnostics.sh" || true; fi + if [[ -n "${proxy_pid}" ]]; then kill -TERM "${proxy_pid}" 2>/dev/null || true; wait "${proxy_pid}" 2>/dev/null || true; fi + if [[ -n "${second_proxy_pid}" ]]; then kill -TERM "${second_proxy_pid}" 2>/dev/null || true; wait "${second_proxy_pid}" 2>/dev/null || true; fi + if [[ "${management_paused}" == true ]]; then docker unpause fleet-management-e2e-control-plane >/dev/null 2>&1 || true; fi + if [[ "${location_paused}" == true ]]; then docker unpause fleet-location-e2e-control-plane >/dev/null 2>&1 || true; fi + if [[ "${bmc_blocked}" == true ]]; then docker exec fleet-e2e-virtual-bmc iptables -D INPUT -p tcp --dport 8000 -s 172.30.0.20 -j REJECT >/dev/null 2>&1 || true; fi +} +trap cleanup EXIT +file_mode() { + if stat -c %a "$1" >/dev/null 2>&1; then stat -c %a "$1"; else stat -f %Lp "$1"; fi +} + +api_server=$(kubectl config view --kubeconfig "${MGMT_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.server}') + +# A Machine reader cannot create a management session. This invokes datumctl's +# actual plugin discovery/dispatch and credential-helper path. +set +e +HOME="${E2E_DIR}/home-viewer" datumctl fleet machine-management proxy db-01 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" \ + --ready-file "${E2E_DIR}/viewer-ready.json" >"${E2E_DIR}/viewer.log" 2>&1 +viewer_status=$? +set -e +[[ ${viewer_status} -eq 11 ]] || fail "Machine-read-only principal exit=${viewer_status}, expected permission exit 11" +[[ ! -e "${E2E_DIR}/viewer-ready.json" ]] || fail "unauthorized principal received a local endpoint" + +start_proxy() { + local ttl=${1:-15m} + local attempt + attempt=$(date -u '+%Y%m%dT%H%M%SZ') + [[ ! -f "${E2E_DIR}/proxy.log" ]] || cp "${E2E_DIR}/proxy.log" "${E2E_DIR}/proxy-${attempt}.log" + rm -f "${E2E_DIR}/ready.json" "${E2E_DIR}/credentials.json" "${E2E_DIR}/ca.pem" + DATUM_TOKEN=must-not-be-used HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-01 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" \ + --listen 127.0.0.1:9443 --ttl "${ttl}" \ + --ready-file "${E2E_DIR}/ready.json" --credential-file "${E2E_DIR}/credentials.json" \ + --ca-file "${E2E_DIR}/ca.pem" >"${E2E_DIR}/proxy.log" 2>&1 & + proxy_pid=$! + wait_for "datumctl fleet proxy readiness" "jq -e '.ready == true' '${E2E_DIR}/ready.json' >/dev/null 2>&1" "${proxy_pid}" + endpoint=$(jq -r .endpoint "${E2E_DIR}/credentials.json") + username=$(jq -r .username "${E2E_DIR}/credentials.json") + password=$(jq -r .password "${E2E_DIR}/credentials.json") + root=${endpoint%/redfish/v1/} +} + +stop_proxy() { + local confirm=${1:-true} + kill -TERM "${proxy_pid}" 2>/dev/null || true + wait "${proxy_pid}" 2>/dev/null || true + proxy_pid= + if [[ "${confirm}" == true ]]; then + wait_for "session deletion" "sessions_absent '${MGMT_KUBECONFIG}' default machinemanagementsessions.metal.datumapis.com" + fi +} + +# Nested x86 QEMU on non-x86 developer hosts can take tens of seconds to apply +# a real libvirt boot mutation. Keep the deadline bounded while allowing the +# required software-emulation fallback to complete without manufacturing a +# client-side lost-response outcome. +rf() { curl --silent --show-error --max-time 90 --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" "$@"; } +rf_status() { curl --silent --max-time 90 --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" "$@"; } + +checkpoint "Machine reader denied session creation" +start_proxy +[[ $(file_mode "${E2E_DIR}/credentials.json") == 600 ]] || fail "credential file is not 0600" +[[ $(file_mode "${E2E_DIR}/ca.pem") == 600 ]] || fail "CA file is not 0600" +if curl --fail --silent --connect-timeout 2 http://172.30.0.10:8000/redfish/v1/ >/dev/null 2>&1; then + fail "customer test process reached the private sushy endpoint" +fi +session_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.name}') +session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsession "${session_name}" -o jsonpath='{.metadata.uid}') +binding_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -l "fleet.datumapis.com/session-uid=${session_uid}" -o jsonpath='{.items[0].metadata.name}') +# This is an actual Karmada Work proof, not a direct controller write to the +# member API: the selected cell owns the one Work containing this projection, +# and status has returned through the hub copy before the public session readied. +work_clusters=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get works.work.karmada.io -A -o json | jq -r --arg name "${binding_name}" ' + .items[] | select(any(.spec.workload.manifests[]?; .kind == "ProjectedMachineManagementSession" and .metadata.name == $name)) | .metadata.namespace' | sort -u) +[[ "${work_clusters}" == karmada-es-fleet-location-e2e ]] || fail "projection Work was not isolated to fleet-location-e2e: ${work_clusters}" +[[ $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${binding_name}" -o jsonpath='{.metadata.labels.fleet\.datumapis\.com/member-cluster}') == fleet-location-e2e ]] || fail "hub projection lost its admitted member identity" +[[ -n $(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n machine-access-system get projectedmachinemanagementsession "${binding_name}" -o jsonpath='{.status.connection.routeID}') ]] || fail "cell status was not reflected through Karmada" +if kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get secret fleet-location-kubeconfig >/dev/null 2>&1; then + fail "management cluster retained a direct location credential" +fi +if kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default patch machinemanagementsession "${session_name}" --type=merge -p '{"spec":{"ttl":"10m"}}' >/dev/null 2>&1; then + fail "immutable public session spec was mutable" +fi + +# Use DMTF's generic Python Redfish client, not a project-specific client. A +# remote Docker engine cannot share the macOS loopback namespace, so the +# unqualified Darwin development path uses the same pinned client from a local +# temporary virtual environment. Native Linux and CI retain the container path. +if [[ $(uname -s) == Darwin ]]; then + validator_bin=${FLEET_VALIDATOR_BIN:-/private/tmp/fleet-validator-venv/bin} + FLEET_CREDENTIAL_FILE="${E2E_DIR}/credentials.json" FLEET_CA_BUNDLE="${E2E_DIR}/ca.pem" \ + "${validator_bin}/python" "${TEST_DIR}/generic-client.py" +else + docker run --rm --network host \ + -e FLEET_CREDENTIAL_FILE=/state/credentials.json -e FLEET_CA_BUNDLE=/state/ca.pem \ + -v "${E2E_DIR}:/state:ro" -v "${TEST_DIR}:/work:ro" fleet-redfish-tools:e2e \ + "python /work/generic-client.py" +fi +checkpoint "generic DMTF client and Karmada projection" + +# Session-local login credentials are revocable and are not BMC credentials. +login_headers="${E2E_DIR}/login.headers" +curl --silent --show-error --cacert "${E2E_DIR}/ca.pem" -D "${login_headers}" \ + -H 'Content-Type: application/json' -d "{\"UserName\":\"${username}\",\"Password\":\"${password}\"}" \ + "${root}/redfish/v1/SessionService/Sessions" >/dev/null +local_token=$(awk 'tolower($1)=="x-auth-token:" {gsub("\r", "", $2); print $2}' "${login_headers}") +[[ -n "${local_token}" ]] || fail "local Redfish login did not return a token" +curl --silent --show-error --cacert "${E2E_DIR}/ca.pem" -H "X-Auth-Token: ${local_token}" \ + -X DELETE "${root}/redfish/v1/SessionService/Sessions/local" -o /dev/null +[[ $(curl --silent --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" -H "X-Auth-Token: ${local_token}" "${root}/redfish/v1/Systems") == 401 ]] || fail "deleted local Redfish token remained valid" + +# The virtual tree is intentionally narrow and contains exactly one allocated system. +for path in AccountService Managers UpdateService Systems/unallocated Systems/allocated/Oem/Reset; do + [[ $(rf_status "${root}/redfish/v1/${path}") == 404 ]] || fail "forbidden path ${path} was exposed" +done +[[ $(curl --silent --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" -H 'Host: 172.30.0.10' "${root}/redfish/v1/Systems") == 400 ]] || fail "Host routing was accepted" +[[ $(curl --silent --output /dev/null --write-out '%{http_code}' --cacert "${E2E_DIR}/ca.pem" --user "${username}:${password}" --request-target 'http://172.30.0.10/redfish/v1/Systems' "${root}/redfish/v1/Systems") == 400 ]] || fail "absolute request target was accepted" +[[ $(rf_status -X PATCH -H 'Content-Type: application/json' -d '{"AssetTag":"customer-controlled"}' "${root}/redfish/v1/Systems/allocated") == 400 ]] || fail "unsupported PATCH was accepted" +[[ $(rf_status -X POST -H 'Content-Type: application/json' -d '{"ResetType":"Nmi"}' "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") == 400 ]] || fail "unsupported reset was accepted" +[[ $(docker exec fleet-e2e-virtual-bmc virsh domstate unallocated | tr -d '\r') == "shut off" ]] || fail "unallocated domain was affected" + +# A second connector cannot consume the already-consumed rendezvous route. +route=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].status.connection.routeID}') +replay=$(run_timeout 3 bash -c "exec 9<>/dev/tcp/127.0.0.1/30443; printf 'CLIENT %s\\n' '${route}' >&9; IFS= read -r line <&9; printf '%s' \"\${line}\"") +[[ "${replay}" == ERROR* ]] || fail "relay route replay was not rejected: ${replay}" + +# Per-Machine admission limit remains distinct from Machine read permission. +set +e +run_timeout 20 env HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-01 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" >"${E2E_DIR}/second-session.log" 2>&1 +second_status=$? +set -e +[[ ${second_status} -ne 0 ]] || fail "second concurrent Machine session was admitted" +grep -q SessionLimitExceeded "${E2E_DIR}/second-session.log" || fail "session limit rejection was not actionable" + +# The E2E controller uses a test-only project limit of two. A second distinct, +# pre-bound Machine is admitted; a third is rejected by the real plugin workflow. +for machine in db-02 db-03; do + kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - <"${E2E_DIR}/proxy-2.log" 2>&1 & +second_proxy_pid=$! +wait_for "second project session" "jq -e '.ready == true' '${E2E_DIR}/ready-2.json' >/dev/null 2>&1" "${second_proxy_pid}" +set +e +run_timeout 20 env HOME="${E2E_DIR}/home-authorized" datumctl fleet machine-management proxy db-03 -- \ + --api-server "${api_server}" --api-ca-file "${E2E_DIR}/management-ca.crt" >"${E2E_DIR}/project-limit.log" 2>&1 +project_status=$? +set -e +[[ ${project_status} -ne 0 ]] || fail "third project session was admitted over the limit" +grep -q SessionLimitExceeded "${E2E_DIR}/project-limit.log" || fail "project limit rejection was not actionable" +kill -TERM "${second_proxy_pid}"; wait "${second_proxy_pid}" || true; second_proxy_pid= +release_fixture db-02 "${db02_uid}" + +checkpoint "local login revocation, route isolation, and session limits" + +# Real sushy -> libvirt PXE effect, correlated by the allocated VM MAC callback. +pxe_body='{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Pxe"}}' +pxe_task=$(rf -X PATCH -H 'Content-Type: application/json' -d "${pxe_body}" "${root}/redfish/v1/Systems/allocated") +[[ $(jq -r .TaskState <<<"${pxe_task}") == Completed ]] || fail "PXE boot mutation did not complete" +power_task=$(rf -X POST -H 'Content-Type: application/json' -d '{"ResetType":"On"}' "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +task_uri=$(jq -r '.["@odata.id"]' <<<"${power_task}") +[[ $(rf "${root}${task_uri}" | jq -r .TaskState) == Completed ]] || fail "power task did not complete" +# A complete Ubuntu kernel boot under nested software QEMU can exceed the +# ordinary control-plane wait. Keep this proof bounded, but allow four minutes +# for the real VM to load the initramfs, configure DHCP, and call back. +for _ in $(seq 1 240); do + docker exec fleet-e2e-virtual-bmc grep -q '/pxe/52-54-00-aa-00-01' /evidence/pxe-callbacks.jsonl 2>/dev/null && break + sleep 1 +done +docker cp fleet-e2e-virtual-bmc:/evidence/pxe-callbacks.jsonl "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" +grep -q '/pxe/52-54-00-aa-00-01' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" 2>/dev/null || fail "timed out waiting for PXE callback for allocated MAC" +wait_for "PXE fixture poweroff in libvirt" "[[ \$(docker exec fleet-e2e-virtual-bmc virsh domstate allocated | tr -d '\\r') == 'shut off' ]]" +! grep -q '/pxe/52-54-00-aa-00-02' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" || fail "unallocated VM produced a PXE callback" +jq -n --arg operationID "$(jq -r .Id <<<"${power_task}")" --arg mac 52:54:00:aa:00:01 \ + --argjson callback "$(grep '/pxe/52-54-00-aa-00-01' "${E2E_DIR}/virtual-bmc/evidence/pxe-callbacks.jsonl" | tail -1)" \ + '{operationID:$operationID,vmMAC:$mac,callback:$callback}' >"${E2E_DIR}/virtual-bmc/evidence/pxe-operation-correlation.json" +checkpoint "fresh allocated PXE callback and libvirt poweroff" + +wait_for "authority after PXE boot" "[[ \$(rf_status '${root}/redfish/v1/Systems/allocated') == 200 ]]" + +hdd_body='{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Hdd"}}' +hdd_task=$(rf -X PATCH -H 'Content-Type: application/json' -d "${hdd_body}" "${root}/redfish/v1/Systems/allocated") +[[ $(jq -r .TaskState <<<"${hdd_task}") == Completed ]] || fail "local-disk mutation did not complete: ${hdd_task}" +[[ $(rf "${root}/redfish/v1/Systems/allocated" | jq -r .Boot.BootSourceOverrideTarget) == Hdd ]] || fail "local-disk target was not restored" +domain_xml=$(docker exec fleet-e2e-virtual-bmc virsh dumpxml allocated) +grep -A6 "" <<<"${domain_xml}" | grep -q "" || fail "libvirt did not retain the local-disk boot target" +if grep -A6 "" <<<"${domain_xml}" | grep -q '"${E2E_DIR}/recreated-allocation.json" +jq -e '.epoch > 1' "${E2E_DIR}/recreated-allocation.json" >/dev/null || fail "capacity reuse did not advance allocation epoch" +[[ "${new_machine_uid}" != "${old_machine_uid}" ]] || fail "recreated Machine retained its old UID" +[[ $(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${old_binding_name}" -o jsonpath='{.spec.machineUID}') == "${old_machine_uid}" ]] || fail "old session binding inherited the recreated Machine" +old_binding_revoked=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbinding "${old_binding_name}" -o jsonpath='{.metadata.annotations.fleet\.datumapis\.com/revoked-at}') +[[ -n "${old_binding_revoked}" ]] || fail "released old binding was not terminally revoked" + +start_proxy +[[ $(rf "${root}/redfish/v1/Systems/allocated" | jq -r .Id) == allocated ]] || fail "virtual system identity was not stable" +# The adapter now targets the newly allocated physical domain; the old domain +# is never addressable through the customer's virtual ID. +rf -X POST -H 'Content-Type: application/json' -d '{"ResetType":"On"}' "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset" >/dev/null +wait_for "new allocation domain power-on" "[[ \$(docker exec fleet-e2e-virtual-bmc virsh domstate unallocated | tr -d '\\r') == running ]]" +checkpoint "release fence and same-name Machine recreation" + +# The gateway schedules the admitted expiry and closes the stream rather than +# treating a still-live client or relay connection as authority. +stop_proxy +start_proxy 1m +sleep 65 +[[ $(rf_status "${root}/redfish/v1/Systems/allocated") != 200 ]] || fail "expired session retained Redfish access" +checkpoint "admitted expiry closes access" +stop_proxy +start_proxy + +# Stop only the private sushy route. The customer receives a bounded error that +# does not disclose the private endpoint or credential. +docker exec fleet-e2e-virtual-bmc iptables -I INPUT 1 -p tcp --dport 8000 -s 172.30.0.20 -j REJECT +bmc_blocked=true +bmc_error=$(rf "${root}/redfish/v1/Systems/allocated") +[[ $(jq -r .error.code <<<"${bmc_error}") == Fleet.1.0.BMCUnavailable ]] || fail "BMC failure was not actionable" +! grep -Eq '172\.30\.0\.10|fleet-gateway|synthetic-e2e-only' <<<"${bmc_error}" || fail "BMC failure disclosed private data" +docker exec fleet-e2e-virtual-bmc iptables -D INPUT -p tcp --dport 8000 -s 172.30.0.20 -j REJECT +bmc_blocked=false +checkpoint "bounded private BMC outage without credential disclosure" + +# If the location cannot acknowledge explicit deletion, the public object may +# finish deleting only with a protected Unknown teardown outcome. +unknown_session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.uid}') +unknown_binding_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -l "fleet.datumapis.com/session-uid=${unknown_session_uid}" -o jsonpath='{.items[0].metadata.name}') +docker pause fleet-location-e2e-control-plane >/dev/null +location_paused=true +stop_proxy false +wait_for "unconfirmed location teardown" "[[ \$(kubectl --request-timeout=10s --kubeconfig '${MGMT_KUBECONFIG}' -n fleet-system get machinemanagementsessionbinding '${unknown_binding_name}' -o json | jq -r '.status.conditions[] | select(.type==\"CleanupConfirmed\") | .status + \":\" + .reason') == Unknown:LocationUnconfirmed ]]" +unconfirmed_session=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o json) +jq -e --arg uid "${unknown_session_uid}" 'any(.items[]; .metadata.uid == $uid and .metadata.deletionTimestamp != null and (.metadata.finalizers | length > 0))' <<<"${unconfirmed_session}" >/dev/null || fail "unconfirmed session deletion discarded custody" +docker unpause fleet-location-e2e-control-plane >/dev/null +location_paused=false +[[ ! -e "${E2E_DIR}/credentials.json" && ! -e "${E2E_DIR}/ca.pem" ]] || fail "proxy secret files survived shutdown" +checkpoint "unconfirmed location teardown remains Unknown; local secrets removed" +wait_for "location recovery verified teardown" "binding_clean '${unknown_binding_name}'" +wait_for "recovered session deletion" "sessions_absent '${MGMT_KUBECONFIG}' default machinemanagementsessions" + +wait_for "prior location projection teardown" \ + "sessions_absent '${LOCATION_KUBECONFIG}' machine-access-system projectedmachinemanagementsessions.coordination.fleet.datumapis.com" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system patch deployment fleet-gateway --type=json \ + -p='[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--fault-drop-reset-response-once"}]' +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s +start_proxy +lost_session_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsessions -o jsonpath='{.items[0].metadata.name}') +lost_session_uid=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsession "${lost_session_name}" -o jsonpath='{.metadata.uid}') +lost_binding_name=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system get machinemanagementsessionbindings -l "fleet.datumapis.com/session-uid=${lost_session_uid}" -o jsonpath='{.items[0].metadata.name}') +reset_path='/redfish/v1/Systems/unallocated/Actions/ComputerSystem.Reset' +reset_before=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) +lost_body='{"ResetType":"ForceRestart"}' +lost_first=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +lost_second=$(rf -X POST -H 'Content-Type: application/json' -d "${lost_body}" "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") +[[ $(jq -r .TaskState <<<"${lost_first}") == Exception && $(jq -r .TaskStatus <<<"${lost_first}") == Warning ]] || fail "lost response was not reported Unknown" +[[ $(jq -r .Id <<<"${lost_first}") == $(jq -r .Id <<<"${lost_second}") ]] || fail "retry created a second operation" +reset_after=$(docker logs fleet-e2e-virtual-bmc 2>&1 | grep -c "POST ${reset_path}" || true) +[[ $((reset_after - reset_before)) -eq 1 ]] || fail "lost-response retry sent $((reset_after - reset_before)) physical resets" +[[ $(rf_status -X POST -H 'Content-Type: application/json' -d '{"ResetType":"ForceOff"}' "${root}/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset") == 409 ]] || fail "unknown effect allowed a new mutation" +release_blocked db-01 "${new_machine_uid}" +stop_proxy false +sleep 35 +release_blocked db-01 "${new_machine_uid}" +if binding_clean "${lost_binding_name}"; then fail "unknown operation fabricated verified teardown"; fi +retained_session=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machinemanagementsession "${lost_session_name}" -o json) +jq -e '.metadata.deletionTimestamp != null and (.metadata.finalizers | length > 0)' <<<"${retained_session}" >/dev/null || fail "unknown session lost its finalizer" +retained_machine=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machine db-01 -o json) +jq -e '.metadata.finalizers | index("fleet.datumapis.com/machine-protection") != null' <<<"${retained_machine}" >/dev/null || fail "unknown effect released Machine protection" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - <"${E2E_DIR}/blocked-reuse.json" 2>"${E2E_DIR}/blocked-reuse.log"; then + fail "unknown effect allowed occupied capacity reuse" +fi +grep -q 'no eligible clean machine is available' "${E2E_DIR}/blocked-reuse.log" || fail "reuse failed for an unexpected reason" +asset_state "${new_machine_uid}" Releasing || fail "failed reuse changed occupied asset custody" +checkpoint "lost response deduplicates; unknown effects block mutation, release, and reuse" +echo "machine-management end-to-end scenarios: PASS" diff --git a/hack/e2e/up.sh b/hack/e2e/up.sh new file mode 100755 index 00000000..1d7244d4 --- /dev/null +++ b/hack/e2e/up.sh @@ -0,0 +1,281 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +TEST_DIR="${ROOT_DIR}/test/e2e/machine-management" +MGMT_KUBECONFIG="${E2E_DIR}/management.kubeconfig" +LOCATION_KUBECONFIG="${E2E_DIR}/location.kubeconfig" +export FLEET_E2E_STATE="${E2E_DIR}/virtual-bmc" +source "${ROOT_DIR}/hack/e2e/common.sh" +source "${ROOT_DIR}/hack/e2e/lifecycle.sh" + +for tool in docker kind kubectl helm curl go jq openssl; do + command -v "${tool}" >/dev/null || { echo "missing required tool: ${tool}" >&2; exit 1; } +done +if [[ $(uname -s) != Linux ]]; then + echo "warning: Linux is the qualified environment; attempting the same QEMU software-emulation path on $(uname -s)" >&2 + # Cross-architecture Lima guests can expose a nominal /dev/kvm even though + # nesting it reboots the outer VM. Select the required software fallback. + export FLEET_FORCE_QEMU=${FLEET_FORCE_QEMU:-1} +fi +mkdir -p "${E2E_DIR}/bin" "${FLEET_E2E_STATE}/evidence" "${FLEET_E2E_STATE}/images" +go build -o "${E2E_DIR}/bin/fleet-session-fixture" "${ROOT_DIR}/cmd/fleet-session-fixture" +if kind get clusters | grep -qx fleet-management-e2e; then + kind get kubeconfig --name fleet-management-e2e >"${MGMT_KUBECONFIG}" + chmod 0600 "${MGMT_KUBECONFIG}" + machine_crd=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" get crd machines.metal.datumapis.com --ignore-not-found -o name) + if [[ -n "${machine_crd}" ]]; then + retained=$(kubectl --request-timeout=10s --kubeconfig "${MGMT_KUBECONFIG}" -n default get machines -o json) + while IFS=$'\t' read -r machine uid; do + [[ -n "${machine}" ]] || continue + release_fixture "${machine}" "${uid}" + done < <(jq -r '.items[] | select(.metadata.name == "db-01" or .metadata.name == "db-02" or .metadata.name == "db-03" or .metadata.name == "db-04") | + [.metadata.name,.metadata.uid] | @tsv' <<<"${retained}") + fi +fi +bash "${ROOT_DIR}/hack/e2e/prepare-schemas.sh" +find "${FLEET_E2E_STATE}/evidence" -maxdepth 1 -type f -delete + +docker compose -p fleet-bmc-e2e -f "${TEST_DIR}/compose.yaml" up -d --build +for _ in $(seq 1 60); do docker exec fleet-e2e-virtual-bmc virsh list --all >/dev/null 2>&1 && break; sleep 1; done +docker exec fleet-e2e-virtual-bmc virsh destroy allocated >/dev/null 2>&1 || true +docker exec fleet-e2e-virtual-bmc virsh destroy unallocated >/dev/null 2>&1 || true + +if ! kind get clusters | grep -qx fleet-management-e2e; then + kind create cluster --name fleet-management-e2e --config "${TEST_DIR}/kind-management.yaml" +fi +if ! kind get clusters | grep -qx fleet-location-e2e; then + kind create cluster --name fleet-location-e2e --config "${TEST_DIR}/kind-location.yaml" +fi +kind get kubeconfig --name fleet-management-e2e >"${MGMT_KUBECONFIG}" +kind get kubeconfig --name fleet-location-e2e >"${LOCATION_KUBECONFIG}" +chmod 0600 "${MGMT_KUBECONFIG}" "${LOCATION_KUBECONFIG}" + +if ! docker network inspect fleet-management-e2e | jq -e '.[0].Containers | to_entries[] | select(.value.Name=="fleet-location-e2e-control-plane")' >/dev/null; then + docker network connect --ip 172.30.0.20 fleet-management-e2e fleet-location-e2e-control-plane +fi + +# Install the same pinned Karmada release used by Datum Compute. The Karmada +# API is a separate control plane hosted inside the management Kind cluster; +# only it receives the member-cluster credential. +KARMADA_VERSION=v1.16.0 +KARMADA_KUBECONFIG="${E2E_DIR}/karmada.kubeconfig" +if [[ ! -x "${E2E_DIR}/bin/karmadactl" ]]; then + os=$(uname -s | tr '[:upper:]' '[:lower:]') + arch=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/') + curl -sSfL "https://github.com/karmada-io/karmada/releases/download/${KARMADA_VERSION}/karmadactl-${os}-${arch}.tgz" | + tar -xz -C "${E2E_DIR}/bin" karmadactl + chmod 0755 "${E2E_DIR}/bin/karmadactl" +fi +if ! helm repo list 2>/dev/null | grep -q '^karmada-charts'; then + helm repo add karmada-charts https://raw.githubusercontent.com/karmada-io/karmada/master/charts +fi +helm repo update karmada-charts +if ! kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n karmada-system get deployment karmada-apiserver >/dev/null 2>&1; then + helm install karmada karmada-charts/karmada \ + --kubeconfig "${MGMT_KUBECONFIG}" --namespace karmada-system --create-namespace \ + --version "${KARMADA_VERSION}" --set apiServer.serviceType=NodePort \ + --set apiServer.nodePort=32443 --wait --timeout 10m +fi +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n karmada-system wait \ + --for=condition=Available deployment --all --timeout=10m +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n karmada-system get secret karmada-kubeconfig \ + -o jsonpath='{.data.kubeconfig}' | base64 -d >"${KARMADA_KUBECONFIG}" +karmada_cluster=$(kubectl config get-clusters --kubeconfig "${KARMADA_KUBECONFIG}" | tail -n 1) +kubectl config set-cluster "${karmada_cluster}" --kubeconfig "${KARMADA_KUBECONFIG}" \ + --server=https://127.0.0.1:32443 --insecure-skip-tls-verify=true >/dev/null +chmod 0600 "${KARMADA_KUBECONFIG}" + +for _ in $(seq 1 90); do + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get clusters >/dev/null 2>&1 && break + sleep 2 +done +if ! kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get cluster fleet-location-e2e >/dev/null 2>&1; then + for attempt in 1 2 3 4 5; do + if "${E2E_DIR}/bin/karmadactl" join fleet-location-e2e \ + --kubeconfig "${KARMADA_KUBECONFIG}" \ + --cluster-kubeconfig "${LOCATION_KUBECONFIG}" \ + --cluster-context kind-fleet-location-e2e; then + break + fi + [[ ${attempt} -lt 5 ]] || { echo "failed to join location cluster to Karmada" >&2; exit 1; } + sleep 10 + done +fi +cp "${LOCATION_KUBECONFIG}" "${E2E_DIR}/location-internal.kubeconfig" +location_cluster=$(kubectl config get-clusters --kubeconfig "${E2E_DIR}/location-internal.kubeconfig" | tail -n 1) +location_ip=$(docker inspect fleet-location-e2e-control-plane | jq -r '.[0].NetworkSettings.Networks.kind.IPAddress') +kubectl config set-cluster "${location_cluster}" --kubeconfig "${E2E_DIR}/location-internal.kubeconfig" \ + --server="https://${location_ip}:6443" --insecure-skip-tls-verify=true >/dev/null +member_secret=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get cluster fleet-location-e2e -o jsonpath='{.spec.secretRef.name}') +member_secret_namespace=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" get cluster fleet-location-e2e -o jsonpath='{.spec.secretRef.namespace}') +member_secret_namespace=${member_secret_namespace:-karmada-system} +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n "${member_secret_namespace}" create secret generic "${member_secret}" \ + --from-file=kubeconfig="${E2E_DIR}/location-internal.kubeconfig" --dry-run=client -o yaml | + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" patch cluster fleet-location-e2e --type=merge \ + -p "{\"spec\":{\"apiEndpoint\":\"https://${location_ip}:6443\"}}" +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" label cluster fleet-location-e2e \ + topology.datum.net/location=44444444-4444-4444-8444-444444444444 --overwrite +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" wait cluster/fleet-location-e2e \ + --for=condition=Ready --timeout=180s + +build_image() { + local image=$1 package=$2 binary=$3 + if [[ $(uname -s) == Darwin ]]; then + mkdir -p "${E2E_DIR}/image-bin/${binary}" + env GOOS=linux GOARCH=amd64 CGO_ENABLED=0 GOCACHE="${E2E_DIR}/go-cache" \ + go build -trimpath -ldflags='-s -w' -o "${E2E_DIR}/image-bin/${binary}/${binary}" "${package}" + docker build -t "${image}:e2e" --build-arg "BINARY=${binary}" \ + -f "${TEST_DIR}/Dockerfile.prebuilt" "${E2E_DIR}/image-bin/${binary}" + return + fi + docker build -t "${image}:e2e" --build-arg "PACKAGE=${package}" --build-arg "BINARY=${binary}" "${ROOT_DIR}" +} +build_image fleet-controller ./cmd/fleet-controller fleet-controller +build_image fleet-gateway ./cmd/fleet-gateway fleet-gateway +build_image fleet-relay ./cmd/fleet-relay fleet-relay +docker build -t fleet-redfish-tools:e2e "${TEST_DIR}/tools" +kind load docker-image fleet-controller:e2e --name fleet-management-e2e +kind load docker-image fleet-gateway:e2e fleet-relay:e2e --name fleet-location-e2e + +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/base/crd" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/base/crd" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/crd" +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply \ + -f "${ROOT_DIR}/config/crd/bases/coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml" --server-side --validate=false +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -k "${ROOT_DIR}/config/federation" --server-side --validate=false +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" create namespace machine-access-system --dry-run=client -o yaml | + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -k "${ROOT_DIR}/config/machine-management/base" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -k "${ROOT_DIR}/config/machine-management/base" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" wait --for=condition=Established --timeout=60s crd/machinemanagementsessions.metal.datumapis.com +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" wait --for=condition=Established --timeout=60s crd/projectedmachinemanagementsessions.coordination.fleet.datumapis.com +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/controller.yaml" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/rbac/controller.yaml" + +relay_token=$(openssl rand -hex 32) +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system create secret generic fleet-relay-token \ + --from-literal=relay-token="${relay_token}" --dry-run=client -o yaml | kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f - +unset relay_token + +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" create namespace fleet-system --dry-run=client -o yaml | + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n fleet-system create serviceaccount fleet-controller --dry-run=client -o yaml | + kubectl --kubeconfig "${KARMADA_KUBECONFIG}" apply -f - +federation_token=$(kubectl --kubeconfig "${KARMADA_KUBECONFIG}" -n fleet-system create token fleet-controller --duration=2h) +cat >"${E2E_DIR}/federation.kubeconfig" </dev/null 2>&1 +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system create secret tls fleet-webhook-tls \ + --cert="${E2E_DIR}/webhook/tls.crt" --key="${E2E_DIR}/webhook/tls.key" --dry-run=client -o yaml | kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${ROOT_DIR}/config/manager/controller.yaml" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${ROOT_DIR}/config/manager/networkpolicy.yaml" +webhook_ca=$(base64 -w0 <"${E2E_DIR}/webhook/tls.crt") +kubectl --kubeconfig "${MGMT_KUBECONFIG}" patch mutatingwebhookconfiguration fleet-machine-management-session --type=json \ + -p="[{\"op\":\"add\",\"path\":\"/webhooks/0/clientConfig/caBundle\",\"value\":\"${webhook_ca}\"}]" +unset webhook_ca + +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/location/access.yaml" +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${ROOT_DIR}/config/location/networkpolicy.yaml" +# Local images intentionally reuse stable :e2e tags and the synthetic relay and +# webhook credentials may be regenerated. Restart all consumers together so an +# idempotent rerun cannot leave a process using a stale image or secret value. +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system rollout restart deployment/fleet-controller +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout restart deployment/fleet-relay deployment/fleet-gateway +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-system rollout status deployment/fleet-controller --timeout=120s +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-relay --timeout=120s +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" -n machine-access-system rollout status deployment/fleet-gateway --timeout=120s + +# Reset only resources owned by this dedicated E2E environment so repeated up +# and test invocations begin from the same authority state. +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machinemanagementsessions --all --timeout=40s --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default delete machines db-01 db-02 db-03 db-04 --ignore-not-found +kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n fleet-provider delete machinecapacities --all --ignore-not-found + +kubectl --kubeconfig "${MGMT_KUBECONFIG}" create namespace fleet-provider --dry-run=client -o yaml | kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f - +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/machine.yaml" +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/allocation.yaml" +allocate_fixture db-01 allocated-capacity +kubectl --kubeconfig "${LOCATION_KUBECONFIG}" apply -f "${TEST_DIR}/seed/location-management.yaml" + +kubectl --kubeconfig "${MGMT_KUBECONFIG}" apply -f "${TEST_DIR}/seed/test-identities.yaml" +authorized_token=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default create token fleet-authorized --duration=2h) +viewer_token=$(kubectl --kubeconfig "${MGMT_KUBECONFIG}" -n default create token fleet-viewer --duration=2h) + +env GOBIN="${E2E_DIR}/bin" go install go.datum.net/datumctl@v0.15.0 +env GOCACHE="${E2E_DIR}/go-cache" go build -o "${E2E_DIR}/bin/datumctl-fleet" "${ROOT_DIR}/cmd/datumctl-fleet" +api_server=$(kubectl config view --kubeconfig "${MGMT_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.server}') +api_host=${api_server#https://} +kubectl config view --kubeconfig "${MGMT_KUBECONFIG}" --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}' | base64 -d >"${E2E_DIR}/management-ca.crt" + +write_datum_session() { + local name=$1 token=$2 + local home_dir="${E2E_DIR}/home-${name}" user_key="${name}@kind" + mkdir -p "${home_dir}/.datumctl" + chmod 0700 "${home_dir}/.datumctl" + cat >"${home_dir}/.datumctl/config" </dev/null 2>&1; then + expiry=$(date -u -d '+2 hours' '+%Y-%m-%dT%H:%M:%SZ') + else + expiry=$(date -u -v+2H '+%Y-%m-%dT%H:%M:%SZ') + fi + creds=$(jq -cn --arg token "${token}" --arg expiry "${expiry}" --arg host "${api_host}" --arg email "${name}@example.test" \ + '{hostname:"kind.invalid",api_hostname:$host,client_id:"fleet-e2e",endpoint_auth_url:"https://kind.invalid/auth",endpoint_token_url:"https://kind.invalid/token",scopes:[],token:{access_token:$token,token_type:"Bearer",expiry:$expiry},user_name:$email,user_email:$email,subject:$email}') + jq -n --arg key "${user_key}" --arg creds "${creds}" '{"datumctl-auth":{($key):$creds,"active_user":$key,"known_users":([$key]|tojson)}}' >"${home_dir}/.datumctl/credentials.json" + chmod 0600 "${home_dir}/.datumctl/config" "${home_dir}/.datumctl/credentials.json" +} +write_datum_session authorized "${authorized_token}" +write_datum_session viewer "${viewer_token}" +unset authorized_token viewer_token +for identity in authorized viewer; do + HOME="${E2E_DIR}/home-${identity}" PATH="${E2E_DIR}/bin:${PATH}" \ + "${E2E_DIR}/bin/datumctl" plugin trust fleet >/dev/null +done + +echo "Fleet machine-management e2e environment is ready in ${E2E_DIR}" diff --git a/hack/e2e/validators.sh b/hack/e2e/validators.sh new file mode 100755 index 00000000..784773d3 --- /dev/null +++ b/hack/e2e/validators.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +E2E_DIR="${ROOT_DIR}/.e2e" +CREDENTIAL_FILE=${FLEET_CREDENTIAL_FILE:-${E2E_DIR}/credentials.json} +REPORT_DIR="${E2E_DIR}/validators" +SCHEMA_DIR="${E2E_DIR}/redfish-schemas" +source "${ROOT_DIR}/hack/e2e/common.sh" +[[ -f "${CREDENTIAL_FILE}" ]] || { echo "missing proxy credential file: ${CREDENTIAL_FILE}" >&2; exit 1; } +for schema in ServiceRoot SessionService Session SessionCollection ComputerSystem ComputerSystemCollection TaskService Task TaskCollection Resource; do + [[ -s "${SCHEMA_DIR}/${schema}_v1.xml" || -s "${SCHEMA_DIR}/${schema}.xml" ]] || fail "missing pinned ${schema} schema; run task e2e:up" +done +mkdir -p "${REPORT_DIR}/service" "${REPORT_DIR}/interop" +cp "${SCHEMA_DIR}/provenance.txt" "${REPORT_DIR}/schema-provenance.txt" + +endpoint=$(jq -r .endpoint "${CREDENTIAL_FILE}") +username=$(jq -r .username "${CREDENTIAL_FILE}") +password=$(jq -r .password "${CREDENTIAL_FILE}") +ca_bundle=$(jq -r .caBundle "${CREDENTIAL_FILE}") + +if [[ $(uname -s) == Darwin ]]; then + validator_bin=${FLEET_VALIDATOR_BIN:-/private/tmp/fleet-validator-venv/bin} + REQUESTS_CA_BUNDLE="${ca_bundle}" "${validator_bin}/rf_service_validator" \ + --rhost "${endpoint%/redfish/v1/}" --user "${username}" --password "${password}" \ + --authtype Session --nooemcheck --logdir "${REPORT_DIR}/service" \ + --skipschema --schema_directory "${SCHEMA_DIR}" 2>&1 | tee "${REPORT_DIR}/service-summary.log" + validator_coverage "${REPORT_DIR}/service-summary.log" || fail "service validator did not complete warning-free schema validation" + REQUESTS_CA_BUNDLE="${ca_bundle}" "${validator_bin}/rf_interop_validator" \ + --rhost "${endpoint%/redfish/v1/}" --user "${username}" --password "${password}" \ + --authtype Session --nooemcheck --logdir "${REPORT_DIR}/interop" \ + "${ROOT_DIR}/config/redfish/FleetProvisioning.v1_0_0.json" 2>&1 | tee "${REPORT_DIR}/interop-summary.log" +else + docker run --rm --network host --user "$(id -u):$(id -g)" --workdir /state/validators/service \ + -e REQUESTS_CA_BUNDLE=/state/ca.pem \ + -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ + fleet-redfish-tools:e2e \ + "rf_service_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/service --skipschema --schema_directory /state/redfish-schemas" 2>&1 | tee "${REPORT_DIR}/service-summary.log" + validator_coverage "${REPORT_DIR}/service-summary.log" || fail "service validator did not complete warning-free schema validation" + + docker run --rm --network host --user "$(id -u):$(id -g)" --workdir /state/validators/interop \ + -e REQUESTS_CA_BUNDLE=/state/ca.pem \ + -v "${ROOT_DIR}:/work:ro" -v "${E2E_DIR}:/state" \ + fleet-redfish-tools:e2e \ + "rf_interop_validator --rhost '${endpoint%/redfish/v1/}' --user '${username}' --password '${password}' --authtype Session --nooemcheck --logdir /state/validators/interop /work/config/redfish/FleetProvisioning.v1_0_0.json" 2>&1 | tee "${REPORT_DIR}/interop-summary.log" +fi +validator_coverage "${REPORT_DIR}/interop-summary.log" || fail "interop validator did not complete warning-free profile validation" + +echo "DMTF validator reports: ${REPORT_DIR}" diff --git a/internal/api/coordination/v1alpha1/doc.go b/internal/api/coordination/v1alpha1/doc.go new file mode 100644 index 00000000..d4d8eb9c --- /dev/null +++ b/internal/api/coordination/v1alpha1/doc.go @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package v1alpha1 contains private location coordination APIs. +// +kubebuilder:object:generate=true +// +groupName=coordination.fleet.datumapis.com +package v1alpha1 diff --git a/internal/api/coordination/v1alpha1/teardown.go b/internal/api/coordination/v1alpha1/teardown.go new file mode 100644 index 00000000..7aaf6098 --- /dev/null +++ b/internal/api/coordination/v1alpha1/teardown.go @@ -0,0 +1,24 @@ +package v1alpha1 + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +func TeardownDigest(session *ProjectedMachineManagementSession) string { + if session.Spec.DesiredState != sessionv1.ProjectionRevoked { + return "" + } + data, err := json.Marshal(struct { + Name string `json:"name"` + Spec ProjectedMachineManagementSessionSpec `json:"spec"` + }{Name: session.Name, Spec: session.Spec}) + if err != nil { + return "" + } + digest := sha256.Sum256(data) + return hex.EncodeToString(digest[:]) +} diff --git a/internal/api/coordination/v1alpha1/teardown_test.go b/internal/api/coordination/v1alpha1/teardown_test.go new file mode 100644 index 00000000..855e7f11 --- /dev/null +++ b/internal/api/coordination/v1alpha1/teardown_test.go @@ -0,0 +1,31 @@ +package v1alpha1 + +import ( + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +func TestTeardownDigestBindsRevocationNotClusterMetadata(t *testing.T) { + session := &ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: "opaque-session", Namespace: "hub", UID: "hub-uid", Generation: 8}, Spec: ProjectedMachineManagementSessionSpec{DesiredState: sessionv1.ProjectionActive, MachineCapacityRef: sessionv1.LocalReference{Name: "capacity"}}} + if TeardownDigest(session) != "" { + t.Fatal("active projection has teardown proof") + } + session.Spec.DesiredState = sessionv1.ProjectionRevoked + digest := TeardownDigest(session) + session.Namespace, session.UID, session.Generation = "cell", "cell-uid", 3 + if digest == "" || TeardownDigest(session) != digest { + t.Fatal("API-local metadata changed proof identity") + } + session.Spec.MachineCapacityRef.Name = "other-capacity" + if TeardownDigest(session) == digest { + t.Fatal("proof survived a target change") + } + session.Spec.MachineCapacityRef.Name = "capacity" + session.Name = "another-session" + if TeardownDigest(session) == digest { + t.Fatal("proof survived session replacement") + } +} diff --git a/internal/api/coordination/v1alpha1/types.go b/internal/api/coordination/v1alpha1/types.go new file mode 100644 index 00000000..fd400a78 --- /dev/null +++ b/internal/api/coordination/v1alpha1/types.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 +package v1alpha1 + +import ( + "encoding/json" + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +var GroupVersion = schema.GroupVersion{Group: "coordination.fleet.datumapis.com", Version: "v1alpha1"} + +// ProjectedMachineManagementSession is the least-privileged Karmada-delivered +// location copy. Its generated name is the location session identity. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type ProjectedMachineManagementSession struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + Spec ProjectedMachineManagementSessionSpec `json:"spec"` + Status ProjectedMachineManagementSessionStatus `json:"status,omitempty"` +} + +// +kubebuilder:validation:XValidation:rule="self.machineCapacityRef == oldSelf.machineCapacityRef && self.protocol == oldSelf.protocol && self.accessProfile == oldSelf.accessProfile && self.clientPublicKey == oldSelf.clientPublicKey && self.connectBefore == oldSelf.connectBefore && self.expiresAt == oldSelf.expiresAt",message="projected authority inputs are immutable" +// +kubebuilder:validation:XValidation:rule="oldSelf.desiredState == 'Active' || self.desiredState == 'Revoked'",message="revocation is terminal" +// +kubebuilder:validation:XValidation:rule="timestamp(self.authorityFreshUntil) >= timestamp(oldSelf.authorityFreshUntil) && timestamp(self.authorityFreshUntil) <= timestamp(self.expiresAt)",message="authority freshness may only advance within expiry" +type ProjectedMachineManagementSessionSpec struct { + // +kubebuilder:validation:Enum=Active;Revoked + DesiredState string `json:"desiredState"` + MachineCapacityRef sessionv1.LocalReference `json:"machineCapacityRef"` + Protocol string `json:"protocol"` + AccessProfile string `json:"accessProfile"` + ClientPublicKey string `json:"clientPublicKey"` + ConnectBefore metav1.Time `json:"connectBefore"` + ExpiresAt metav1.Time `json:"expiresAt"` + AuthorityFreshUntil metav1.Time `json:"authorityFreshUntil"` +} + +type ProjectedMachineManagementSessionStatus struct { + TeardownSpecDigest string `json:"teardownSpecDigest,omitempty"` + Connection *sessionv1.SessionConnection `json:"connection,omitempty"` + ConnectedAt *metav1.Time `json:"connectedAt,omitempty"` + EndedAt *metav1.Time `json:"endedAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +type ProjectedMachineManagementSessionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []ProjectedMachineManagementSession `json:"items"` +} + +func AddToScheme(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, &ProjectedMachineManagementSession{}, &ProjectedMachineManagementSessionList{}) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} +func (in *ProjectedMachineManagementSession) DeepCopy() *ProjectedMachineManagementSession { + return copyJSON(in) +} +func (in *ProjectedMachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *ProjectedMachineManagementSessionList) DeepCopy() *ProjectedMachineManagementSessionList { + return copyJSON(in) +} +func (in *ProjectedMachineManagementSessionList) DeepCopyObject() runtime.Object { + return in.DeepCopy() +} + +func copyJSON[T any](in *T) *T { + b, _ := json.Marshal(in) + out := new(T) + _ = json.Unmarshal(b, out) + return out +} diff --git a/internal/api/coordination/v1alpha1/types_test.go b/internal/api/coordination/v1alpha1/types_test.go new file mode 100644 index 00000000..b3d16d82 --- /dev/null +++ b/internal/api/coordination/v1alpha1/types_test.go @@ -0,0 +1,30 @@ +package v1alpha1 + +import ( + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "testing" +) + +func TestSessionAPIBoundaries(t *testing.T) { + s := runtime.NewScheme() + if err := AddToScheme(s); err != nil { + t.Fatal(err) + } + if err := sessionv1.AddToScheme(s); err != nil { + t.Fatal(err) + } + for _, tc := range []struct{ kind, group string }{ + {"MachineManagementSession", "metal.datumapis.com"}, + {"MachineManagementSessionBinding", "metal.datumapis.com"}, + {"ProjectedMachineManagementSession", "coordination.fleet.datumapis.com"}, + } { + for _, group := range []string{"metal.datumapis.com", "coordination.fleet.datumapis.com", "fleet.datumapis.com"} { + _, err := s.New(schema.GroupVersionKind{Group: group, Version: "v1alpha1", Kind: tc.kind}) + if (err == nil) != (group == tc.group) { + t.Errorf("%s in %s: %v", tc.kind, group, err) + } + } + } +} diff --git a/internal/api/session/v1alpha1/doc.go b/internal/api/session/v1alpha1/doc.go new file mode 100644 index 00000000..41c262ba --- /dev/null +++ b/internal/api/session/v1alpha1/doc.go @@ -0,0 +1,6 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package v1alpha1 contains provisional Fleet machine-management session APIs. +// +kubebuilder:object:generate=true +// +groupName=metal.datumapis.com +package v1alpha1 diff --git a/internal/api/session/v1alpha1/types.go b/internal/api/session/v1alpha1/types.go new file mode 100644 index 00000000..10db7f61 --- /dev/null +++ b/internal/api/session/v1alpha1/types.go @@ -0,0 +1,152 @@ +// SPDX-License-Identifier: Apache-2.0 + +package v1alpha1 + +import ( + "encoding/json" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" +) + +var GroupVersion = schema.GroupVersion{Group: "metal.datumapis.com", Version: "v1alpha1"} + +type LocalReference struct { + Name string `json:"name"` +} + +const ( + SessionFinalizer = "fleet.datumapis.com/machine-management-session" + ConditionReady = "Ready" + ProjectionActive = "Active" + ProjectionRevoked = "Revoked" +) + +// MachineManagementSession is a short-lived public request for the Machine's +// current allocation. Provider and location details never enter this object. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type MachineManagementSession struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="spec is immutable" + Spec MachineManagementSessionSpec `json:"spec"` + Status MachineManagementSessionStatus `json:"status,omitempty"` +} + +type MachineManagementSessionSpec struct { + MachineRef LocalReference `json:"machineRef"` + // +kubebuilder:validation:Enum=Redfish + Protocol string `json:"protocol"` + // +kubebuilder:validation:Enum=Provisioning + AccessProfile string `json:"accessProfile"` + // +kubebuilder:validation:Pattern=`^[0-9a-f]{64}$` + ClientPublicKey string `json:"clientPublicKey"` + // +kubebuilder:validation:XValidation:rule="duration(self) >= duration('1m') && duration(self) <= duration('15m')",message="ttl must be between 1m and 15m" + TTL metav1.Duration `json:"ttl"` +} + +type MachineManagementSessionStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + ConnectBefore *metav1.Time `json:"connectBefore,omitempty"` + ExpiresAt *metav1.Time `json:"expiresAt,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// SessionConnection contains non-secret rendezvous information only. +type SessionConnection struct { + RelayURL string `json:"relayURL"` + RouteID string `json:"routeID"` + GatewayAudience string `json:"gatewayAudience"` + GatewayCertSHA256 string `json:"gatewayCertSHA256"` + ProtocolVersion string `json:"protocolVersion"` +} + +// +kubebuilder:object:root=true +type MachineManagementSessionList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineManagementSession `json:"items"` +} + +// MachineManagementSessionBinding is protected admission evidence. Local UIDs +// are retained only as same-API-server recreation preconditions and are never +// projected through Karmada. +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status +type MachineManagementSessionBinding struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + // +kubebuilder:validation:XValidation:rule="self == oldSelf",message="admitted binding inputs are immutable" + Spec MachineManagementSessionBindingSpec `json:"spec"` + Status MachineManagementSessionBindingStatus `json:"status,omitempty"` +} + +type MachineManagementSessionBindingSpec struct { + SessionNamespace string `json:"sessionNamespace"` + SessionName string `json:"sessionName"` + SessionUID types.UID `json:"sessionUID"` + RequestingPrincipal string `json:"requestingPrincipal"` + ConsumerProject string `json:"consumerProject"` + ProviderProject string `json:"providerProject"` + MachineNamespace string `json:"machineNamespace"` + MachineName string `json:"machineName"` + MachineUID types.UID `json:"machineUID"` + AllocationName string `json:"allocationName"` + AllocationUID types.UID `json:"allocationUID"` + MachineCapacityNamespace string `json:"machineCapacityNamespace"` + MachineCapacityName string `json:"machineCapacityName"` + MachineCapacityUID types.UID `json:"machineCapacityUID"` + DeviceName string `json:"deviceName"` + LocationName string `json:"locationName"` + MemberCluster string `json:"memberCluster"` + Protocol string `json:"protocol"` + AccessProfile string `json:"accessProfile"` + ClientPublicKey string `json:"clientPublicKey"` + ConnectBefore metav1.Time `json:"connectBefore"` + ExpiresAt metav1.Time `json:"expiresAt"` + SessionCorrelationID string `json:"sessionCorrelationID"` + OperationCorrelationID string `json:"operationCorrelationID"` +} + +type MachineManagementSessionBindingStatus struct { + Connection *SessionConnection `json:"connection,omitempty"` + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +// +kubebuilder:object:root=true +type MachineManagementSessionBindingList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []MachineManagementSessionBinding `json:"items"` +} + +func AddToScheme(s *runtime.Scheme) error { + s.AddKnownTypes(GroupVersion, + &MachineManagementSession{}, &MachineManagementSessionList{}, + &MachineManagementSessionBinding{}, &MachineManagementSessionBindingList{}, + ) + metav1.AddToGroupVersion(s, GroupVersion) + return nil +} + +func (in *MachineManagementSession) DeepCopy() *MachineManagementSession { return copyJSON(in) } +func (in *MachineManagementSession) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionList) DeepCopy() *MachineManagementSessionList { return copyJSON(in) } +func (in *MachineManagementSessionList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionBinding) DeepCopy() *MachineManagementSessionBinding { + return copyJSON(in) +} +func (in *MachineManagementSessionBinding) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func (in *MachineManagementSessionBindingList) DeepCopy() *MachineManagementSessionBindingList { + return copyJSON(in) +} +func (in *MachineManagementSessionBindingList) DeepCopyObject() runtime.Object { return in.DeepCopy() } +func copyJSON[T any](in *T) *T { + b, _ := json.Marshal(in) + out := new(T) + _ = json.Unmarshal(b, out) + return out +} diff --git a/internal/api/session/v1alpha1/types_test.go b/internal/api/session/v1alpha1/types_test.go new file mode 100644 index 00000000..43e1cd5f --- /dev/null +++ b/internal/api/session/v1alpha1/types_test.go @@ -0,0 +1,82 @@ +package v1alpha1 + +import ( + "os" + "path/filepath" + "testing" + + extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/yaml" +) + +func TestAddToSchemeRegistersSessionKinds(t *testing.T) { + scheme := runtime.NewScheme() + if err := AddToScheme(scheme); err != nil { + t.Fatal(err) + } + for _, kind := range []string{"MachineManagementSession", "MachineManagementSessionList", "MachineManagementSessionBinding", "MachineManagementSessionBindingList"} { + if _, err := scheme.New(GroupVersion.WithKind(kind)); err != nil { + t.Errorf("kind %s is not registered: %v", kind, err) + } + } +} + +func TestGeneratedSessionCRDsDoNotProjectPrivateRouting(t *testing.T) { + public := readCRD(t, "metal.datumapis.com_machinemanagementsessions.yaml") + if public.Spec.Group != "metal.datumapis.com" { + t.Fatal("public CRD is outside Metal") + } + publicSpec := property(t, public, "spec") + if _, ok := publicSpec.Properties["machineRef"]; !ok { + t.Fatal("public session does not reference Machine") + } + if _, ok := publicSpec.Properties["machineClaimRef"]; ok { + t.Fatal("legacy MachineClaim reference remains public") + } + if len(publicSpec.XValidations) == 0 { + t.Fatal("public session spec is mutable") + } + + projected := readCRD(t, "coordination.fleet.datumapis.com_projectedmachinemanagementsessions.yaml") + if projected.Spec.Group != "coordination.fleet.datumapis.com" { + t.Fatal("projection CRD is outside coordination") + } + projectedSpec := property(t, projected, "spec") + for _, forbidden := range []string{"sessionUID", "machineUID", "allocationName", "bindingID", "bindingEpoch", "memberCluster", "locationUID", "adapterRoute", "bmcSystemID", "secretRef"} { + if _, ok := projectedSpec.Properties[forbidden]; ok { + t.Errorf("projected session leaks %s", forbidden) + } + } + if _, ok := projectedSpec.Properties["machineCapacityRef"]; !ok { + t.Fatal("projected session does not carry MachineCapacity identity") + } + if len(projectedSpec.XValidations) < 3 { + t.Fatal("projected session lacks immutable and monotonic authority validation") + } +} + +func readCRD(t *testing.T, name string) *extensionsv1.CustomResourceDefinition { + t.Helper() + data, err := os.ReadFile(filepath.Join("..", "..", "..", "..", "config", "crd", "bases", name)) + if err != nil { + t.Fatal(err) + } + var crd extensionsv1.CustomResourceDefinition + if err := yaml.Unmarshal(data, &crd); err != nil { + t.Fatal(err) + } + return &crd +} + +func property(t *testing.T, crd *extensionsv1.CustomResourceDefinition, name string) extensionsv1.JSONSchemaProps { + t.Helper() + if crd == nil || len(crd.Spec.Versions) != 1 || crd.Spec.Versions[0].Schema == nil || crd.Spec.Versions[0].Schema.OpenAPIV3Schema == nil { + t.Fatal("CRD schema is missing") + } + property, ok := crd.Spec.Versions[0].Schema.OpenAPIV3Schema.Properties[name] + if !ok { + t.Fatalf("CRD has no %s", name) + } + return property +} diff --git a/internal/cmd/fleet/root.go b/internal/cmd/fleet/root.go new file mode 100644 index 00000000..a57e44b1 --- /dev/null +++ b/internal/cmd/fleet/root.go @@ -0,0 +1,546 @@ +// SPDX-License-Identifier: Apache-2.0 + +package fleet + +import ( + "context" + "crypto/ecdsa" + "crypto/ed25519" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "math/big" + "net" + "net/http" + "net/http/httputil" + "net/url" + "os" + "os/signal" + "path/filepath" + "strings" + "sync" + "syscall" + "time" + + "github.com/spf13/cobra" + "go.datum.net/datumctl/plugin" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + "go.datum.net/fleet/internal/gateway" + "go.datum.net/fleet/internal/protocol" + "go.datum.net/fleet/internal/relay" +) + +const ( + ExitUsage = 2 + ExitAuth = 10 + ExitPermission = 11 + ExitAPI = 12 + ExitConnect = 13 +) + +type ExitError struct { + Code int + Err error +} + +func (e *ExitError) Error() string { return e.Err.Error() } +func (e *ExitError) Unwrap() error { return e.Err } + +type proxyOptions struct { + namespace, listen, credentialFile, readyFile, caFile, apiServer, apiCAFile string + ttl time.Duration +} + +func Command() *cobra.Command { + root := plugin.NewRootCmd("fleet", "Manage Datum Fleet resources") + mm := &cobra.Command{Use: "machine-management", Short: "Access allocation-scoped machine management"} + o := &proxyOptions{} + proxy := &cobra.Command{Use: "proxy MACHINE", Short: "Open a short-lived local Redfish endpoint", Args: cobra.ExactArgs(1), SilenceUsage: true, RunE: func(cmd *cobra.Command, args []string) error { return o.run(cmd.Context(), cmd, args[0]) }} + proxy.Flags().StringVar(&o.namespace, "namespace", "default", "Machine namespace") + proxy.Flags().StringVar(&o.listen, "listen", "127.0.0.1:0", "loopback address for the local Redfish endpoint") + proxy.Flags().DurationVar(&o.ttl, "ttl", 15*time.Minute, "session lifetime (1m-15m)") + proxy.Flags().StringVar(&o.credentialFile, "credential-file", "", "0600 JSON credential file (temporary when omitted)") + proxy.Flags().StringVar(&o.readyFile, "ready-file", "", "machine-readable non-secret readiness JSON") + proxy.Flags().StringVar(&o.caFile, "ca-file", "", "session CA bundle path (temporary when omitted)") + proxy.Flags().StringVar(&o.apiServer, "api-server", "", "Fleet/Kubernetes API URL (defaults to datumctl API context)") + proxy.Flags().StringVar(&o.apiCAFile, "api-ca-file", "", "CA bundle for the API server") + mm.AddCommand(proxy) + root.AddCommand(mm) + return root +} + +func (o *proxyOptions) run(parent context.Context, cmd *cobra.Command, machine string) error { + if o.ttl < time.Minute || o.ttl > 15*time.Minute { + return &ExitError{ExitUsage, errors.New("--ttl must be between 1m and 15m")} + } + pctx := plugin.Context() + if pctx.CredentialsHelper == "" { + return &ExitError{ExitAuth, errors.New("run datumctl-fleet through datumctl so the credential helper is available")} + } + if pctx.Project == "" { + return &ExitError{ExitUsage, errors.New("select a Datum project before creating a machine-management session")} + } + token, err := plugin.Token() + if err != nil { + return &ExitError{ExitAuth, fmt.Errorf("obtain credentials through datumctl: %w", err)} + } + api, err := newAPIClient(o, pctx.APIHost, token, pctx.Project) + if err != nil { + return &ExitError{ExitAPI, err} + } + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return &ExitError{ExitConnect, err} + } + defer clear(privateKey) + ctx, cancel := signal.NotifyContext(parent, os.Interrupt, syscall.SIGTERM) + defer cancel() + session, err := api.create(ctx, o.namespace, machine, protocol.PublicKey(privateKey), o.ttl) + if err != nil { + return classifyAPI(err) + } + sessionName := session.Name + defer func() { + revokeCtx, c := context.WithTimeout(context.Background(), 10*time.Second) + defer c() + _ = api.delete(revokeCtx, o.namespace, sessionName) + }() + session, err = api.waitReady(ctx, o.namespace, sessionName) + if err != nil { + return classifyAPI(err) + } + conn, err := connectLocation(ctx, privateKey, session) + if err != nil { + return &ExitError{ExitConnect, err} + } + defer conn.Close() + cleanup, endpoint, err := o.serveLocal(ctx, privateKey, session.Name, session.Status.Connection, conn) + if err != nil { + return &ExitError{ExitConnect, err} + } + defer cleanup() + fmt.Fprintf(cmd.OutOrStdout(), "Session %s is ready until %s\nRedfish endpoint: %s\nReadiness file: %s\n", session.Name, session.Status.ExpiresAt.UTC().Format(time.RFC3339), endpoint, o.readyFile) + <-ctx.Done() + return nil +} + +type apiClient struct { + base, project, token string + client *http.Client +} + +func newAPIClient(o *proxyOptions, host, token, project string) (*apiClient, error) { + base := o.apiServer + if base == "" { + if strings.Contains(host, "://") { + base = host + } else { + base = "https://" + host + } + } + if base == "https://" || base == "" { + return nil, errors.New("datumctl did not provide an API host") + } + transport := http.DefaultTransport.(*http.Transport).Clone() + if o.apiCAFile != "" { + b, err := os.ReadFile(o.apiCAFile) + if err != nil { + return nil, err + } + roots, _ := x509.SystemCertPool() + if roots == nil { + roots = x509.NewCertPool() + } + if !roots.AppendCertsFromPEM(b) { + return nil, errors.New("API CA bundle contains no certificates") + } + transport.TLSClientConfig = &tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12} + } + return &apiClient{base: strings.TrimRight(base, "/"), project: project, token: token, client: &http.Client{Transport: transport, Timeout: 30 * time.Second}}, nil +} +func (a *apiClient) url(ns, name string) string { + u := a.base + "/apis/metal.datumapis.com/v1alpha1/namespaces/" + url.PathEscape(ns) + "/machinemanagementsessions" + if name != "" { + u += "/" + url.PathEscape(name) + } + return u +} +func (a *apiClient) do(ctx context.Context, method, u string, body io.Reader, out any) error { + req, err := http.NewRequestWithContext(ctx, method, u, body) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+a.token) + req.Header.Set("X-Datum-Project", a.project) + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + resp, err := a.client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + b, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + return &apiError{status: resp.StatusCode, message: strings.TrimSpace(string(b))} + } + if out != nil && resp.StatusCode != http.StatusNoContent { + return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out) + } + return nil +} +func (a *apiClient) create(ctx context.Context, ns, machine, key string, ttl time.Duration) (*fleetv1alpha1.MachineManagementSession, error) { + s := &fleetv1alpha1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{GenerateName: machine + "-", Namespace: ns}, Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineRef: fleetv1alpha1.LocalReference{Name: machine}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: key, TTL: metav1.Duration{Duration: ttl}}} + b, _ := json.Marshal(s) + var out fleetv1alpha1.MachineManagementSession + if err := a.do(ctx, http.MethodPost, a.url(ns, ""), strings.NewReader(string(b)), &out); err != nil { + return nil, err + } + return &out, nil +} +func (a *apiClient) waitReady(ctx context.Context, ns, name string) (*fleetv1alpha1.MachineManagementSession, error) { + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + for { + var s fleetv1alpha1.MachineManagementSession + if err := a.do(ctx, http.MethodGet, a.url(ns, name), nil, &s); err != nil { + return nil, err + } + for _, c := range s.Status.Conditions { + if c.Type == fleetv1alpha1.ConditionReady && c.Status == metav1.ConditionTrue && s.Status.Connection != nil { + return &s, nil + } + if c.Type == fleetv1alpha1.ConditionReady && c.Status == metav1.ConditionFalse { + return nil, fmt.Errorf("session rejected: %s: %s", c.Reason, c.Message) + } + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-ticker.C: + } + } +} +func (a *apiClient) delete(ctx context.Context, ns, name string) error { + return a.do(ctx, http.MethodDelete, a.url(ns, name), nil, nil) +} + +type apiError struct { + status int + message string +} + +func (e *apiError) Error() string { return fmt.Sprintf("API returned %d: %s", e.status, e.message) } +func classifyAPI(err error) error { + var e *apiError + if errors.As(err, &e) { + if e.status == http.StatusUnauthorized { + return &ExitError{ExitAuth, err} + } + if e.status == http.StatusForbidden { + return &ExitError{ExitPermission, err} + } + } + return &ExitError{ExitAPI, err} +} + +func connectLocation(ctx context.Context, key ed25519.PrivateKey, s *fleetv1alpha1.MachineManagementSession) (net.Conn, error) { + c := s.Status.Connection + if c == nil { + return nil, errors.New("session has no connection") + } + u, err := url.Parse(c.RelayURL) + if err != nil || u.Scheme != "tcp" { + return nil, fmt.Errorf("unsupported relay URL %q", c.RelayURL) + } + d := net.Dialer{} + raw, err := d.DialContext(ctx, "tcp", u.Host) + if err != nil { + return nil, fmt.Errorf("reach relay: %w", err) + } + if err := relay.Connect(raw, c.RouteID); err != nil { + _ = raw.Close() + return nil, err + } + expected, err := hex.DecodeString(c.GatewayCertSHA256) + if err != nil || len(expected) != sha256.Size { + _ = raw.Close() + return nil, errors.New("session published an invalid gateway certificate pin") + } + tlsConn := tls.Client(raw, &tls.Config{MinVersion: tls.VersionTLS13, ServerName: "fleet-gateway", NextProtos: []string{"datum-fleet-redfish/1"}, InsecureSkipVerify: true, VerifyConnection: func(cs tls.ConnectionState) error { + if len(cs.PeerCertificates) != 1 { + return errors.New("gateway certificate chain must contain one pinned certificate") + } + sum := sha256.Sum256(cs.PeerCertificates[0].Raw) + if !equal(sum[:], expected) { + return errors.New("gateway certificate does not match the admitted session") + } + return nil + }}) + if err := tlsConn.HandshakeContext(ctx); err != nil { + _ = raw.Close() + return nil, fmt.Errorf("authenticate location gateway: %w", err) + } + return tlsConn, nil +} + +func (o *proxyOptions) serveLocal(ctx context.Context, key ed25519.PrivateKey, sessionName string, c *fleetv1alpha1.SessionConnection, remote net.Conn) (func(), string, error) { + listener, err := net.Listen("tcp", o.listen) + if err != nil { + return nil, "", err + } + if !isLoopback(listener.Addr()) { + _ = listener.Close() + return nil, "", errors.New("local Redfish endpoint must listen on loopback") + } + cert, caPEM, err := localCertificate() + if err != nil { + _ = listener.Close() + return nil, "", err + } + dir, err := os.MkdirTemp("", "datumctl-fleet-") + if err != nil { + _ = listener.Close() + return nil, "", err + } + removeDir := true + if o.caFile == "" { + o.caFile = filepath.Join(dir, "ca.pem") + } + if o.credentialFile == "" { + o.credentialFile = filepath.Join(dir, "credentials.json") + } + if o.readyFile == "" { + o.readyFile = filepath.Join(dir, "ready.json") + } + cleanup := func() { + _ = listener.Close() + _ = remote.Close() + _ = os.Remove(o.credentialFile) + _ = os.Remove(o.caFile) + _ = os.Remove(o.readyFile) + if removeDir { + _ = os.Remove(dir) + } + } + if err := os.WriteFile(o.caFile, caPEM, 0o600); err != nil { + cleanup() + return nil, "", err + } + password := randomSecret() + username := "fleet" + endpoint := "https://" + listener.Addr().String() + "/redfish/v1/" + credential := map[string]string{"endpoint": endpoint, "username": username, "password": password, "caBundle": o.caFile} + if err := writeJSONFile(o.credentialFile, credential, 0o600); err != nil { + cleanup() + return nil, "", err + } + ready := map[string]any{"ready": true, "endpoint": endpoint, "credentialFile": o.credentialFile, "caBundle": o.caFile, "session": sessionName} + if err := writeJSONFile(o.readyFile, ready, 0o644); err != nil { + cleanup() + return nil, "", err + } + transport := &http.Transport{ForceAttemptHTTP2: false, DialTLSContext: singleDialer(remote)} + proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: "https", Host: "fleet-gateway"}) + proxy.Transport = transport + original := proxy.Director + proxy.Director = func(r *http.Request) { + original(r) + r.Host = "fleet-gateway" + r.Header.Del("Authorization") + r.Header.Del("X-Auth-Token") + p, _ := protocol.Sign(key, c.RouteID, c.GatewayAudience, time.Now()) + r.Header.Set(gateway.HeaderSession, c.RouteID) + r.Header.Set(gateway.HeaderAudience, c.GatewayAudience) + r.Header.Set(gateway.HeaderTimestamp, p.Timestamp) + r.Header.Set(gateway.HeaderNonce, p.Nonce) + r.Header.Set(gateway.HeaderSignature, p.Signature) + } + local := newLocalAuth(username, password, proxy) + server := &http.Server{Handler: local, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 30 * time.Second} + tlsListener := tls.NewListener(listener, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13}) + go func() { + <-ctx.Done() + shutdown, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = server.Shutdown(shutdown) + }() + go func() { _ = server.Serve(tlsListener) }() + return cleanup, endpoint, nil +} + +func singleDialer(conn net.Conn) func(context.Context, string, string) (net.Conn, error) { + var mu sync.Mutex + used := false + return func(context.Context, string, string) (net.Conn, error) { + mu.Lock() + defer mu.Unlock() + if used { + return nil, errors.New("location connection is single-use") + } + used = true + return conn, nil + } +} +func newLocalAuth(user, password string, next http.Handler) http.Handler { + tokens := map[string]bool{} + var mu sync.Mutex + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !validLocalTarget(r) { + http.Error(w, "arbitrary local targets and Host routing are not accepted", http.StatusBadRequest) + return + } + // Generic Redfish clients discover the service root before creating a + // session. It contains only virtual links and still crosses the admitted, + // proof-protected gateway stream. + if r.Method == http.MethodGet && (r.URL.Path == "/redfish/v1" || r.URL.Path == "/redfish/v1/") { + // DMTF clients commonly probe the slashless URI first. Canonicalize it + // for the virtual gateway without redirecting or exposing another host. + if r.URL.Path == "/redfish/v1" { + r.URL.Path = "/redfish/v1/" + } + next.ServeHTTP(w, r) + return + } + if r.Method == http.MethodPost && r.URL.Path == "/redfish/v1/SessionService/Sessions" { + var in struct { + UserName string `json:"UserName"` + Password string `json:"Password"` + } + if json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&in) != nil || in.UserName != user || in.Password != password { + http.Error(w, "invalid local Redfish credentials", http.StatusUnauthorized) + return + } + token := randomSecret() + mu.Lock() + tokens[token] = true + mu.Unlock() + w.Header().Set("X-Auth-Token", token) + w.Header().Set("Location", "/redfish/v1/SessionService/Sessions/local") + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = io.WriteString(w, `{"@odata.id":"/redfish/v1/SessionService/Sessions/local","Id":"local","Name":"Fleet local session"}`) + return + } + if r.Method == http.MethodDelete && r.URL.Path == "/redfish/v1/SessionService/Sessions/local" { + token := r.Header.Get("X-Auth-Token") + mu.Lock() + valid := tokens[token] + if valid { + delete(tokens, token) + } + mu.Unlock() + if !valid { + http.Error(w, "invalid local Redfish session", http.StatusUnauthorized) + return + } + w.WriteHeader(http.StatusNoContent) + return + } + authorized := false + if u, p, ok := r.BasicAuth(); ok && u == user && p == password { + authorized = true + } + mu.Lock() + if tokens[r.Header.Get("X-Auth-Token")] { + authorized = true + } + mu.Unlock() + if !authorized { + w.Header().Set("WWW-Authenticate", `Basic realm="Fleet Redfish"`) + http.Error(w, "local Redfish authentication required", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, r) + }) +} + +func validLocalTarget(r *http.Request) bool { + if r.URL.IsAbs() || r.RequestURI == "*" || strings.Contains(r.URL.Path, "..") || !strings.HasPrefix(r.URL.Path, "/redfish/v1") { + return false + } + if r.URL.RawPath != "" { + unescaped, err := url.PathUnescape(r.URL.RawPath) + if err != nil || unescaped != r.URL.Path { + return false + } + } + host := r.Host + if parsed, _, err := net.SplitHostPort(host); err == nil { + host = parsed + } + host = strings.Trim(host, "[]") + return host == "localhost" || (net.ParseIP(host) != nil && net.ParseIP(host).IsLoopback()) +} +func localCertificate() (tls.Certificate, []byte, error) { + priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return tls.Certificate{}, nil, err + } + pub := &priv.PublicKey + serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + now := time.Now() + tmpl := x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "datumctl-fleet local Redfish"}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(time.Hour), IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, DNSNames: []string{"localhost"}, KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IsCA: true, BasicConstraintsValid: true} + der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, pub, priv) + if err != nil { + return tls.Certificate{}, nil, err + } + keyDER, _ := x509.MarshalPKCS8PrivateKey(priv) + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}) + cert, err := tls.X509KeyPair(certPEM, keyPEM) + return cert, certPEM, err +} +func randomSecret() string { b := make([]byte, 24); _, _ = rand.Read(b); return hex.EncodeToString(b) } +func writeJSONFile(path string, v any, mode os.FileMode) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + b, err := json.MarshalIndent(v, "", " ") + if err != nil { + return err + } + f, err := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) + if err != nil { + return err + } + if err := f.Chmod(mode); err != nil { + _ = f.Close() + return err + } + if _, err := f.Write(b); err != nil { + _ = f.Close() + return err + } + return f.Close() +} +func isLoopback(addr net.Addr) bool { + host, _, err := net.SplitHostPort(addr.String()) + if err != nil { + return false + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} +func equal(a, b []byte) bool { + if len(a) != len(b) { + return false + } + var v byte + for i := range a { + v |= a[i] ^ b[i] + } + return v == 0 +} diff --git a/internal/cmd/fleet/root_test.go b/internal/cmd/fleet/root_test.go new file mode 100644 index 00000000..86480c12 --- /dev/null +++ b/internal/cmd/fleet/root_test.go @@ -0,0 +1,83 @@ +package fleet + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestLocalRedfishSessionCanBeDeleted(t *testing.T) { + nextCalls := 0 + h := newLocalAuth("fleet", "secret", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { nextCalls++ })) + login := httptest.NewRequest(http.MethodPost, "/redfish/v1/SessionService/Sessions", strings.NewReader(`{"UserName":"fleet","Password":"secret"}`)) + login.Host = "127.0.0.1:9443" + w := httptest.NewRecorder() + h.ServeHTTP(w, login) + if w.Code != http.StatusCreated || w.Header().Get("X-Auth-Token") == "" { + t.Fatalf("login: %d %#v", w.Code, w.Header()) + } + token := w.Header().Get("X-Auth-Token") + del := httptest.NewRequest(http.MethodDelete, "/redfish/v1/SessionService/Sessions/local", nil) + del.Host = "127.0.0.1:9443" + del.Header.Set("X-Auth-Token", token) + w = httptest.NewRecorder() + h.ServeHTTP(w, del) + if w.Code != http.StatusNoContent { + t.Fatalf("delete: %d", w.Code) + } + get := httptest.NewRequest(http.MethodGet, "/redfish/v1/Systems", nil) + get.Host = "127.0.0.1:9443" + get.Header.Set("X-Auth-Token", token) + w = httptest.NewRecorder() + h.ServeHTTP(w, get) + if w.Code != http.StatusUnauthorized || nextCalls != 0 { + t.Fatalf("deleted token accepted: status=%d calls=%d", w.Code, nextCalls) + } +} + +func TestLocalConnectorAllowsSlashlessServiceRootDiscovery(t *testing.T) { + called := false + h := newLocalAuth("fleet", "secret", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + called = true + if r.URL.Path != "/redfish/v1/" { + t.Fatalf("path = %q, want canonical service root", r.URL.Path) + } + })) + r := httptest.NewRequest(http.MethodGet, "/redfish/v1", nil) + r.Host = "127.0.0.1:9443" + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if !called || w.Code != http.StatusOK { + t.Fatalf("service root discovery: called=%v status=%d", called, w.Code) + } +} + +func TestLocalConnectorRejectsArbitraryRouting(t *testing.T) { + h := newLocalAuth("fleet", "secret", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + t.Fatal("rejected target reached proxy") + })) + for _, test := range []struct { + target string + host string + }{ + {target: "/redfish/v1/Systems", host: "bmc.private"}, + {target: "http://bmc.private/redfish/v1/Systems", host: "bmc.private"}, + {target: "/redfish/v1/Systems/../Managers", host: "127.0.0.1:9443"}, + } { + r := httptest.NewRequest(http.MethodGet, test.target, nil) + r.Host = test.host + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != http.StatusBadRequest { + t.Fatalf("target=%q host=%q: %d", test.target, test.host, w.Code) + } + } +} + +func TestSessionClientUsesMetalAPI(t *testing.T) { + a := &apiClient{base: "https://api.example.invalid"} + if got, want := a.url("default", "session-a"), "https://api.example.invalid/apis/metal.datumapis.com/v1alpha1/namespaces/default/machinemanagementsessions/session-a"; got != want { + t.Fatalf("session endpoint = %q, want %q", got, want) + } +} diff --git a/internal/controller/admission.go b/internal/controller/admission.go new file mode 100644 index 00000000..b9e4348c --- /dev/null +++ b/internal/controller/admission.go @@ -0,0 +1,59 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "encoding/json" + "reflect" + "time" + + admissionv1 "k8s.io/api/admission/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +// SessionAdmission retains the authenticated API principal before the +// asynchronous controller resolves private allocation state. Kubernetes RBAC +// separately controls create on sessions; claim read permission does not imply it. +type SessionAdmission struct{} + +func (SessionAdmission) Handle(_ context.Context, req admission.Request) admission.Response { + var session fleetv1alpha1.MachineManagementSession + if err := json.Unmarshal(req.Object.Raw, &session); err != nil { + return admission.Errored(400, err) + } + if req.Operation == admissionv1.Update { + var old fleetv1alpha1.MachineManagementSession + if err := json.Unmarshal(req.OldObject.Raw, &old); err != nil { + return admission.Errored(400, err) + } + if !reflect.DeepEqual(session.Spec, old.Spec) { + return admission.Denied("spec is immutable; create a new session") + } + if session.Annotations[PrincipalAnnotation] != old.Annotations[PrincipalAnnotation] { + return admission.Denied("requesting principal is service-owned") + } + return admission.Allowed("immutable session update") + } + if req.Operation != admissionv1.Create { + return admission.Allowed("no mutation required") + } + if session.Spec.Protocol != "Redfish" || session.Spec.AccessProfile != "Provisioning" { + return admission.Denied("only the Redfish Provisioning profile is supported") + } + if session.Spec.TTL.Duration == 0 { + session.Spec.TTL = metav1.Duration{Duration: 15 * time.Minute} + } + if session.Annotations == nil { + session.Annotations = map[string]string{} + } + session.Annotations[PrincipalAnnotation] = req.UserInfo.Username + mutated, err := json.Marshal(&session) + if err != nil { + return admission.Errored(500, err) + } + return admission.PatchResponseFromRaw(req.Object.Raw, mutated) +} diff --git a/internal/controller/admission_test.go b/internal/controller/admission_test.go new file mode 100644 index 00000000..0ce7c6fc --- /dev/null +++ b/internal/controller/admission_test.go @@ -0,0 +1,36 @@ +package controller + +import ( + "context" + "encoding/json" + "testing" + + admissionv1 "k8s.io/api/admission/v1" + authnv1 "k8s.io/api/authentication/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +func TestAdmissionRetainsAuthenticatedPrincipal(t *testing.T) { + s := fleetv1alpha1.MachineManagementSession{Spec: fleetv1alpha1.MachineManagementSessionSpec{MachineRef: fleetv1alpha1.LocalReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}} + raw, _ := json.Marshal(s) + resp := SessionAdmission{}.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{Operation: admissionv1.Create, Object: runtime.RawExtension{Raw: raw}, UserInfo: authnv1.UserInfo{Username: "alice@example.test"}}}) + if !resp.Allowed || len(resp.Patches) == 0 { + t.Fatalf("response %+v", resp) + } +} + +func TestAdmissionRejectsSpecMutation(t *testing.T) { + old := fleetv1alpha1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Annotations: map[string]string{PrincipalAnnotation: "alice"}}, Spec: fleetv1alpha1.MachineManagementSessionSpec{Protocol: "Redfish", AccessProfile: "Provisioning"}} + newObj := *old.DeepCopy() + newObj.Spec.AccessProfile = "Other" + oldRaw, _ := json.Marshal(old) + newRaw, _ := json.Marshal(newObj) + resp := SessionAdmission{}.Handle(context.Background(), admission.Request{AdmissionRequest: admissionv1.AdmissionRequest{Operation: admissionv1.Update, Object: runtime.RawExtension{Raw: newRaw}, OldObject: runtime.RawExtension{Raw: oldRaw}}}) + if resp.Allowed { + t.Fatal("mutable spec accepted") + } +} diff --git a/internal/controller/lifecycle.go b/internal/controller/lifecycle.go index d1f2a0db..00df5d47 100644 --- a/internal/controller/lifecycle.go +++ b/internal/controller/lifecycle.go @@ -29,8 +29,9 @@ import ( ) const ( - MachineFinalizer = "fleet.datumapis.com/machine-protection" - recordSchemaVersion = 1 + MachineFinalizer = "fleet.datumapis.com/machine-protection" + recordSchemaVersion = 1 + assetRecordSchemaVersion = 2 // Installation records gained retained public routing identities in v2. // v1 is accepted only by the explicit request-bound upgrader below. installationRecordSchemaVersion = 2 @@ -116,6 +117,8 @@ type AssetRecord struct { MachineNamespace string `json:"machineNamespace"` MachineName string `json:"machineName"` MachineUID types.UID `json:"machineUID"` + DeviceName string `json:"deviceName,omitempty"` + LocationName string `json:"locationName,omitempty"` ClaimNamespace string `json:"claimNamespace"` ClaimName string `json:"claimName"` ClaimUID types.UID `json:"claimUID"` @@ -133,6 +136,7 @@ type AssetRecord struct { FenceToken string `json:"fenceToken"` CurrentInstallationName string `json:"currentInstallationName"` ActiveOperationID string `json:"activeOperationID,omitempty"` + Management *ManagementSessionRecord `json:"management,omitempty"` AcceptedRequirements fleetv1.MachineProfileSpec `json:"acceptedRequirements"` Hardware fleetv1.Hardware `json:"hardware"` Network *NetworkRecord `json:"network,omitempty"` @@ -552,6 +556,9 @@ func (c *Coordinator) recordCandidateEligible(record *AssetRecord, request Alloc } func validateAssetForRequest(record *AssetRecord, request AllocationRequest) error { + if record.SchemaVersion == assetRecordSchemaVersion && record.LocationName != request.Claim.Spec.LocationRef.Name { + return fmt.Errorf("%w: retained allocation location differs from retry", ErrRecordInvalid) + } // Specs contain slices, so compare their canonical JSON rather than // allowing a recovered Preparing record to drift across retries. got, _ := json.Marshal(record.AcceptedRequirements) @@ -792,8 +799,9 @@ func (c *Coordinator) proposeAsset(ctx context.Context, request AllocationReques } func newAssetRecord(request AllocationRequest, machine *fleetv1.MachineCapacity, assetID string, epoch int64, bindingID, fenceToken string) *AssetRecord { - record := &AssetRecord{SchemaVersion: recordSchemaVersion, State: AssetPreparing, AssetID: assetID, + record := &AssetRecord{SchemaVersion: assetRecordSchemaVersion, State: AssetPreparing, AssetID: assetID, MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, + DeviceName: machine.Spec.DeviceRef.Name, LocationName: request.Claim.Spec.LocationRef.Name, ClaimNamespace: request.Claim.Namespace, ClaimName: request.Claim.Name, ClaimUID: request.Claim.UID, ClaimScope: allocationClaimScope(request), ClassUID: request.Class.UID, ProfileUID: request.Profile.UID, LocalClassUID: localClassUID(request), LocalProfileUID: localProfileUID(request), ConsumerProject: request.ConsumerProject, ProviderProject: request.ProviderProject, Authority: request.Authority, ExternalHold: request.ExternalHold, @@ -1001,6 +1009,12 @@ func (c *Coordinator) release(ctx context.Context, scope ClaimScope, claimUID ty if custody.State != CustodyBound || custody.AssetID != record.AssetID { return ReleaseResult{}, fmt.Errorf("%w: custody and asset authority disagree", ErrRecordInvalid) } + if managementHeld(record) { + if err := c.revokeManagement(ctx, record.AssetID, claimUID, true); err != nil { + return ReleaseResult{}, err + } + return ReleaseResult{State: AssetReleasing}, ErrManagementActive + } if record.ActiveOperationID != "" { if err := c.settleActiveOperation(ctx, record); err != nil { return ReleaseResult{State: record.State}, err @@ -1445,6 +1459,12 @@ func (c *Coordinator) activateOperation(ctx context.Context, assetID string, cla if record.ClaimUID != claimUID || record.State != AssetCommitted || record.CurrentInstallationName != predecessor { return ErrPredecessorConflict } + if managementHeld(record) { + if err := c.revokeManagement(ctx, assetID, claimUID, false); err != nil { + return err + } + return ErrManagementActive + } if record.ActiveOperationID != "" && record.ActiveOperationID != operationID { return ErrOperationActive } @@ -1539,7 +1559,7 @@ func (c *Coordinator) setAssetState(ctx context.Context, assetID string, claimUI if err != nil { return nil, err } - if record.ClaimUID != claimUID || record.State != from || record.ActiveOperationID != "" { + if record.ClaimUID != claimUID || record.State != from || record.ActiveOperationID != "" || managementHeld(record) { return nil, fmt.Errorf("%w: asset transition %s to %s rejected", ErrRecordInvalid, record.State, to) } record.State = to @@ -1988,7 +2008,7 @@ func decodeLegacyOperationSecret(secret *corev1.Secret) (*InstallationRecord, er } func validateAssetRecord(r *AssetRecord) error { - if r.SchemaVersion != recordSchemaVersion || r.AssetID == "" || r.MachineNamespace == "" || r.MachineName == "" || r.MachineUID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.ClassUID == "" || r.ProfileUID == "" || r.LocalClassUID == "" || r.LocalProfileUID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" || r.CurrentInstallationName == "" { + if (r.SchemaVersion != recordSchemaVersion && r.SchemaVersion != assetRecordSchemaVersion) || r.SchemaVersion == recordSchemaVersion && r.Management != nil || r.AssetID == "" || r.MachineNamespace == "" || r.MachineName == "" || r.MachineUID == "" || r.ClaimNamespace == "" || r.ClaimName == "" || r.ClaimUID == "" || !r.ClaimScope.Valid() || r.ClassUID == "" || r.ProfileUID == "" || r.LocalClassUID == "" || r.LocalProfileUID == "" || r.BindingID == "" || r.Epoch < 1 || r.FenceToken == "" || r.CurrentInstallationName == "" { return ErrRecordInvalid } projectAuthority := r.ConsumerProject.Valid() || r.ProviderProject.Valid() || r.Authority.Valid() || r.ExternalHold.Valid() @@ -1998,6 +2018,9 @@ func validateAssetRecord(r *AssetRecord) error { if r.ConsumerProject.Valid() && r.ClaimScope != ProjectClaimScope(r.ConsumerProject) { return ErrRecordInvalid } + if r.Management != nil && validateManagementRecord(r) != nil { + return ErrRecordInvalid + } switch r.State { case AssetPreparing, AssetCommitted, AssetReleasing, AssetCleanupVerified, AssetReleased: default: diff --git a/internal/controller/management_lifecycle.go b/internal/controller/management_lifecycle.go new file mode 100644 index 00000000..5aa85f75 --- /dev/null +++ b/internal/controller/management_lifecycle.go @@ -0,0 +1,326 @@ +package controller + +import ( + "context" + "errors" + "time" + + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/equality" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +var ErrManagementActive = errors.New("management session teardown is not verified") + +type ManagementSessionRecord struct { + Binding sessionv1.MachineManagementSessionBindingSpec `json:"binding"` + Revoking bool `json:"revoking"` + Completed bool `json:"completed"` + ProjectionAdmitted bool `json:"projectionAdmitted"` +} + +type ManagementAccess struct { + Scope ClaimScope + ConsumerProject ProjectIdentity + ProviderProject ProjectIdentity + NamespaceUID types.UID + MachineUID types.UID + CapacityNamespace string + CapacityName string + CapacityUID types.UID + DeviceName string + MemberCluster string + LocationName string +} + +type ManagementAccessResolver interface { + ResolveManagementAccess(context.Context, sessionv1.MachineManagementSessionBindingSpec) (ManagementAccess, error) +} + +type SessionLifecycle interface { + Recover(context.Context, *sessionv1.MachineManagementSession) (*sessionv1.MachineManagementSessionBindingSpec, error) + Prepare(context.Context, sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) + Acquire(context.Context, sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) + Active(context.Context, *sessionv1.MachineManagementSessionBinding) bool + Complete(context.Context, *sessionv1.MachineManagementSessionBinding) error + BeginProjection(context.Context, *sessionv1.MachineManagementSessionBinding) error + CancelUnprojected(context.Context, *sessionv1.MachineManagementSessionBinding) (bool, error) +} + +func (a *LifecycleSessionAuthority) BeginProjection(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) error { + if !a.Active(ctx, binding) || binding.Annotations[RevokedAtAnnotation] != "" { + return ErrManagementActive + } + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + secret, asset, err := a.readBindingAsset(ctx, binding) + if err != nil { + return err + } + if !managementHeld(asset) || asset.State != AssetCommitted || asset.Management.Revoking || !equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) { + return ErrManagementActive + } + if asset.Management.ProjectionAdmitted { + return nil + } + asset.Management.ProjectionAdmitted = true + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + return a.Coordinator.client.Update(ctx, secret) + }) +} + +func (a *LifecycleSessionAuthority) CancelUnprojected(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) (bool, error) { + if a == nil || a.Coordinator == nil || binding.Annotations[RevokedAtAnnotation] == "" { + return false, ErrManagementActive + } + completed := false + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + secret, asset, err := a.readBindingAsset(ctx, binding) + if err != nil { + return err + } + if asset.Management == nil || !equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) { + return ErrRecordInvalid + } + if asset.Management.ProjectionAdmitted { + return nil + } + asset.Management.Revoking = true + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + if err := a.Coordinator.client.Update(ctx, secret); err != nil { + return err + } + completed = true + return nil + }) + return completed, err +} + +func (a *LifecycleSessionAuthority) Recover(ctx context.Context, session *sessionv1.MachineManagementSession) (*sessionv1.MachineManagementSessionBindingSpec, error) { + if a == nil || a.Coordinator == nil { + return nil, ErrUnsupported + } + var records corev1.SecretList + if err := a.Coordinator.client.List(ctx, &records, client.InNamespace(a.Coordinator.namespace), client.MatchingLabels{recordTypeLabel: "asset"}); err != nil { + return nil, err + } + var retained *sessionv1.MachineManagementSessionBindingSpec + for index := range records.Items { + asset, err := decodeAssetSecret(&records.Items[index]) + if err != nil { + return nil, err + } + if asset.Management == nil || asset.Management.Binding.SessionUID != session.UID { + continue + } + binding := asset.Management.Binding + if retained != nil || binding.SessionNamespace != session.Namespace || binding.SessionName != session.Name || binding.MachineName != session.Spec.MachineRef.Name || binding.RequestingPrincipal != session.Annotations[PrincipalAnnotation] || binding.ClientPublicKey != session.Spec.ClientPublicKey || binding.Protocol != session.Spec.Protocol || binding.AccessProfile != session.Spec.AccessProfile { + return nil, ErrRecordInvalid + } + retained = &binding + } + return retained, nil +} + +func (a *LifecycleSessionAuthority) Prepare(ctx context.Context, binding sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) { + asset, access, err := a.resolve(ctx, binding) + if err != nil { + return binding, err + } + binding.ConsumerProject, binding.ProviderProject = access.ConsumerProject.RouteName, access.ProviderProject.RouteName + binding.AllocationName, binding.AllocationUID = assetRecordName(asset.AssetID), types.UID(asset.BindingID) + binding.MachineCapacityNamespace, binding.MachineCapacityName, binding.MachineCapacityUID = asset.MachineNamespace, asset.MachineName, asset.MachineUID + binding.DeviceName, binding.LocationName, binding.MemberCluster = asset.DeviceName, asset.LocationName, access.MemberCluster + return binding, nil +} + +type LifecycleSessionAuthority struct { + Coordinator *Coordinator + Resolver ManagementAccessResolver +} + +func (a *LifecycleSessionAuthority) resolve(ctx context.Context, binding sessionv1.MachineManagementSessionBindingSpec) (*AssetRecord, ManagementAccess, error) { + if a == nil || a.Coordinator == nil || a.Resolver == nil || binding.RequestingPrincipal == "" || binding.MachineUID == "" { + return nil, ManagementAccess{}, ErrUnsupported + } + access, err := a.Resolver.ResolveManagementAccess(ctx, binding) + if err != nil { + return nil, access, err + } + if !access.Scope.Valid() || !access.ConsumerProject.Valid() || !access.ProviderProject.Valid() || access.MemberCluster == "" || access.LocationName == "" || access.Scope.ProjectUID != access.ConsumerProject.UID || access.Scope.AuthorityID != access.ConsumerProject.AuthorityID { + return nil, access, ErrRecordInvalid + } + custody, _, err := a.Coordinator.getCustodyScoped(ctx, access.Scope, binding.MachineUID) + if err != nil { + return nil, access, err + } + if custody.State != CustodyBound || custody.ClaimName != binding.MachineName || custody.ClaimNamespace != binding.MachineNamespace || custody.NamespaceUID != access.NamespaceUID || access.MachineUID != binding.MachineUID { + return nil, access, ErrRecordInvalid + } + asset, _, err := a.Coordinator.getAsset(ctx, custody.AssetID) + if err != nil { + return nil, access, err + } + if asset.SchemaVersion != assetRecordSchemaVersion { + return nil, access, ErrRecordInvalid + } + if custody.ConsumerProject != asset.ConsumerProject || custody.ProviderProject != asset.ProviderProject || custody.Authority != asset.Authority || custody.ExternalHold != asset.ExternalHold { + return nil, access, ErrRecordInvalid + } + if asset.ClaimScope != access.Scope || asset.ClaimUID != binding.MachineUID || asset.ClaimName != binding.MachineName || asset.ClaimNamespace != binding.MachineNamespace || asset.State != AssetCommitted || asset.DeviceName == "" || asset.DeviceName != access.DeviceName || asset.MachineNamespace != access.CapacityNamespace || asset.MachineName != access.CapacityName || asset.MachineUID != access.CapacityUID || asset.LocationName != access.LocationName || asset.ActiveOperationID != "" { + return nil, access, ErrRecordInvalid + } + if asset.ConsumerProject.Valid() && (asset.ConsumerProject != access.ConsumerProject || asset.ProviderProject != access.ProviderProject) { + return nil, access, ErrRecordInvalid + } + return asset, access, nil +} + +func (a *LifecycleSessionAuthority) Acquire(ctx context.Context, proposed sessionv1.MachineManagementSessionBindingSpec) (sessionv1.MachineManagementSessionBindingSpec, error) { + proposed.ConnectBefore = metav1.NewTime(proposed.ConnectBefore.UTC().Truncate(time.Second)) + proposed.ExpiresAt = metav1.NewTime(proposed.ExpiresAt.UTC().Truncate(time.Second)) + var retained sessionv1.MachineManagementSessionBindingSpec + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + asset, access, err := a.resolve(ctx, proposed) + if err != nil { + return err + } + current, secret, err := a.Coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + return err + } + if !equality.Semantic.DeepEqual(current, asset) { + return ErrOperationActive + } + binding := proposed + binding.ConsumerProject, binding.ProviderProject = access.ConsumerProject.RouteName, access.ProviderProject.RouteName + binding.AllocationName, binding.AllocationUID = secret.Name, types.UID(asset.BindingID) + binding.MachineCapacityNamespace, binding.MachineCapacityName, binding.MachineCapacityUID = asset.MachineNamespace, asset.MachineName, asset.MachineUID + binding.DeviceName, binding.LocationName, binding.MemberCluster = asset.DeviceName, asset.LocationName, access.MemberCluster + if asset.Management != nil && asset.Management.Binding.SessionUID == binding.SessionUID { + previous := asset.Management.Binding + binding.ConnectBefore, binding.ExpiresAt = previous.ConnectBefore, previous.ExpiresAt + binding.SessionCorrelationID, binding.OperationCorrelationID = previous.SessionCorrelationID, previous.OperationCorrelationID + if !equality.Semantic.DeepEqual(previous, binding) || asset.Management.Completed { + return ErrRecordInvalid + } + retained = previous + return nil + } + if managementHeld(asset) { + return ErrManagementActive + } + asset.Management = &ManagementSessionRecord{Binding: binding} + if err := validateManagementRecord(asset); err != nil { + return err + } + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + if err := a.Coordinator.client.Update(ctx, secret); err != nil { + return err + } + retained = binding + return nil + }) + return retained, err +} + +func (a *LifecycleSessionAuthority) Active(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) bool { + asset, access, err := a.resolve(ctx, binding.Spec) + return err == nil && managementHeld(asset) && !asset.Management.Revoking && equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) && access.MemberCluster == binding.Spec.MemberCluster && access.ConsumerProject.RouteName == binding.Spec.ConsumerProject && access.ProviderProject.RouteName == binding.Spec.ProviderProject +} + +func (a *LifecycleSessionAuthority) Complete(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) error { + if a == nil || a.Coordinator == nil || binding.Annotations[RevokedAtAnnotation] == "" { + return ErrManagementActive + } + condition := apimeta.FindStatusCondition(binding.Status.Conditions, "CleanupConfirmed") + if condition == nil || condition.Status != metav1.ConditionTrue || condition.ObservedGeneration != binding.Generation { + return ErrManagementActive + } + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + return a.complete(ctx, binding) + }) +} + +func (a *LifecycleSessionAuthority) readBindingAsset(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) (*corev1.Secret, *AssetRecord, error) { + var secret corev1.Secret + if err := a.Coordinator.client.Get(ctx, client.ObjectKey{Namespace: a.Coordinator.namespace, Name: binding.Spec.AllocationName}, &secret); err != nil { + return nil, nil, err + } + asset, err := decodeAssetSecret(&secret) + if err != nil { + return nil, nil, err + } + if secret.Name != assetRecordName(asset.AssetID) { + return nil, nil, ErrRecordInvalid + } + return &secret, asset, nil +} + +func (a *LifecycleSessionAuthority) complete(ctx context.Context, binding *sessionv1.MachineManagementSessionBinding) error { + secret, asset, err := a.readBindingAsset(ctx, binding) + if err != nil { + return err + } + if string(binding.Spec.AllocationUID) != asset.BindingID || asset.Management != nil && asset.Management.Binding.SessionUID != binding.Spec.SessionUID { + return nil + } + if asset.Management == nil || !equality.Semantic.DeepEqual(asset.Management.Binding, binding.Spec) { + return ErrRecordInvalid + } + if asset.Management.Completed { + return nil + } + asset.Management.Revoking, asset.Management.Completed = true, true + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + return a.Coordinator.client.Update(ctx, secret) +} + +func managementHeld(asset *AssetRecord) bool { + return asset.Management != nil && !asset.Management.Completed +} + +func validateManagementRecord(asset *AssetRecord) error { + record := asset.Management + binding := record.Binding + if binding.SessionUID == "" || binding.SessionName == "" || binding.SessionNamespace != asset.ClaimNamespace || binding.RequestingPrincipal == "" || binding.ClientPublicKey == "" || binding.Protocol != "Redfish" || binding.AccessProfile != "Provisioning" || binding.ConsumerProject == "" || binding.ProviderProject == "" || binding.MemberCluster == "" || binding.LocationName == "" || binding.LocationName != asset.LocationName || binding.DeviceName == "" || binding.DeviceName != asset.DeviceName || binding.AllocationName != assetRecordName(asset.AssetID) || string(binding.AllocationUID) != asset.BindingID || binding.MachineUID != asset.ClaimUID || binding.MachineName != asset.ClaimName || binding.MachineNamespace != asset.ClaimNamespace || binding.MachineCapacityUID != asset.MachineUID || binding.MachineCapacityName != asset.MachineName || binding.MachineCapacityNamespace != asset.MachineNamespace || binding.ConnectBefore.IsZero() || binding.ExpiresAt.IsZero() || binding.ConnectBefore.After(binding.ExpiresAt.Time) || binding.SessionCorrelationID == "" || binding.OperationCorrelationID == "" { + return ErrRecordInvalid + } + if record.Completed && !record.Revoking || managementHeld(asset) && (asset.ActiveOperationID != "" || asset.State != AssetCommitted && asset.State != AssetReleasing) || asset.State == AssetReleasing && !record.Revoking { + return ErrRecordInvalid + } + return nil +} + +func (c *Coordinator) revokeManagement(ctx context.Context, assetID string, claimUID types.UID, releasing bool) error { + return retry.RetryOnConflict(retry.DefaultRetry, func() error { + asset, secret, err := c.getAsset(ctx, assetID) + if err != nil { + return err + } + if asset.ClaimUID != claimUID || !managementHeld(asset) || asset.ActiveOperationID != "" || asset.State != AssetCommitted && asset.State != AssetReleasing { + return ErrRecordInvalid + } + asset.Management.Revoking = true + if releasing { + asset.State = AssetReleasing + } + if err := encodeRecord(secret, asset, "asset"); err != nil { + return err + } + return c.client.Update(ctx, secret) + }) +} diff --git a/internal/controller/management_lifecycle_test.go b/internal/controller/management_lifecycle_test.go new file mode 100644 index 00000000..ec650282 --- /dev/null +++ b/internal/controller/management_lifecycle_test.go @@ -0,0 +1,454 @@ +package controller + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "k8s.io/apimachinery/pkg/api/equality" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" +) + +type managementResolver struct { + access ManagementAccess + err error +} + +func (r *managementResolver) ResolveManagementAccess(_ context.Context, _ sessionv1.MachineManagementSessionBindingSpec) (ManagementAccess, error) { + return r.access, r.err +} + +func managementFixture(t *testing.T) (*fixture, AllocationRequest, *AssetRecord, *LifecycleSessionAuthority, sessionv1.MachineManagementSessionBindingSpec) { + t.Helper() + ctx := context.Background() + f := newFixture(t) + request := f.request("customer") + request.Claim.Spec.LocationRef.Name = "location" + if err := f.coordinator.EnsureClaimCustody(ctx, request.Claim, request.NamespaceUID, request.Admission); err != nil { + t.Fatal(err) + } + asset, err := f.coordinator.Allocate(ctx, request) + if err != nil { + t.Fatal(err) + } + authority := &LifecycleSessionAuthority{Coordinator: f.coordinator, Resolver: &managementResolver{access: ManagementAccess{Scope: LocalClaimScope(request.NamespaceUID), NamespaceUID: request.NamespaceUID, MachineUID: request.Claim.UID, CapacityNamespace: asset.MachineNamespace, CapacityName: asset.MachineName, CapacityUID: asset.MachineUID, DeviceName: asset.DeviceName, ConsumerProject: ProjectIdentity{AuthorityID: "local", RouteName: "consumer", UID: request.NamespaceUID}, ProviderProject: ProjectIdentity{AuthorityID: "local", RouteName: "provider", UID: "provider-uid"}, MemberCluster: "cell", LocationName: "location"}}} + binding := sessionv1.MachineManagementSessionBindingSpec{SessionNamespace: request.Claim.Namespace, SessionName: "access", SessionUID: "session", RequestingPrincipal: "principal", MachineNamespace: request.Claim.Namespace, MachineName: request.Claim.Name, MachineUID: request.Claim.UID, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", ConnectBefore: metav1.NewTime(f.now.Add(time.Minute)), ExpiresAt: metav1.NewTime(f.now.Add(time.Hour)), SessionCorrelationID: "session-correlation", OperationCorrelationID: "operation-correlation"} + return f, request, asset, authority, binding +} + +func confirmedBinding(spec sessionv1.MachineManagementSessionBindingSpec) *sessionv1.MachineManagementSessionBinding { + return &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: bindingName(spec.SessionUID), Namespace: SystemNamespace, Generation: 2, Annotations: map[string]string{RevokedAtAnnotation: "revoked"}}, Spec: spec, Status: sessionv1.MachineManagementSessionBindingStatus{Conditions: []metav1.Condition{{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, ObservedGeneration: 2, Reason: "Verified"}}}} +} + +func TestManagementCustodyBlocksReleaseAndReuse(t *testing.T) { + ctx := context.Background() + f, request, asset, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + if retained.AllocationName != assetRecordName(asset.AssetID) || retained.AllocationUID != types.UID(asset.BindingID) || retained.MachineUID == retained.MachineCapacityUID || retained.DeviceName != asset.DeviceName { + t.Fatalf("identities collapsed: %+v", retained) + } + if !authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: retained}) { + t.Fatal("retained session inactive") + } + result, err := f.coordinator.Release(ctx, request.Claim.UID) + if !errors.Is(err, ErrManagementActive) || result.SafeToRemoveFinalizer || len(f.executor.requests) != 0 { + t.Fatalf("release crossed live session: %+v %v", result, err) + } + if authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: retained}) { + t.Fatal("release still refreshes session authority") + } + competitor := f.request("other") + if err := f.coordinator.EnsureClaimCustody(ctx, competitor.Claim, competitor.NamespaceUID, competitor.Admission); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Allocate(ctx, competitor); !errors.Is(err, ErrInsufficientCapacity) { + t.Fatalf("reuse before teardown: %v", err) + } + confirmation := confirmedBinding(retained) + confirmation.Status.Conditions[0].Status = metav1.ConditionUnknown + if err := authority.Complete(ctx, confirmation); !errors.Is(err, ErrManagementActive) { + t.Fatalf("unknown teardown cleared hold: %v", err) + } + confirmation.Status.Conditions[0].Status = metav1.ConditionTrue + confirmation.Status.Conditions[0].ObservedGeneration-- + if err := authority.Complete(ctx, confirmation); !errors.Is(err, ErrManagementActive) { + t.Fatalf("stale teardown cleared hold: %v", err) + } + confirmation.Status.Conditions[0].ObservedGeneration++ + authority = &LifecycleSessionAuthority{Coordinator: f.coordinator} + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatal(err) + } + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatalf("completion not replayable: %v", err) + } + result, err = f.coordinator.Release(ctx, request.Claim.UID) + if err != nil || !result.SafeToRemoveFinalizer || len(f.executor.requests) != 1 { + t.Fatalf("verified teardown did not unblock cleanup: %+v %v", result, err) + } + next, err := f.coordinator.Allocate(ctx, competitor) + if err != nil || next.Epoch <= asset.Epoch || next.BindingID == asset.BindingID || next.Management != nil { + t.Fatalf("reuse inherited authority: %+v %v", next, err) + } +} + +func TestManagementInstallationAndSessionAdmissionSerialize(t *testing.T) { + ctx := context.Background() + for iteration := 0; iteration < 20; iteration++ { + f, request, asset, authority, proposed := managementFixture(t) + var acquireErr, installErr error + var wait sync.WaitGroup + wait.Add(2) + go func() { defer wait.Done(); _, acquireErr = authority.Acquire(ctx, proposed) }() + go func() { + defer wait.Done() + installErr = f.coordinator.activateOperation(ctx, asset.AssetID, request.Claim.UID, "None", "installation") + }() + wait.Wait() + if acquireErr == nil && installErr == nil { + t.Fatal("session and installation both acquired hardware authority") + } + stored, _, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil || managementHeld(stored) && stored.ActiveOperationID != "" { + t.Fatalf("conflicting durable authority: %+v %v", stored, err) + } + } +} + +func TestManagementInstallWaitsForTeardown(t *testing.T) { + ctx := context.Background() + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + installation := &fleetv1.Installation{ObjectMeta: metav1.ObjectMeta{Namespace: request.Claim.Namespace, Name: "install", UID: "installation-uid"}, Spec: fleetv1.InstallationSpec{MachineRef: fleetv1.MachineReference{Name: request.Claim.Name}, ExpectedPredecessor: fleetv1.InstallationPredecessor{Type: "None"}, ImageRef: fleetv1.LocalReference{Name: "registry/image@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} + installRequest := InstallationRequest{Claim: request.Claim, Installation: installation, NamespaceUID: request.NamespaceUID, Admission: installAdmission()} + if _, err := f.coordinator.Install(ctx, installRequest); !errors.Is(err, ErrManagementActive) || len(f.executor.requests) != 0 { + t.Fatalf("install bypassed session: %v", err) + } + if authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: retained}) { + t.Fatal("install did not revoke management refresh") + } + if err := authority.Complete(ctx, confirmedBinding(retained)); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Install(ctx, installRequest); err != nil || len(f.executor.requests) != 1 { + t.Fatalf("install did not resume: %v", err) + } +} + +func TestManagementParallelSessionsAndReleaseCAS(t *testing.T) { + ctx := context.Background() + for iteration := 0; iteration < 20; iteration++ { + f, request, asset, authority, proposed := managementFixture(t) + other := proposed + other.SessionUID, other.SessionName = "other", "other" + var firstErr, secondErr error + var wait sync.WaitGroup + wait.Add(2) + go func() { defer wait.Done(); _, firstErr = authority.Acquire(ctx, proposed) }() + go func() { defer wait.Done(); _, secondErr = authority.Acquire(ctx, other) }() + wait.Wait() + if (firstErr == nil) == (secondErr == nil) { + t.Fatalf("expected exactly one session: %v %v", firstErr, secondErr) + } + stored, _, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + t.Fatal(err) + } + if err := authority.Complete(ctx, confirmedBinding(stored.Management.Binding)); err != nil { + t.Fatal(err) + } + proposed.SessionUID = "racing-release" + var releaseErr error + wait.Add(2) + go func() { defer wait.Done(); _, firstErr = authority.Acquire(ctx, proposed) }() + go func() { defer wait.Done(); _, releaseErr = f.coordinator.Release(ctx, request.Claim.UID) }() + wait.Wait() + stored, _, err = f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + t.Fatal(err) + } + if firstErr == nil && releaseErr == nil || managementHeld(stored) && len(f.executor.requests) != 0 { + t.Fatal("release executed cleanup concurrently with management custody") + } + } +} + +func TestOldTeardownCannotClearNextSession(t *testing.T) { + ctx := context.Background() + f, _, asset, authority, proposed := managementFixture(t) + first, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + confirmation := confirmedBinding(first) + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatal(err) + } + proposed.SessionUID, proposed.SessionName = "next-session", "next-access" + next, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + if err := authority.Complete(ctx, confirmation); err != nil { + t.Fatal(err) + } + stored, _, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil || !managementHeld(stored) || stored.Management.Binding.SessionUID != next.SessionUID { + t.Fatalf("old cleanup touched new authority: %+v %v", stored, err) + } + authority.Resolver.(*managementResolver).err = errors.New("project authorization revoked") + if authority.Active(ctx, &sessionv1.MachineManagementSessionBinding{Spec: next}) { + t.Fatal("refresh did not reauthorize") + } +} + +func TestSessionAdmissionConsumesLifecycleCustody(t *testing.T) { + ctx := context.Background() + f, request, asset, authority, proposed := managementFixture(t) + session := &sessionv1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: proposed.SessionName, Namespace: proposed.SessionNamespace, UID: proposed.SessionUID, Annotations: map[string]string{PrincipalAnnotation: proposed.RequestingPrincipal}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: request.Claim.Name}, Protocol: proposed.Protocol, AccessProfile: proposed.AccessProfile, ClientPublicKey: proposed.ClientPublicKey}} + public := fake.NewClientBuilder().WithScheme(testScheme(t)).WithStatusSubresource(session, &sessionv1.MachineManagementSessionBinding{}).WithObjects(session, request.Claim).Build() + reconciler := &SessionReconciler{Client: public, Lifecycle: authority, Now: func() time.Time { return f.now }} + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + var binding sessionv1.MachineManagementSessionBinding + if err := public.Get(ctx, client.ObjectKey{Namespace: SystemNamespace, Name: bindingName(session.UID)}, &binding); err != nil { + t.Fatal(err) + } + if binding.Spec.AllocationUID != types.UID(asset.BindingID) || binding.Spec.DeviceName != asset.DeviceName || binding.Spec.MachineCapacityUID != asset.MachineUID { + t.Fatalf("binding did not use authoritative custody: %+v", binding.Spec) + } + if err := public.Get(ctx, client.ObjectKeyFromObject(session), session); err != nil { + t.Fatal(err) + } + if err := public.Delete(ctx, session); err != nil { + t.Fatal(err) + } + reconciler.Now = func() time.Time { return time.Now().Add(time.Hour) } + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + if err := public.Get(ctx, client.ObjectKeyFromObject(session), session); err != nil || !contains(session.Finalizers, sessionv1.SessionFinalizer) { + t.Fatalf("unknown teardown dropped finalizer: %v", err) + } +} + +func TestManagementAuthorizationAndPinnedTargets(t *testing.T) { + ctx := context.Background() + for _, mutation := range []string{"missing-authorizer", "denied", "project-lifetime", "namespace-lifetime", "machine-lifetime", "location", "device-unpinned", "capacity-recreated", "device-changed"} { + t.Run(mutation, func(t *testing.T) { + f, _, asset, authority, proposed := managementFixture(t) + resolver := authority.Resolver.(*managementResolver) + switch mutation { + case "missing-authorizer": + authority.Resolver = nil + case "denied": + resolver.err = errors.New("denied") + case "project-lifetime": + resolver.access.Scope.ProjectUID = "recreated" + case "machine-lifetime": + proposed.MachineUID = "recreated" + case "namespace-lifetime": + resolver.access.NamespaceUID = "recreated" + case "capacity-recreated": + resolver.access.CapacityUID = "recreated" + case "device-changed": + resolver.access.DeviceName = "other-device" + case "location": + resolver.access.LocationName = "other" + case "device-unpinned": + stored, secret, _ := f.coordinator.getAsset(ctx, asset.AssetID) + stored.DeviceName = "" + if err := encodeRecord(secret, stored, "asset"); err != nil { + t.Fatal(err) + } + if err := f.coordinator.client.Update(ctx, secret); err != nil { + t.Fatal(err) + } + } + if _, err := authority.Acquire(ctx, proposed); err == nil { + t.Fatal("untrusted input acquired authority") + } + }) + } +} + +func TestManagementRecoveryRetainsExactInputsDuringRelease(t *testing.T) { + ctx := context.Background() + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + proposed.ExpiresAt = metav1.NewTime(f.now.Add(2 * time.Hour)) + proposed.SessionCorrelationID = "new-random-value" + replayed, err := authority.Acquire(ctx, proposed) + if err != nil || !equality.Semantic.DeepEqual(replayed, retained) { + t.Fatalf("replay changed inputs: %+v %v", replayed, err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal(err) + } + session := &sessionv1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: retained.SessionName, Namespace: retained.SessionNamespace, UID: retained.SessionUID, Annotations: map[string]string{PrincipalAnnotation: retained.RequestingPrincipal}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: retained.MachineName}, Protocol: retained.Protocol, AccessProfile: retained.AccessProfile, ClientPublicKey: retained.ClientPublicKey}} + authority = &LifecycleSessionAuthority{Coordinator: f.coordinator} + recovered, err := authority.Recover(ctx, session) + if err != nil || !equality.Semantic.DeepEqual(recovered, &retained) { + t.Fatalf("orphaned hold cannot recover: %+v %v", recovered, err) + } + if err := sessionv1.AddToScheme(f.coordinator.client.Scheme()); err != nil { + t.Fatal(err) + } + if err := f.coordinator.client.Create(ctx, session); err != nil { + t.Fatal(err) + } + reconciler := &SessionReconciler{Client: f.coordinator.client, Lifecycle: authority} + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + var binding sessionv1.MachineManagementSessionBinding + if err := f.coordinator.client.Get(ctx, client.ObjectKey{Namespace: SystemNamespace, Name: bindingName(session.UID)}, &binding); err != nil || !equality.Semantic.DeepEqual(binding.Spec, retained) { + t.Fatalf("binding recovery: %+v %v", binding, err) + } +} + +func TestProjectionIntentDistinguishesNeverStartedFromUnknown(t *testing.T) { + ctx := context.Background() + for _, projected := range []bool{false, true} { + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + binding := &sessionv1.MachineManagementSessionBinding{Spec: retained} + if projected { + if err := authority.BeginProjection(ctx, binding); err != nil { + t.Fatal(err) + } + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal(err) + } + binding.Annotations = map[string]string{RevokedAtAnnotation: "revoked"} + closed, err := authority.CancelUnprojected(ctx, binding) + if err != nil || closed == projected { + t.Fatalf("projection intent %v, cancellation %v: %v", projected, closed, err) + } + if err := authority.BeginProjection(ctx, binding); err == nil { + t.Fatal("release permitted a new projection") + } + if !projected { + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal("hold cleared before confirmation was retained") + } + if err := authority.Complete(ctx, confirmedBinding(retained)); err != nil { + t.Fatal(err) + } + } + result, err := f.coordinator.Release(ctx, request.Claim.UID) + if projected && (!errors.Is(err, ErrManagementActive) || result.SafeToRemoveFinalizer || len(f.executor.requests) != 0) { + t.Fatalf("uncertain projection allowed cleanup: %+v %v", result, err) + } + if !projected && (err != nil || !result.SafeToRemoveFinalizer) { + t.Fatalf("never-projected hold could not settle: %+v %v", result, err) + } + } +} + +func TestLegacyAssetRecordsCannotAdmitManagement(t *testing.T) { + ctx := context.Background() + f, request, asset, authority, proposed := managementFixture(t) + stored, secret, err := f.coordinator.getAsset(ctx, asset.AssetID) + if err != nil { + t.Fatal(err) + } + stored.SchemaVersion = recordSchemaVersion + if err := encodeRecord(secret, stored, "asset"); err != nil { + t.Fatal(err) + } + if err := f.coordinator.client.Update(ctx, secret); err != nil { + t.Fatal(err) + } + if _, err := authority.Acquire(ctx, proposed); !errors.Is(err, ErrRecordInvalid) { + t.Fatalf("legacy record acquired a hold invisible to older writers: %v", err) + } + if result, err := f.coordinator.Release(ctx, request.Claim.UID); err != nil || !result.SafeToRemoveFinalizer { + t.Fatalf("legacy custody cannot drain: %+v %v", result, err) + } +} + +func TestLifecycleProjectionRequiresCurrentTeardownBeforeCleanup(t *testing.T) { + ctx := context.Background() + f, request, _, authority, proposed := managementFixture(t) + retained, err := authority.Acquire(ctx, proposed) + if err != nil { + t.Fatal(err) + } + binding := &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: bindingName(retained.SessionUID), Namespace: SystemNamespace, Generation: 1}, Spec: retained} + scheme := testScheme(t) + primary := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(binding).WithObjects(binding).Build() + federation := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&coordinationv1.ProjectedMachineManagementSession{}).Build() + reconciler := &ProjectionReconciler{Client: primary, FederationClient: federation, Lifecycle: authority, Now: func() time.Time { return f.now }} + req := ctrl.Request{NamespacedName: client.ObjectKeyFromObject(binding)} + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatal(err) + } + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + var projected coordinationv1.ProjectedMachineManagementSession + key := client.ObjectKey{Namespace: LocationNamespace, Name: binding.Name} + if err := federation.Get(ctx, key, &projected); err != nil { + t.Fatal(err) + } + if projected.Spec.DesiredState != sessionv1.ProjectionRevoked { + t.Fatal("release not propagated") + } + projected.Generation = 3 + if err := federation.Update(ctx, &projected); err != nil { + t.Fatal(err) + } + apimeta.SetStatusCondition(&projected.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, ObservedGeneration: 2, Reason: "Old"}) + if err := federation.Status().Update(ctx, &projected); err != nil { + t.Fatal(err) + } + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); !errors.Is(err, ErrManagementActive) { + t.Fatalf("stale evidence cleared custody: %v", err) + } + projected.Status.TeardownSpecDigest = coordinationv1.TeardownDigest(&projected) + projected.Status.Conditions[0].ObservedGeneration = 77 + if err := federation.Status().Update(ctx, &projected); err != nil { + t.Fatal(err) + } + if _, err := reconciler.Reconcile(ctx, req); err != nil { + t.Fatal(err) + } + if _, err := f.coordinator.Release(ctx, request.Claim.UID); err != nil { + t.Fatal(err) + } + if err := federation.Get(ctx, key, &projected); err == nil { + t.Fatal("settled projection was not removed") + } +} diff --git a/internal/controller/projection.go b/internal/controller/projection.go new file mode 100644 index 00000000..4316aa0d --- /dev/null +++ b/internal/controller/projection.go @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "fmt" + "reflect" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +// ProjectionReconciler writes only to the Karmada hub. Karmada carries the +// projection to the exact member cluster retained at admission and reflects +// cell-written status. This controller has no cell credential. +type ProjectionReconciler struct { + client.Client + FederationClient client.Client + SystemNamespace string + HubNamespace string + Now func() time.Time + Freshness time.Duration + Lifecycle SessionLifecycle +} + +func (r *ProjectionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + var b fleetv1alpha1.MachineManagementSessionBinding + if err := r.Get(ctx, req.NamespacedName, &b); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if req.Namespace != r.systemNamespace() { + return ctrl.Result{}, nil + } + if cleanup := apimeta.FindStatusCondition(b.Status.Conditions, "CleanupConfirmed"); cleanup != nil && cleanup.Status == metav1.ConditionTrue { + return r.finishTeardown(ctx, &b) + } + key := types.NamespacedName{Namespace: r.hubNamespace(), Name: b.Name} + active := r.now().Before(b.Spec.ExpiresAt.Time) && r.allocationStillActive(ctx, &b) + if !active && b.Annotations[RevokedAtAnnotation] == "" { + patch := client.MergeFrom(b.DeepCopy()) + if b.Annotations == nil { + b.Annotations = map[string]string{} + } + b.Annotations[RevokedAtAnnotation] = r.now().UTC().Format(time.RFC3339Nano) + if err := r.Patch(ctx, &b, patch); err != nil { + return ctrl.Result{}, err + } + } + + var p coordinationv1.ProjectedMachineManagementSession + err := r.FederationClient.Get(ctx, key, &p) + if apierrors.IsNotFound(err) { + if b.Annotations[RevokedAtAnnotation] != "" || !active { + if r.Lifecycle != nil { + completed, err := r.Lifecycle.CancelUnprojected(ctx, &b) + if err != nil { + return ctrl.Result{}, err + } + if completed { + setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionTrue, "NeverProjected", "Private custody proves no projection was admitted.", r.now()) + if err := r.Status().Update(ctx, &b); err != nil { + return ctrl.Result{}, err + } + return r.finishTeardown(ctx, &b) + } + } + return ctrl.Result{}, nil + } + if err := r.Lifecycle.BeginProjection(ctx, &b); err != nil { + return ctrl.Result{}, err + } + p = *r.build(&b) + if err := r.FederationClient.Create(ctx, &p); err != nil { + return ctrl.Result{}, err + } + if err := r.ensurePolicy(ctx, &b); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } + if err != nil { + return ctrl.Result{}, err + } + if !projectionMatches(&b, &p) { + setNamedCondition(&b.Status.Conditions, fleetv1alpha1.ConditionReady, b.Generation, metav1.ConditionFalse, "ProjectionChanged", "The federated projection no longer matches the admitted session inputs.", r.now()) + return ctrl.Result{}, r.Status().Update(ctx, &b) + } + if err := r.ensurePolicy(ctx, &b); err != nil { + return ctrl.Result{}, err + } + if b.Annotations[RevokedAtAnnotation] != "" || !active { + return r.revokeProjection(ctx, &b, &p) + } + + fresh := r.freshUntil(b.Spec.ExpiresAt) + if p.Spec.DesiredState != fleetv1alpha1.ProjectionActive || p.Spec.AuthorityFreshUntil.Before(&fresh) { + patch := client.MergeFrom(p.DeepCopy()) + p.Spec.DesiredState = fleetv1alpha1.ProjectionActive + p.Spec.AuthorityFreshUntil = fresh + if err := r.FederationClient.Patch(ctx, &p, patch); err != nil { + return ctrl.Result{}, err + } + } + if !reflect.DeepEqual(b.Status.Connection, p.Status.Connection) || !reflect.DeepEqual(b.Status.Conditions, p.Status.Conditions) { + b.Status.Connection = p.Status.Connection + b.Status.Conditions = append([]metav1.Condition(nil), p.Status.Conditions...) + for i := range b.Status.Conditions { + b.Status.Conditions[i].ObservedGeneration = b.Generation + } + if err := r.Status().Update(ctx, &b); err != nil { + return ctrl.Result{}, err + } + } + if p.Status.Connection == nil { + return ctrl.Result{RequeueAfter: 2 * time.Second}, nil + } + return ctrl.Result{RequeueAfter: r.freshness() / 2}, nil +} + +func (r *ProjectionReconciler) allocationStillActive(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) bool { + return r.Lifecycle != nil && r.Lifecycle.Active(ctx, b) +} + +func (r *ProjectionReconciler) revokeProjection(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding, p *coordinationv1.ProjectedMachineManagementSession) (ctrl.Result, error) { + if p.Spec.DesiredState != fleetv1alpha1.ProjectionRevoked { + patch := client.MergeFrom(p.DeepCopy()) + p.Spec.DesiredState = fleetv1alpha1.ProjectionRevoked + if err := r.FederationClient.Patch(ctx, p, patch); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } + cleanup := apimeta.FindStatusCondition(p.Status.Conditions, "CleanupConfirmed") + if cleanup == nil || cleanup.Status != metav1.ConditionTrue || p.Status.TeardownSpecDigest != coordinationv1.TeardownDigest(p) { + return ctrl.Result{RequeueAfter: time.Second}, nil + } + setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionTrue, "LocationTeardownConfirmed", "The selected location gateway confirmed session teardown through Karmada status aggregation.", r.now()) + setNamedCondition(&b.Status.Conditions, fleetv1alpha1.ConditionReady, b.Generation, metav1.ConditionFalse, "Revoked", "The session authority has ended.", r.now()) + if err := r.Status().Update(ctx, b); err != nil { + return ctrl.Result{}, err + } + return r.finishTeardown(ctx, b) +} + +func (r *ProjectionReconciler) finishTeardown(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) (ctrl.Result, error) { + if r.Lifecycle == nil { + return ctrl.Result{}, ErrUnsupported + } + if err := r.Lifecycle.Complete(ctx, b); err != nil { + return ctrl.Result{}, err + } + if err := r.deletePolicy(ctx, b.Name); err != nil { + return ctrl.Result{}, err + } + projection := &coordinationv1.ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Namespace: r.hubNamespace(), Name: b.Name}} + return ctrl.Result{}, client.IgnoreNotFound(r.FederationClient.Delete(ctx, projection)) +} + +func (r *ProjectionReconciler) build(b *fleetv1alpha1.MachineManagementSessionBinding) *coordinationv1.ProjectedMachineManagementSession { + s := b.Spec + return &coordinationv1.ProjectedMachineManagementSession{ + TypeMeta: metav1.TypeMeta{APIVersion: coordinationv1.GroupVersion.String(), Kind: "ProjectedMachineManagementSession"}, + ObjectMeta: metav1.ObjectMeta{Name: b.Name, Namespace: r.hubNamespace(), Labels: map[string]string{MemberClusterLabel: s.MemberCluster}}, + Spec: coordinationv1.ProjectedMachineManagementSessionSpec{ + DesiredState: fleetv1alpha1.ProjectionActive, + MachineCapacityRef: fleetv1alpha1.LocalReference{Name: s.MachineCapacityName}, + Protocol: s.Protocol, AccessProfile: s.AccessProfile, ClientPublicKey: s.ClientPublicKey, + ConnectBefore: s.ConnectBefore, ExpiresAt: s.ExpiresAt, + AuthorityFreshUntil: r.freshUntil(s.ExpiresAt), + }, + } +} + +func projectionMatches(b *fleetv1alpha1.MachineManagementSessionBinding, p *coordinationv1.ProjectedMachineManagementSession) bool { + s, x := b.Spec, p.Spec + return p.Labels[MemberClusterLabel] == s.MemberCluster && + x.MachineCapacityRef.Name == s.MachineCapacityName && x.Protocol == s.Protocol && x.AccessProfile == s.AccessProfile && + x.ClientPublicKey == s.ClientPublicKey && x.ConnectBefore.Equal(&s.ConnectBefore) && x.ExpiresAt.Equal(&s.ExpiresAt) +} + +func (r *ProjectionReconciler) ensurePolicy(ctx context.Context, b *fleetv1alpha1.MachineManagementSessionBinding) error { + policy := propagationPolicy(r.hubNamespace(), b.Name, b.Spec.MemberCluster) + var existing unstructured.Unstructured + existing.SetAPIVersion("policy.karmada.io/v1alpha1") + existing.SetKind("PropagationPolicy") + err := r.FederationClient.Get(ctx, types.NamespacedName{Namespace: r.hubNamespace(), Name: policy.GetName()}, &existing) + if apierrors.IsNotFound(err) { + return r.FederationClient.Create(ctx, policy) + } + if err != nil { + return err + } + clusters, _, _ := unstructured.NestedStringSlice(existing.Object, "spec", "placement", "clusterAffinity", "clusterNames") + if len(clusters) != 1 || clusters[0] != b.Spec.MemberCluster { + return fmt.Errorf("propagation policy %s target changed from admitted member %q", existing.GetName(), b.Spec.MemberCluster) + } + return nil +} + +func propagationPolicy(namespace, sessionName, member string) *unstructured.Unstructured { + return &unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "policy.karmada.io/v1alpha1", "kind": "PropagationPolicy", + "metadata": map[string]any{"name": "mms-" + sessionName, "namespace": namespace, "labels": map[string]any{SessionUIDLabel: sessionName}}, + "spec": map[string]any{ + "resourceSelectors": []any{map[string]any{"apiVersion": coordinationv1.GroupVersion.String(), "kind": "ProjectedMachineManagementSession", "name": sessionName, "namespace": namespace}}, + "placement": map[string]any{"clusterAffinity": map[string]any{"clusterNames": []any{member}}}, + }, + }} +} + +func (r *ProjectionReconciler) deletePolicy(ctx context.Context, sessionName string) error { + p := propagationPolicy(r.hubNamespace(), sessionName, "") + if err := r.FederationClient.Delete(ctx, p); err != nil && !apierrors.IsNotFound(err) { + return err + } + return nil +} + +func (r *ProjectionReconciler) SetupWithManager(mgr ctrl.Manager) error { + if r.FederationClient == nil { + return fmt.Errorf("federation client is required") + } + r.Client = mgr.GetClient() + return ctrl.NewControllerManagedBy(mgr). + For(&fleetv1alpha1.MachineManagementSessionBinding{}).Complete(r) +} + +func (r *ProjectionReconciler) systemNamespace() string { + if r.SystemNamespace != "" { + return r.SystemNamespace + } + return SystemNamespace +} +func (r *ProjectionReconciler) hubNamespace() string { + if r.HubNamespace != "" { + return r.HubNamespace + } + return LocationNamespace +} +func (r *ProjectionReconciler) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} +func (r *ProjectionReconciler) freshness() time.Duration { + if r.Freshness > 0 { + return r.Freshness + } + return DefaultAuthorityFreshness +} + +// Freshness never extends the admitted expiry; revocation uses desiredState +// rather than moving this monotonic deadline backwards. +func (r *ProjectionReconciler) freshUntil(expiry metav1.Time) metav1.Time { + fresh := metav1.NewTime(r.now().Add(r.freshness())) + if expiry.Before(&fresh) { + return expiry + } + return fresh +} diff --git a/internal/controller/projection_test.go b/internal/controller/projection_test.go new file mode 100644 index 00000000..1d4a115f --- /dev/null +++ b/internal/controller/projection_test.go @@ -0,0 +1,81 @@ +package controller + +import ( + "context" + "errors" + "testing" + "time" + + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" +) + +func TestReleasedAllocationTerminallyRevokesProjection(t *testing.T) { + scheme := testScheme(t) + now := time.Unix(1000, 0).UTC() + machine := testMachine("machine-uid") + allocation := testAllocation(machine.UID) + allocation.Status.Phase = "Released" + capacity := testCapacity() + binding := &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: "mms-internal", Namespace: SystemNamespace}, Spec: sessionv1.MachineManagementSessionBindingSpec{ + SessionUID: "session-uid", ConsumerProject: "consumer", ProviderProject: "provider", MachineNamespace: "default", MachineName: "db-01", MachineUID: machine.UID, + AllocationName: allocation.Name, AllocationUID: allocation.UID, MachineCapacityNamespace: capacity.Namespace, MachineCapacityName: capacity.Name, MachineCapacityUID: capacity.UID, + DeviceName: "device-a", LocationName: "location", MemberCluster: "cell-a", Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", ConnectBefore: metav1.NewTime(now.Add(time.Minute)), ExpiresAt: metav1.NewTime(now.Add(time.Hour)), + }} + projection := &coordinationv1.ProjectedMachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: binding.Name, Namespace: LocationNamespace, Labels: map[string]string{MemberClusterLabel: "cell-a"}}, Spec: coordinationv1.ProjectedMachineManagementSessionSpec{DesiredState: sessionv1.ProjectionActive, MachineCapacityRef: sessionv1.LocalReference{Name: capacity.Name}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", ConnectBefore: binding.Spec.ConnectBefore, ExpiresAt: binding.Spec.ExpiresAt, AuthorityFreshUntil: metav1.NewTime(now.Add(time.Minute))}} + primary := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(binding).WithObjects(binding, machine, allocation, capacity).Build() + federation := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(projection).WithObjects(projection).Build() + r := &ProjectionReconciler{Client: primary, FederationClient: federation, Now: func() time.Time { return now }} + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: SystemNamespace, Name: binding.Name}} + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatal(err) + } + var got sessionv1.MachineManagementSessionBinding + if err := primary.Get(context.Background(), req.NamespacedName, &got); err != nil { + t.Fatal(err) + } + if got.Annotations[RevokedAtAnnotation] == "" { + t.Fatal("released allocation did not permanently revoke admitted binding") + } + var revoked coordinationv1.ProjectedMachineManagementSession + key := types.NamespacedName{Namespace: LocationNamespace, Name: binding.Name} + if err := federation.Get(context.Background(), key, &revoked); err != nil { + t.Fatal(err) + } + if !revoked.Spec.AuthorityFreshUntil.Equal(&projection.Spec.AuthorityFreshUntil) { + t.Fatal("revocation moved the monotonic freshness deadline") + } + if revoked.Spec.DesiredState != sessionv1.ProjectionRevoked { + t.Fatal("allocation release was not propagated as revocation") + } + apimeta.SetStatusCondition(&revoked.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, Reason: "GatewayStopped", Message: "stopped", ObservedGeneration: revoked.Generation}) + revoked.Status.TeardownSpecDigest = coordinationv1.TeardownDigest(&revoked) + if err := federation.Status().Update(context.Background(), &revoked); err != nil { + t.Fatal(err) + } + if _, err := r.Reconcile(context.Background(), req); !errors.Is(err, ErrUnsupported) { + t.Fatalf("missing lifecycle authority must block completion: %v", err) + } + if err := federation.Get(context.Background(), key, &revoked); err != nil { + t.Fatal("projection evidence removed without lifecycle settlement") + } +} + +func TestProjectionFreshnessCannotExceedExpiry(t *testing.T) { + now := time.Unix(1000, 0).UTC() + r := &ProjectionReconciler{Now: func() time.Time { return now }, Freshness: 2 * time.Minute} + b := &sessionv1.MachineManagementSessionBinding{Spec: sessionv1.MachineManagementSessionBindingSpec{ExpiresAt: metav1.NewTime(now.Add(time.Second))}} + p := r.build(b) + if !p.Spec.AuthorityFreshUntil.Equal(&b.Spec.ExpiresAt) { + t.Fatal("projection extends authority past expiry") + } + if got := p.APIVersion; got != "coordination.fleet.datumapis.com/v1alpha1" { + t.Fatalf("projection API = %s", got) + } +} diff --git a/internal/controller/session.go b/internal/controller/session.go new file mode 100644 index 00000000..9649b242 --- /dev/null +++ b/internal/controller/session.go @@ -0,0 +1,352 @@ +// SPDX-License-Identifier: Apache-2.0 + +package controller + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "fmt" + "log/slog" + "reflect" + "time" + + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + "sigs.k8s.io/controller-runtime/pkg/handler" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + fleetmetrics "go.datum.net/fleet/internal/metrics" +) + +const ( + SystemNamespace = "fleet-system" + LocationNamespace = "machine-access-system" + PrincipalAnnotation = "fleet.datumapis.com/requesting-principal" + MachineUIDLabel = "fleet.datumapis.com/machine-uid" + AllocationNameLabel = "fleet.datumapis.com/allocation-name" + SessionUIDLabel = "fleet.datumapis.com/session-uid" + RevokedAtAnnotation = "fleet.datumapis.com/revoked-at" + MemberClusterLabel = "fleet.datumapis.com/member-cluster" + DefaultConnectWindow = time.Minute + DefaultAuthorityFreshness = 2 * time.Minute +) + +type SessionReconciler struct { + client.Client + SystemNamespace string + Now func() time.Time + PerClaimLimit int + PerProjectLimit int + Lifecycle SessionLifecycle +} + +func (r *SessionReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + var session fleetv1alpha1.MachineManagementSession + if err := r.Get(ctx, req.NamespacedName, &session); err != nil { + return ctrl.Result{}, client.IgnoreNotFound(err) + } + if session.UID != "" && r.Lifecycle != nil { + binding, err := r.bindingForSession(ctx, session.UID) + if err != nil { + return ctrl.Result{}, err + } + if binding == nil { + retained, err := r.Lifecycle.Recover(ctx, &session) + if err != nil { + return ctrl.Result{}, err + } + if retained != nil { + binding = &fleetv1alpha1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Name: bindingName(session.UID), Namespace: r.systemNamespace(), Labels: map[string]string{SessionUIDLabel: string(session.UID), MachineUIDLabel: string(retained.MachineUID), AllocationNameLabel: retained.AllocationName}}, Spec: *retained} + if err := r.Create(ctx, binding); err != nil && !apierrors.IsAlreadyExists(err) { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } + } + } + if !session.DeletionTimestamp.IsZero() { + return r.revoke(ctx, &session) + } + if !controllerutil.ContainsFinalizer(&session, fleetv1alpha1.SessionFinalizer) { + patch := client.MergeFrom(session.DeepCopy()) + controllerutil.AddFinalizer(&session, fleetv1alpha1.SessionFinalizer) + if err := r.Patch(ctx, &session, patch); err != nil { + return ctrl.Result{}, err + } + } + if session.UID == "" { + return ctrl.Result{RequeueAfter: time.Second}, nil + } + admitted, err := r.bindingForSession(ctx, session.UID) + if err == nil && admitted == nil { + return r.admit(ctx, &session) + } + if err != nil { + return ctrl.Result{}, err + } + return r.reflect(ctx, &session, admitted) +} + +func (r *SessionReconciler) admit(ctx context.Context, session *fleetv1alpha1.MachineManagementSession) (ctrl.Result, error) { + principal := session.Annotations[PrincipalAnnotation] + if principal == "" { + return r.reject(ctx, session, "PrincipalMissing", "Admission did not retain the authenticated principal.") + } + var machine fleetv1.Machine + key := types.NamespacedName{Namespace: session.Namespace, Name: session.Spec.MachineRef.Name} + if err := r.Get(ctx, key, &machine); err != nil { + if apierrors.IsNotFound(err) { + return r.reject(ctx, session, "MachineNotFound", "The Machine does not exist.") + } + return ctrl.Result{}, err + } + if r.Lifecycle == nil { + return r.reject(ctx, session, "AuthorityUnavailable", "Authoritative lifecycle access is unavailable.") + } + now := r.now() + ttl := session.Spec.TTL.Duration + if ttl <= 0 { + ttl = 15 * time.Minute + } + connect := metav1.NewTime(now.Add(DefaultConnectWindow)) + expiry := metav1.NewTime(now.Add(ttl)) + b := &fleetv1alpha1.MachineManagementSessionBinding{ + TypeMeta: metav1.TypeMeta{APIVersion: fleetv1alpha1.GroupVersion.String(), Kind: "MachineManagementSessionBinding"}, + ObjectMeta: metav1.ObjectMeta{Name: bindingName(session.UID), Namespace: r.systemNamespace(), Labels: map[string]string{ + SessionUIDLabel: string(session.UID), MachineUIDLabel: string(machine.UID), + }}, + Spec: fleetv1alpha1.MachineManagementSessionBindingSpec{ + SessionNamespace: session.Namespace, SessionName: session.Name, SessionUID: session.UID, + RequestingPrincipal: principal, + MachineNamespace: machine.Namespace, MachineName: machine.Name, MachineUID: machine.UID, + Protocol: session.Spec.Protocol, AccessProfile: session.Spec.AccessProfile, + ClientPublicKey: session.Spec.ClientPublicKey, ConnectBefore: connect, ExpiresAt: expiry, + SessionCorrelationID: randomCorrelationID(), OperationCorrelationID: randomCorrelationID(), + }, + } + if !machine.DeletionTimestamp.IsZero() { + return r.reject(ctx, session, "MachineDeleting", "The Machine is being released.") + } + prepared, err := r.Lifecycle.Prepare(ctx, b.Spec) + if err != nil { + return ctrl.Result{}, err + } + if result, err := r.enforceLimits(ctx, prepared.ConsumerProject, machine.UID); err != nil || result != nil { + if err != nil { + return ctrl.Result{}, err + } + return r.reject(ctx, session, "SessionLimitExceeded", *result) + } + retained, err := r.Lifecycle.Acquire(ctx, prepared) + if err != nil { + return ctrl.Result{RequeueAfter: time.Second}, err + } + b.Spec = retained + b.Labels[AllocationNameLabel] = retained.AllocationName + if err := r.Create(ctx, b); err != nil { + if apierrors.IsAlreadyExists(err) { + return ctrl.Result{Requeue: true}, nil + } + return ctrl.Result{}, err + } + fleetmetrics.SessionAdmissions.WithLabelValues("admitted").Inc() + slog.InfoContext(ctx, "machine-management session admitted", + "session", session.Name, "machine", machine.Name, "allocation", retained.AllocationName, + "principal", principal, "sessionCorrelationID", b.Spec.SessionCorrelationID) + return ctrl.Result{RequeueAfter: time.Second}, nil +} + +func (r *SessionReconciler) enforceLimits(ctx context.Context, project string, machineUID types.UID) (*string, error) { + var list fleetv1alpha1.MachineManagementSessionBindingList + if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace())); err != nil { + return nil, err + } + machineCount, projectCount := 0, 0 + now := r.now() + for i := range list.Items { + b := &list.Items[i] + if !b.Spec.ExpiresAt.After(now) || b.Annotations[RevokedAtAnnotation] != "" { + continue + } + if b.Spec.MachineUID == machineUID { + machineCount++ + } + if b.Spec.ConsumerProject == project { + projectCount++ + } + } + cl := r.PerClaimLimit + if cl == 0 { + cl = 1 + } + pl := r.PerProjectLimit + if pl == 0 { + pl = 5 + } + if machineCount >= cl { + s := fmt.Sprintf("The Machine already has %d active session(s); limit is %d.", machineCount, cl) + return &s, nil + } + if projectCount >= pl { + s := fmt.Sprintf("The project already has %d active session(s); limit is %d.", projectCount, pl) + return &s, nil + } + return nil, nil +} + +func (r *SessionReconciler) reflect(ctx context.Context, s *fleetv1alpha1.MachineManagementSession, b *fleetv1alpha1.MachineManagementSessionBinding) (ctrl.Result, error) { + if equalityStatus(s, b) { + if r.now().After(b.Spec.ExpiresAt.Time) { + patch := client.MergeFrom(b.DeepCopy()) + if b.Annotations == nil { + b.Annotations = map[string]string{} + } + b.Annotations[RevokedAtAnnotation] = r.now().UTC().Format(time.RFC3339Nano) + if err := r.Patch(ctx, b, patch); err != nil { + return ctrl.Result{}, err + } + } + return ctrl.Result{RequeueAfter: time.Until(b.Spec.ExpiresAt.Time)}, nil + } + s.Status.ConnectBefore = b.Spec.ConnectBefore.DeepCopy() + s.Status.ExpiresAt = b.Spec.ExpiresAt.DeepCopy() + s.Status.Connection = b.Status.Connection + if c := apimeta.FindStatusCondition(b.Status.Conditions, fleetv1alpha1.ConditionReady); c != nil { + condition := *c + condition.ObservedGeneration = s.Generation + apimeta.SetStatusCondition(&s.Status.Conditions, condition) + } else { + setCondition(&s.Status.Conditions, s.Generation, metav1.ConditionUnknown, "Pending", "Waiting for location projection.", r.now()) + } + if err := r.Status().Update(ctx, s); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Until(b.Spec.ExpiresAt.Time)}, nil +} + +func (r *SessionReconciler) reject(ctx context.Context, s *fleetv1alpha1.MachineManagementSession, reason, message string) (ctrl.Result, error) { + fleetmetrics.SessionAdmissions.WithLabelValues(reason).Inc() + slog.WarnContext(ctx, "machine-management session rejected", "session", s.Name, "reason", reason) + setCondition(&s.Status.Conditions, s.Generation, metav1.ConditionFalse, reason, message, r.now()) + return ctrl.Result{}, r.Status().Update(ctx, s) +} + +func (r *SessionReconciler) revoke(ctx context.Context, s *fleetv1alpha1.MachineManagementSession) (ctrl.Result, error) { + if !controllerutil.ContainsFinalizer(s, fleetv1alpha1.SessionFinalizer) { + return ctrl.Result{}, nil + } + if r.Lifecycle == nil { + return ctrl.Result{}, ErrUnsupported + } + b, err := r.bindingForSession(ctx, s.UID) + if err == nil && b != nil { + if b.Annotations[RevokedAtAnnotation] == "" { + patch := client.MergeFrom(b.DeepCopy()) + if b.Annotations == nil { + b.Annotations = map[string]string{} + } + b.Annotations[RevokedAtAnnotation] = r.now().UTC().Format(time.RFC3339Nano) + if err := r.Patch(ctx, b, patch); err != nil { + return ctrl.Result{}, err + } + slog.InfoContext(ctx, "machine-management session revocation requested", "session", s.Name, "allocation", b.Spec.AllocationName, "sessionCorrelationID", b.Spec.SessionCorrelationID) + } + if c := apimeta.FindStatusCondition(b.Status.Conditions, "CleanupConfirmed"); c != nil && c.Status == metav1.ConditionTrue { + if err := r.Lifecycle.Complete(ctx, b); err != nil { + return ctrl.Result{}, err + } + fleetmetrics.RevocationLatency.Observe(r.now().Sub(s.DeletionTimestamp.Time).Seconds()) + patch := client.MergeFrom(s.DeepCopy()) + controllerutil.RemoveFinalizer(s, fleetv1alpha1.SessionFinalizer) + return ctrl.Result{}, r.Patch(ctx, s, patch) + } + if r.now().After(s.DeletionTimestamp.Add(30 * time.Second)) { + fleetmetrics.RevocationLatency.Observe(r.now().Sub(s.DeletionTimestamp.Time).Seconds()) + setNamedCondition(&b.Status.Conditions, "CleanupConfirmed", b.Generation, metav1.ConditionUnknown, "LocationUnconfirmed", "The location did not confirm session teardown.", r.now()) + if err := r.Status().Update(ctx, b); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } + return ctrl.Result{RequeueAfter: time.Second}, nil + } else if err != nil { + return ctrl.Result{}, err + } + patch := client.MergeFrom(s.DeepCopy()) + controllerutil.RemoveFinalizer(s, fleetv1alpha1.SessionFinalizer) + return ctrl.Result{}, r.Patch(ctx, s, patch) +} + +func (r *SessionReconciler) bindingForSession(ctx context.Context, uid types.UID) (*fleetv1alpha1.MachineManagementSessionBinding, error) { + var list fleetv1alpha1.MachineManagementSessionBindingList + if err := r.List(ctx, &list, client.InNamespace(r.systemNamespace()), client.MatchingLabels{SessionUIDLabel: string(uid)}); err != nil { + return nil, err + } + if len(list.Items) == 0 { + return nil, nil + } + if len(list.Items) != 1 || list.Items[0].Spec.SessionUID != uid { + return nil, fmt.Errorf("expected one protected binding for session UID") + } + return &list.Items[0], nil +} + +func (r *SessionReconciler) SetupWithManager(mgr ctrl.Manager) error { + r.Client = mgr.GetClient() + return ctrl.NewControllerManagedBy(mgr). + For(&fleetv1alpha1.MachineManagementSession{}). + Watches(&fleetv1alpha1.MachineManagementSessionBinding{}, handler.EnqueueRequestsFromMapFunc(func(_ context.Context, obj client.Object) []reconcile.Request { + b := obj.(*fleetv1alpha1.MachineManagementSessionBinding) + return []reconcile.Request{{NamespacedName: types.NamespacedName{Namespace: b.Spec.SessionNamespace, Name: b.Spec.SessionName}}} + })). + WithOptions(controller.Options{MaxConcurrentReconciles: 1}).Complete(r) +} +func (r *SessionReconciler) now() time.Time { + if r.Now != nil { + return r.Now() + } + return time.Now() +} +func (r *SessionReconciler) systemNamespace() string { + if r.SystemNamespace != "" { + return r.SystemNamespace + } + return SystemNamespace +} + +func setCondition(cs *[]metav1.Condition, generation int64, status metav1.ConditionStatus, reason, message string, now time.Time) { + apimeta.SetStatusCondition(cs, metav1.Condition{Type: fleetv1alpha1.ConditionReady, Status: status, Reason: reason, Message: message, ObservedGeneration: generation, LastTransitionTime: metav1.NewTime(now)}) +} +func setNamedCondition(cs *[]metav1.Condition, name string, generation int64, status metav1.ConditionStatus, reason, message string, now time.Time) { + apimeta.SetStatusCondition(cs, metav1.Condition{Type: name, Status: status, Reason: reason, Message: message, ObservedGeneration: generation, LastTransitionTime: metav1.NewTime(now)}) +} +func randomCorrelationID() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} + +// bindingName makes admission idempotent even while the controller-runtime +// cache is briefly stale after a successful create. The domain-separated hash +// is an opaque rendezvous name; the underlying Kubernetes UID remains only in +// the protected central binding and is never placed in the location payload. +func bindingName(uid types.UID) string { + sum := sha256.Sum256([]byte("fleet-machine-management-binding-v1\x00" + string(uid))) + return "mms-" + hex.EncodeToString(sum[:16]) +} + +func equalityStatus(s *fleetv1alpha1.MachineManagementSession, b *fleetv1alpha1.MachineManagementSessionBinding) bool { + return reflect.DeepEqual(s.Status.Connection, b.Status.Connection) && reflect.DeepEqual(s.Status.Conditions, b.Status.Conditions) && s.Status.ConnectBefore != nil && s.Status.ConnectBefore.Equal(&b.Spec.ConnectBefore) && s.Status.ExpiresAt != nil && s.Status.ExpiresAt.Equal(&b.Spec.ExpiresAt) +} diff --git a/internal/controller/session_test.go b/internal/controller/session_test.go new file mode 100644 index 00000000..fbc04c66 --- /dev/null +++ b/internal/controller/session_test.go @@ -0,0 +1,114 @@ +package controller + +import ( + "context" + "testing" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" +) + +const ( + MemberClusterAnnotation = "fleet.datumapis.com/member-cluster" + ProviderProjectAnnotation = "fleet.datumapis.com/provider-project" + LocationNameAnnotation = "fleet.datumapis.com/location-name" + AllocationMachineUIDAnnotation = "fleet.datumapis.com/machine-uid" +) + +func testScheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + if err := coordinationv1.AddToScheme(s); err != nil { + t.Fatal(err) + } + if err := fleetv1.AddToScheme(s); err != nil { + t.Fatal(err) + } + if err := sessionv1.AddToScheme(s); err != nil { + t.Fatal(err) + } + return s +} + +func TestPreboundAllocationCannotAuthorizeSession(t *testing.T) { + scheme := testScheme(t) + now := time.Unix(1000, 0) + machine := testMachine("machine-uid") + allocation := testAllocation(machine.UID) + capacity := testCapacity() + session := testSession("session-uid") + c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session, &sessionv1.MachineManagementSessionBinding{}).WithObjects(machine, allocation, capacity, session).Build() + r := &SessionReconciler{Client: c, Now: func() time.Time { return now }} + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: "access"}} + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatal(err) + } + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatal(err) + } + var bindings sessionv1.MachineManagementSessionBindingList + if err := c.List(context.Background(), &bindings, client.InNamespace(SystemNamespace)); err != nil { + t.Fatal(err) + } + if len(bindings.Items) != 0 { + t.Fatalf("bindings=%d", len(bindings.Items)) + } +} + +func TestBindingNameIsStableAndOpaque(t *testing.T) { + uid := types.UID("b88ddb18-b190-455f-bc91-29331950ca41") + got := bindingName(uid) + if got != bindingName(uid) { + t.Fatal("binding name changed for the same session UID") + } + if got == bindingName(types.UID("another-session")) { + t.Fatal("different session UIDs produced the same binding name") + } + if got == "mms-"+string(uid) { + t.Fatal("binding name exposed the raw session UID") + } +} + +func TestRecreatedMachineNameCannotInheritAllocation(t *testing.T) { + scheme := testScheme(t) + machine := testMachine("new-machine-uid") + allocation := testAllocation("old-machine-uid") + session := testSession("session-uid") + c := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(session).WithObjects(machine, allocation, testCapacity(), session).Build() + r := &SessionReconciler{Client: c} + req := ctrl.Request{NamespacedName: types.NamespacedName{Namespace: "default", Name: "access"}} + _, _ = r.Reconcile(context.Background(), req) + _, _ = r.Reconcile(context.Background(), req) + var got sessionv1.MachineManagementSession + if err := c.Get(context.Background(), req.NamespacedName, &got); err != nil { + t.Fatal(err) + } + if len(got.Status.Conditions) == 0 || got.Status.Conditions[0].Reason != "AuthorityUnavailable" { + t.Fatalf("conditions %+v", got.Status.Conditions) + } +} + +func testSession(uid types.UID) *sessionv1.MachineManagementSession { + return &sessionv1.MachineManagementSession{TypeMeta: metav1.TypeMeta{APIVersion: sessionv1.GroupVersion.String(), Kind: "MachineManagementSession"}, ObjectMeta: metav1.ObjectMeta{Name: "access", Namespace: "default", UID: uid, Annotations: map[string]string{PrincipalAnnotation: "alice@example.test"}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: "db-01"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", TTL: metav1.Duration{Duration: 15 * time.Minute}}} +} + +func testMachine(uid types.UID) *fleetv1.Machine { + return &fleetv1.Machine{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1.GroupVersion.String(), Kind: "Machine"}, ObjectMeta: metav1.ObjectMeta{Name: "db-01", Namespace: "default", UID: uid}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "class"}, MachineProfileRef: fleetv1.LocalReference{Name: "profile"}, LocationRef: fleetv1.LocalReference{Name: "location"}}} +} + +func testCapacity() *fleetv1.MachineCapacity { + return &fleetv1.MachineCapacity{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1.GroupVersion.String(), Kind: "MachineCapacity"}, ObjectMeta: metav1.ObjectMeta{Name: "capacity-a", Namespace: "provider-ns", UID: "capacity-uid"}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "device-a"}, AllocationPolicy: "Enabled", CleaningPolicyRef: fleetv1.LocalReference{Name: "clean"}, ReclaimPolicy: "Retain"}} +} + +func testAllocation(machineUID types.UID) *fleetv1.MachineAllocation { + return &fleetv1.MachineAllocation{TypeMeta: metav1.TypeMeta{APIVersion: fleetv1.GroupVersion.String(), Kind: "MachineAllocation"}, ObjectMeta: metav1.ObjectMeta{Name: "allocation-a", Namespace: SystemNamespace, UID: "allocation-uid", Annotations: map[string]string{AllocationMachineUIDAnnotation: string(machineUID), MemberClusterAnnotation: "cell-a", LocationNameAnnotation: "location", ProviderProjectAnnotation: "provider"}}, Spec: fleetv1.MachineAllocationSpec{MachineRef: fleetv1.ProjectNamespacedReference{Project: "consumer", Namespace: "default", Name: "db-01"}, MachineCapacityRef: fleetv1.NamespacedReference{Namespace: "provider-ns", Name: "capacity-a"}}, Status: fleetv1.MachineAllocationStatus{Phase: "Active"}} +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go new file mode 100644 index 00000000..9183193e --- /dev/null +++ b/internal/gateway/gateway.go @@ -0,0 +1,554 @@ +// SPDX-License-Identifier: Apache-2.0 + +package gateway + +import ( + "bufio" + "bytes" + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "math/big" + "net" + "net/http" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "time" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/journal" + fleetmetrics "go.datum.net/fleet/internal/metrics" + "go.datum.net/fleet/internal/protocol" + "go.datum.net/fleet/internal/redfish" + "go.datum.net/fleet/internal/relay" +) + +const ( + HeaderTimestamp = "X-Datum-Fleet-Timestamp" + HeaderNonce = "X-Datum-Fleet-Nonce" + HeaderSignature = "X-Datum-Fleet-Signature" + HeaderSession = "X-Datum-Fleet-Session" + HeaderAudience = "X-Datum-Fleet-Audience" + EnrollmentDeviceLabel = "fleet.datumapis.com/device-name" + DefaultEnrollmentNamespace = "machine-access-system" +) + +type Config struct { + RelayAddress string + RelayPublicURL string + RelayGatewayToken string + Audience string + SupportedAdapter string + EnrollmentNamespace string + JournalDir string + StateDir string + DropResetResponseOnce bool +} + +type Reconciler struct { + client.Client + Config Config + mu sync.Mutex + active map[client.ObjectKey]*activeSession +} + +type activeSession struct { + cancel context.CancelFunc + mu sync.RWMutex + effects sync.RWMutex + stopped bool + done chan struct{} + spec coordinationv1.ProjectedMachineManagementSessionSpec + target resolvedTarget +} + +type resolvedTarget struct { + MachineCapacityName string + DeviceName string + Adapter string + BaseURL string + SystemID string + Username string + Password string +} + +func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + var p coordinationv1.ProjectedMachineManagementSession + if err := r.Get(ctx, req.NamespacedName, &p); err != nil { + if apierrors.IsNotFound(err) { + r.stop(req.NamespacedName) + return ctrl.Result{}, nil + } + return ctrl.Result{}, err + } + now := time.Now() + if p.Spec.DesiredState == fleetv1alpha1.ProjectionRevoked { + r.stop(req.NamespacedName) + if cleanup := apimeta.FindStatusCondition(p.Status.Conditions, "CleanupConfirmed"); cleanup != nil && cleanup.Status == metav1.ConditionTrue && cleanup.ObservedGeneration == p.Generation && p.Status.TeardownSpecDigest == coordinationv1.TeardownDigest(&p) { + return ctrl.Result{}, nil + } + if err := r.verifyTeardown(req.NamespacedName, p.Spec.MachineCapacityRef.Name); err != nil { + apimeta.SetStatusCondition(&p.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionUnknown, Reason: "EffectsUnconfirmed", Message: "Session shutdown or durable effect settlement is unconfirmed.", ObservedGeneration: p.Generation, LastTransitionTime: metav1.Now()}) + return ctrl.Result{RequeueAfter: time.Second}, r.Status().Update(ctx, &p) + } + setCondition(&p, metav1.ConditionFalse, "Revoked", "The central allocation authority revoked this session.") + p.Status.TeardownSpecDigest = coordinationv1.TeardownDigest(&p) + apimeta.SetStatusCondition(&p.Status.Conditions, metav1.Condition{Type: "CleanupConfirmed", Status: metav1.ConditionTrue, Reason: "GatewayStopped", Message: "The location gateway closed the relay stream and discarded session authority.", ObservedGeneration: p.Generation, LastTransitionTime: metav1.Now()}) + return ctrl.Result{}, r.Status().Update(ctx, &p) + } + if !p.DeletionTimestamp.IsZero() || now.After(p.Spec.ExpiresAt.Time) { + r.stop(req.NamespacedName) + return ctrl.Result{}, nil + } + if p.Status.ConnectedAt == nil && now.After(p.Spec.ConnectBefore.Time) { + r.stop(req.NamespacedName) + setCondition(&p, metav1.ConditionFalse, "ConnectWindowExpired", "No client connected before the admitted connection deadline.") + return ctrl.Result{}, r.Status().Update(ctx, &p) + } + r.mu.Lock() + if r.active == nil { + r.active = map[client.ObjectKey]*activeSession{} + } + a := r.active[req.NamespacedName] + if a == nil { + target, err := r.resolveTarget(ctx, p.Spec) + if err != nil { + r.mu.Unlock() + setCondition(&p, metav1.ConditionFalse, "ManagementUnavailable", "The allocated capacity does not have a verified local management enrollment.") + return ctrl.Result{RequeueAfter: 5 * time.Second}, r.Status().Update(ctx, &p) + } + runCtx, cancel := context.WithCancel(context.Background()) + a = &activeSession{cancel: cancel, spec: p.Spec, target: target, done: make(chan struct{})} + r.active[req.NamespacedName] = a + go r.run(runCtx, req.NamespacedName, a) + } else { + a.mu.Lock() + if !sameBinding(a.spec, p.Spec) { + a.mu.Unlock() + r.mu.Unlock() + r.stop(req.NamespacedName) + setCondition(&p, metav1.ConditionFalse, "SessionInputsChanged", "Projected binding inputs changed after the gateway accepted them.") + return ctrl.Result{}, r.Status().Update(ctx, &p) + } + a.spec.AuthorityFreshUntil = p.Spec.AuthorityFreshUntil + a.mu.Unlock() + } + r.mu.Unlock() + wake := time.Until(p.Spec.ExpiresAt.Time) + if p.Status.ConnectedAt == nil && time.Until(p.Spec.ConnectBefore.Time) < wake { + wake = time.Until(p.Spec.ConnectBefore.Time) + } + return ctrl.Result{RequeueAfter: wake}, nil +} + +func (r *Reconciler) run(ctx context.Context, key client.ObjectKey, a *activeSession) { + defer close(a.done) + fleetmetrics.ActiveSessions.Inc() + defer fleetmetrics.ActiveSessions.Dec() + cert, der, fingerprint, err := loadOrCreateCertificate(r.Config.StateDir, key.Name) + if err != nil { + r.failStatus(key, "GatewayCertificateError", "The location gateway could not create its session certificate.") + return + } + sessionStore, err := journal.Open(filepath.Join(r.Config.JournalDir, "sessions")) + if err != nil { + return + } + if _, err := sessionStore.Get(journal.Identity(key.Name, "REVOKED", "", nil)); !errors.Is(err, os.ErrNotExist) { + r.failStatus(key, "SessionRevoked", "The durable journal does not permit this session to start.") + return + } + marker := journal.Identity(key.Name, "SESSION", "", nil) + var store *journal.Store + if _, markerErr := sessionStore.Get(marker); markerErr == nil { + store, err = r.existingOperations() + } else if errors.Is(markerErr, os.ErrNotExist) { + store, err = journal.Open(filepath.Join(r.Config.JournalDir, "operations")) + } else { + err = markerErr + } + if err != nil { + r.failStatus(key, "JournalUnavailable", "The durable operation journal is unavailable.") + return + } + a.mu.RLock() + sessionSpec, sessionTarget := a.spec, a.target + a.mu.RUnlock() + if err := retainSession(sessionStore, key.Name, sessionSpec, sessionTarget); err != nil { + return + } + routeID := randomHex(24) + conn, err := r.dialRelay(ctx, routeID) + if err != nil { + r.failStatus(key, "RelayUnavailable", "The location gateway could not establish its outbound relay route.") + return + } + defer conn.Close() + go func() { + <-ctx.Done() + _ = conn.Close() + }() + if err := r.readyStatus(key, routeID, fingerprint); err != nil { + return + } + line, err := bufio.NewReader(conn).ReadString('\n') + if err != nil || line != "OK\n" { + r.failStatus(key, "RelayDisconnected", "The outbound relay route ended before a client connected.") + return + } + r.connectedStatus(key) + a.mu.RLock() + target := a.target + a.mu.RUnlock() + adapter := &redfish.SushyAdapter{BaseURL: target.BaseURL, SystemID: target.SystemID, Username: target.Username, Password: target.Password, DropResetResponseOnce: r.Config.DropResetResponseOnce} + h := &redfish.Handler{Adapter: adapter, Journal: store, CurrentAuthority: func() redfish.Authority { + a.mu.RLock() + defer a.mu.RUnlock() + s := a.spec + return redfish.Authority{SessionName: key.Name, MachineCapacityName: target.MachineCapacityName, DeviceName: target.DeviceName, OperationEpoch: 1, ExpiresAt: s.ExpiresAt.Time, FreshUntil: s.AuthorityFreshUntil.Time} + }} + protected := r.proofMiddleware(a, routeID, h) + tlsConn := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13, NextProtos: []string{"datum-fleet-redfish/1"}}) + // The relay admits one connector for the session, so an HTTP idle timeout + // would permanently strand a valid session during a long PXE boot. Expiry, + // revocation, and projection teardown bound the stream lifetime instead. + server := &http.Server{Handler: protected, ReadHeaderTimeout: 10 * time.Second, MaxHeaderBytes: 16 << 10, BaseContext: func(net.Listener) context.Context { return ctx }} + defer server.Close() + _ = server.Serve(newOneConnListener(tlsConn)) + _ = der // DER is retained only to make certificate pin derivation explicit. + r.endedStatus(key, "Disconnected", "The client connection ended.") +} + +func (r *Reconciler) dialRelay(ctx context.Context, routeID string) (net.Conn, error) { + d := net.Dialer{Timeout: 10 * time.Second} + c, err := d.DialContext(ctx, "tcp", r.Config.RelayAddress) + if err != nil { + return nil, err + } + if err := relay.Register(c, routeID, r.Config.RelayGatewayToken); err != nil { + _ = c.Close() + return nil, err + } + return c, nil +} + +func (r *Reconciler) proofMiddleware(a *activeSession, routeID string, next http.Handler) http.Handler { + used := map[string]bool{} + var mu sync.Mutex + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + a.effects.RLock() + defer a.effects.RUnlock() + if a.stopped { + http.Error(w, "session revoked", http.StatusForbidden) + return + } + a.mu.RLock() + spec := a.spec + a.mu.RUnlock() + if req.Header.Get(HeaderSession) != routeID || req.Header.Get(HeaderAudience) != r.Config.Audience { + http.Error(w, "session proof target mismatch", http.StatusUnauthorized) + return + } + proof := protocol.Proof{Timestamp: req.Header.Get(HeaderTimestamp), Nonce: req.Header.Get(HeaderNonce), Signature: req.Header.Get(HeaderSignature)} + err := protocol.Verify(spec.ClientPublicKey, routeID, r.Config.Audience, proof, time.Now(), func(n string) bool { + mu.Lock() + defer mu.Unlock() + if used[n] { + return true + } + used[n] = true + return false + }) + if err != nil { + http.Error(w, "invalid session key proof", http.StatusUnauthorized) + return + } + next.ServeHTTP(w, req) + }) +} + +func (r *Reconciler) readyStatus(key client.ObjectKey, route, fingerprint string) error { + return r.updateStatus(key, func(p *coordinationv1.ProjectedMachineManagementSession) { + p.Status.Connection = &fleetv1alpha1.SessionConnection{RelayURL: r.Config.RelayPublicURL, RouteID: route, GatewayAudience: r.Config.Audience, GatewayCertSHA256: fingerprint, ProtocolVersion: protocol.Version} + setCondition(p, metav1.ConditionTrue, "SessionReady", "The outbound location route is ready for one connector.") + }) +} +func (r *Reconciler) connectedStatus(key client.ObjectKey) { + _ = r.updateStatus(key, func(p *coordinationv1.ProjectedMachineManagementSession) { + now := metav1.Now() + p.Status.ConnectedAt = &now + setCondition(p, metav1.ConditionTrue, "Connected", "The client proved possession of the admitted session key.") + }) +} +func (r *Reconciler) endedStatus(key client.ObjectKey, reason, message string) { + _ = r.updateStatus(key, func(p *coordinationv1.ProjectedMachineManagementSession) { + now := metav1.Now() + p.Status.EndedAt = &now + setCondition(p, metav1.ConditionFalse, reason, message) + }) +} +func (r *Reconciler) failStatus(key client.ObjectKey, reason, message string) { + _ = r.updateStatus(key, func(p *coordinationv1.ProjectedMachineManagementSession) { + setCondition(p, metav1.ConditionFalse, reason, message) + }) +} +func (r *Reconciler) updateStatus(key client.ObjectKey, mutate func(*coordinationv1.ProjectedMachineManagementSession)) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var p coordinationv1.ProjectedMachineManagementSession + if err := r.Get(ctx, key, &p); err != nil { + return err + } + mutate(&p) + return r.Status().Update(ctx, &p) +} +func (r *Reconciler) stop(key client.ObjectKey) { + r.mu.Lock() + defer r.mu.Unlock() + if a := r.active[key]; a != nil { + a.cancel() + a.effects.Lock() + a.stopped = true + a.effects.Unlock() + } +} + +func (r *Reconciler) verifyTeardown(key client.ObjectKey, capacity string) error { + r.mu.Lock() + defer r.mu.Unlock() + if active := r.active[key]; active != nil { + select { + case <-active.done: + default: + return fmt.Errorf("gateway stream has not stopped") + } + } + store, err := r.existingOperations() + if err != nil { + return err + } + markerID := journal.Identity(key.Name, "SESSION", "", nil) + sessionStore, err := journal.Open(filepath.Join(r.Config.JournalDir, "sessions")) + if err != nil { + return err + } + marker, err := sessionStore.Get(markerID) + if err != nil || marker.SessionName != key.Name || marker.MachineCapacityName != capacity || marker.Outcome != journal.Succeeded { + return fmt.Errorf("session journal custody is unavailable") + } + operations, err := store.List() + if err != nil { + return err + } + for _, operation := range operations { + if operation.SessionName == key.Name && (operation.MachineCapacityName != capacity || operation.Outcome != journal.Succeeded) { + return fmt.Errorf("session effects are not verified") + } + } + tombstone := journal.Identity(key.Name, "REVOKED", "", nil) + if _, _, err := sessionStore.Admit(journal.Operation{ID: tombstone, SessionName: key.Name, MachineCapacityName: capacity, DeviceName: marker.DeviceName}); err != nil { + return err + } + if _, err := sessionStore.Finish(tombstone, journal.Succeeded, 0, "session terminally revoked after request and effect settlement"); err != nil { + return err + } + delete(r.active, key) + return nil +} + +func (r *Reconciler) existingOperations() (*journal.Store, error) { + directory := filepath.Join(r.Config.JournalDir, "operations") + if info, err := os.Stat(directory); err != nil { + return nil, err + } else if !info.IsDir() { + return nil, fmt.Errorf("operation journal directory is unavailable") + } + return journal.Open(directory) +} + +func retainSession(store *journal.Store, name string, spec coordinationv1.ProjectedMachineManagementSessionSpec, target resolvedTarget) error { + spec.AuthorityFreshUntil = metav1.Time{} + inputs, err := json.Marshal(spec) + if err != nil { + return err + } + marker := journal.Identity(name, "SESSION", "", nil) + physical := target.Adapter + ":" + target.SystemID + retained, _, err := store.Admit(journal.Operation{ID: marker, SessionName: name, MachineCapacityName: target.MachineCapacityName, DeviceName: target.DeviceName, PhysicalTarget: physical, AcceptedBody: inputs}) + if err != nil { + return err + } + var retainedInputs bytes.Buffer + if err := json.Compact(&retainedInputs, retained.AcceptedBody); err != nil { + return err + } + if retained.SessionName != name || retained.MachineCapacityName != target.MachineCapacityName || retained.DeviceName != target.DeviceName || retained.PhysicalTarget != physical || !bytes.Equal(retainedInputs.Bytes(), inputs) { + return fmt.Errorf("retained session inputs differ") + } + _, err = store.Finish(marker, journal.Succeeded, 0, "session journal retained before route registration") + return err +} +func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { + r.Client = mgr.GetClient() + return ctrl.NewControllerManagedBy(mgr).For(&coordinationv1.ProjectedMachineManagementSession{}).Complete(r) +} + +func (r *Reconciler) resolveTarget(ctx context.Context, spec coordinationv1.ProjectedMachineManagementSessionSpec) (resolvedTarget, error) { + namespace := r.Config.EnrollmentNamespace + if namespace == "" { + namespace = DefaultEnrollmentNamespace + } + var capacity fleetv1.MachineCapacity + if err := r.Get(ctx, client.ObjectKey{Namespace: namespace, Name: spec.MachineCapacityRef.Name}, &capacity); err != nil { + return resolvedTarget{}, err + } + if capacity.Spec.DeviceRef.Name == "" { + return resolvedTarget{}, fmt.Errorf("MachineCapacity has no deviceRef") + } + var secrets corev1.SecretList + if err := r.List(ctx, &secrets, client.InNamespace(namespace), client.MatchingLabels{EnrollmentDeviceLabel: capacity.Spec.DeviceRef.Name}); err != nil { + return resolvedTarget{}, err + } + if len(secrets.Items) != 1 { + return resolvedTarget{}, fmt.Errorf("expected one management enrollment") + } + data := secrets.Items[0].Data + target := resolvedTarget{ + MachineCapacityName: capacity.Name, + DeviceName: capacity.Spec.DeviceRef.Name, + Adapter: strings.TrimSpace(string(data["adapter"])), + BaseURL: strings.TrimSpace(string(data["endpoint"])), + SystemID: strings.TrimSpace(string(data["system-id"])), + Username: strings.TrimSpace(string(data["username"])), + Password: strings.TrimSpace(string(data["password"])), + } + if target.Adapter == "" || target.Adapter != r.Config.SupportedAdapter || target.BaseURL == "" || target.SystemID == "" || target.Username == "" || target.Password == "" { + return resolvedTarget{}, fmt.Errorf("management enrollment is incomplete or unsupported") + } + return target, nil +} + +func sameBinding(a, b coordinationv1.ProjectedMachineManagementSessionSpec) bool { + a.AuthorityFreshUntil = metav1.Time{} + b.AuthorityFreshUntil = metav1.Time{} + a.DesiredState = "" + b.DesiredState = "" + return reflect.DeepEqual(a, b) +} +func setCondition(p *coordinationv1.ProjectedMachineManagementSession, status metav1.ConditionStatus, reason, message string) { + apimeta.SetStatusCondition(&p.Status.Conditions, metav1.Condition{Type: fleetv1alpha1.ConditionReady, Status: status, Reason: reason, Message: message, ObservedGeneration: p.Generation, LastTransitionTime: metav1.Now()}) +} + +func loadOrCreateCertificate(dir, name string) (tls.Certificate, []byte, string, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return tls.Certificate{}, nil, "", err + } + certPath, keyPath := filepath.Join(dir, name+".crt"), filepath.Join(dir, name+".key") + if certPEM, err := os.ReadFile(certPath); err == nil { + keyPEM, e := os.ReadFile(keyPath) + if e == nil { + cert, e := tls.X509KeyPair(certPEM, keyPEM) + if e == nil && len(cert.Certificate) > 0 { + sum := sha256.Sum256(cert.Certificate[0]) + return cert, cert.Certificate[0], hex.EncodeToString(sum[:]), nil + } + } + } + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + return tls.Certificate{}, nil, "", err + } + serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) + now := time.Now() + tmpl := x509.Certificate{SerialNumber: serial, Subject: pkix.Name{CommonName: "fleet-gateway"}, NotBefore: now.Add(-time.Minute), NotAfter: now.Add(24 * time.Hour), DNSNames: []string{"fleet-gateway"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} + der, err := x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, pub, priv) + if err != nil { + return tls.Certificate{}, nil, "", err + } + pkcs8, err := x509.MarshalPKCS8PrivateKey(priv) + if err != nil { + return tls.Certificate{}, nil, "", err + } + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pkcs8}) + if err := os.WriteFile(certPath, certPEM, 0o600); err != nil { + return tls.Certificate{}, nil, "", err + } + if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil { + return tls.Certificate{}, nil, "", err + } + cert, err := tls.X509KeyPair(certPEM, keyPEM) + sum := sha256.Sum256(der) + return cert, der, hex.EncodeToString(sum[:]), err +} +func randomHex(n int) string { b := make([]byte, n); _, _ = rand.Read(b); return hex.EncodeToString(b) } + +type oneConnListener struct { + mu sync.Mutex + conn net.Conn + accepted bool + done chan struct{} + once sync.Once +} + +func newOneConnListener(conn net.Conn) *oneConnListener { + l := &oneConnListener{done: make(chan struct{})} + l.conn = ¬ifyConn{Conn: conn, closed: func() { l.once.Do(func() { close(l.done) }) }} + return l +} + +func (l *oneConnListener) Accept() (net.Conn, error) { + l.mu.Lock() + if !l.accepted { + l.accepted = true + conn := l.conn + l.mu.Unlock() + return conn, nil + } + l.mu.Unlock() + <-l.done + return nil, errors.New("single connection consumed") +} +func (l *oneConnListener) Close() error { + l.once.Do(func() { close(l.done) }) + return l.conn.Close() +} +func (l *oneConnListener) Addr() net.Addr { return dummyAddr("relay") } + +type dummyAddr string + +func (d dummyAddr) Network() string { return "relay" } +func (d dummyAddr) String() string { return string(d) } + +type notifyConn struct { + net.Conn + once sync.Once + closed func() +} + +func (c *notifyConn) Close() error { + err := c.Conn.Close() + c.once.Do(c.closed) + return err +} diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go new file mode 100644 index 00000000..68f8c4fe --- /dev/null +++ b/internal/gateway/gateway_test.go @@ -0,0 +1,181 @@ +package gateway + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + "time" + + "go.datum.net/fleet/internal/journal" + "go.datum.net/fleet/internal/protocol" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + coordinationv1 "go.datum.net/fleet/internal/api/coordination/v1alpha1" + fleetv1alpha1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" +) + +func TestTeardownRequiresDurableSettledEffects(t *testing.T) { + for _, outcome := range []journal.Outcome{journal.Pending, journal.Unknown, journal.Failed, journal.Succeeded} { + t.Run(string(outcome), func(t *testing.T) { + reconciler := &Reconciler{Config: Config{JournalDir: t.TempDir()}} + key := client.ObjectKey{Namespace: "cell", Name: "session"} + if err := reconciler.verifyTeardown(key, "capacity"); err == nil { + t.Fatal("missing journal treated as cleanup proof") + } + store, err := journal.Open(filepath.Join(reconciler.Config.JournalDir, "operations")) + if err != nil { + t.Fatal(err) + } + control, err := journal.Open(filepath.Join(reconciler.Config.JournalDir, "sessions")) + if err != nil { + t.Fatal(err) + } + marker := journal.Identity(key.Name, "SESSION", "", nil) + if _, _, err := control.Admit(journal.Operation{ID: marker, SessionName: key.Name, MachineCapacityName: "capacity", DeviceName: "device"}); err != nil { + t.Fatal(err) + } + if _, err := control.Finish(marker, journal.Succeeded, 0, "synthetic proof"); err != nil { + t.Fatal(err) + } + if _, _, err := store.Admit(journal.Operation{ID: "effect", SessionName: key.Name, MachineCapacityName: "capacity", DeviceName: "device"}); err != nil { + t.Fatal(err) + } + if _, err := store.Finish("effect", outcome, 0, "synthetic result"); err != nil { + t.Fatal(err) + } + restarted := &Reconciler{Config: reconciler.Config} + if err := restarted.verifyTeardown(key, "capacity"); (err == nil) != (outcome == journal.Succeeded) { + t.Fatalf("outcome %s: %v", outcome, err) + } + if outcome == journal.Succeeded { + if _, err := control.Get(journal.Identity(key.Name, "REVOKED", "", nil)); err != nil { + t.Fatalf("missing durable revocation: %v", err) + } + if err := os.RemoveAll(filepath.Join(reconciler.Config.JournalDir, "operations")); err != nil { + t.Fatal(err) + } + if err := restarted.verifyTeardown(key, "capacity"); err == nil { + t.Fatal("lost operation directory treated as empty evidence") + } + } + }) + } +} + +func TestStopDrainsRequestsAndDeniesLaterEffects(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + active := &activeSession{cancel: cancel, done: make(chan struct{}), spec: coordinationv1.ProjectedMachineManagementSessionSpec{ClientPublicKey: protocol.PublicKey(privateKey)}} + key := client.ObjectKey{Name: "session", Namespace: "cell"} + reconciler := &Reconciler{Config: Config{Audience: "audience"}, active: map[client.ObjectKey]*activeSession{key: active}} + entered, release, served, stopped := make(chan struct{}), make(chan struct{}), make(chan struct{}), make(chan struct{}) + handler := reconciler.proofMiddleware(active, "route", http.HandlerFunc(func(http.ResponseWriter, *http.Request) { close(entered); <-release })) + proof, err := protocol.Sign(privateKey, "route", "audience", time.Now()) + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodPost, "/", nil) + request.Header.Set(HeaderSession, "route") + request.Header.Set(HeaderAudience, "audience") + request.Header.Set(HeaderTimestamp, proof.Timestamp) + request.Header.Set(HeaderNonce, proof.Nonce) + request.Header.Set(HeaderSignature, proof.Signature) + go func() { handler.ServeHTTP(httptest.NewRecorder(), request); close(served) }() + <-entered + go func() { reconciler.stop(key); close(stopped) }() + <-ctx.Done() + select { + case <-stopped: + t.Fatal("teardown returned with a running effect") + default: + } + close(release) + <-served + <-stopped + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != http.StatusForbidden { + t.Fatalf("post-revocation request: %d", response.Code) + } + if err := reconciler.verifyTeardown(key, "capacity"); err == nil { + t.Fatal("unstopped stream accepted as teardown") + } + close(active.done) +} + +func TestRetainedSessionRejectsChangedInputsAfterRestart(t *testing.T) { + store, err := journal.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + spec := coordinationv1.ProjectedMachineManagementSessionSpec{DesiredState: fleetv1alpha1.ProjectionActive, ClientPublicKey: "key"} + target := resolvedTarget{MachineCapacityName: "capacity", DeviceName: "device", Adapter: "synthetic", SystemID: "physical"} + if err := retainSession(store, "session", spec, target); err != nil { + t.Fatal(err) + } + spec.AuthorityFreshUntil = metav1.Now() + if err := retainSession(store, "session", spec, target); err != nil { + t.Fatalf("freshness could not advance: %v", err) + } + spec.ClientPublicKey = "changed" + if err := retainSession(store, "session", spec, target); err == nil { + t.Fatal("changed client key recovered old authority") + } + spec.ClientPublicKey = "key" + target.DeviceName = "other-device" + if err := retainSession(store, "session", spec, target); err == nil { + t.Fatal("changed device recovered old authority") + } +} + +func TestBindingInputsCannotChangeAfterGatewayAcceptance(t *testing.T) { + a := coordinationv1.ProjectedMachineManagementSessionSpec{ + MachineCapacityRef: fleetv1alpha1.LocalReference{Name: "capacity"}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", + ConnectBefore: metav1.NewTime(time.Unix(100, 0)), ExpiresAt: metav1.NewTime(time.Unix(200, 0)), + AuthorityFreshUntil: metav1.NewTime(time.Unix(110, 0)), + } + b := a + b.AuthorityFreshUntil = metav1.NewTime(time.Unix(120, 0)) + if !sameBinding(a, b) { + t.Fatal("authority freshness was not refreshable") + } + b.MachineCapacityRef.Name = "changed" + if sameBinding(a, b) { + t.Fatal("changed capacity was accepted") + } +} + +func TestEnrollmentResolutionUsesCapacityDeviceNotCustomerTarget(t *testing.T) { + scheme := runtime.NewScheme() + if err := corev1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := fleetv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Name: "allocated", Namespace: DefaultEnrollmentNamespace}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "device-a"}}} + enrollment := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "device-a", Namespace: DefaultEnrollmentNamespace, Labels: map[string]string{EnrollmentDeviceLabel: "device-a"}}, Data: map[string][]byte{"adapter": []byte("sushy-libvirt-v1"), "endpoint": []byte("https://private.invalid"), "system-id": []byte("physical-a"), "username": []byte("user"), "password": []byte("pass")}} + foreign := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "device-b", Namespace: DefaultEnrollmentNamespace, Labels: map[string]string{EnrollmentDeviceLabel: "device-b"}}, Data: map[string][]byte{"adapter": []byte("sushy-libvirt-v1"), "endpoint": []byte("https://foreign.invalid"), "system-id": []byte("physical-b"), "username": []byte("user"), "password": []byte("pass")}} + r := &Reconciler{Client: fake.NewClientBuilder().WithScheme(scheme).WithObjects(capacity, enrollment, foreign).Build(), Config: Config{SupportedAdapter: "sushy-libvirt-v1"}} + target, err := r.resolveTarget(context.Background(), coordinationv1.ProjectedMachineManagementSessionSpec{MachineCapacityRef: fleetv1alpha1.LocalReference{Name: "allocated"}}) + if err != nil { + t.Fatal(err) + } + if target.DeviceName != "device-a" || target.SystemID != "physical-a" || target.BaseURL != "https://private.invalid" { + t.Fatalf("wrong enrollment resolved: %+v", target) + } +} diff --git a/internal/journal/journal.go b/internal/journal/journal.go new file mode 100644 index 00000000..8f503f96 --- /dev/null +++ b/internal/journal/journal.go @@ -0,0 +1,195 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package journal durably records admitted hardware mutations before effects. +package journal + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +type Outcome string + +const ( + Pending Outcome = "Pending" + Succeeded Outcome = "Succeeded" + Failed Outcome = "Failed" + Unknown Outcome = "Unknown" +) + +type Operation struct { + ID string `json:"id"` + SessionName string `json:"sessionName"` + MachineCapacityName string `json:"machineCapacityName"` + DeviceName string `json:"deviceName"` + Method string `json:"method"` + VirtualTarget string `json:"virtualTarget"` + AcceptedBody json.RawMessage `json:"acceptedBody"` + PhysicalTarget string `json:"physicalTarget"` + IdempotencyIdentity string `json:"idempotencyIdentity"` + OperationEpoch int64 `json:"operationEpoch"` + ConflictPrecondition string `json:"conflictPrecondition"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` + Outcome Outcome `json:"outcome"` + Evidence string `json:"evidence,omitempty"` + HTTPStatus int `json:"httpStatus,omitempty"` +} + +func Identity(sessionName, method, target string, body []byte) string { + h := sha256.New() + _, _ = fmt.Fprintf(h, "%s\n%s\n%s\n", sessionName, method, target) + _, _ = h.Write(body) + return hex.EncodeToString(h.Sum(nil)) +} + +type Store struct { + dir string + mu sync.Mutex +} + +var machineLocks = struct { + sync.Mutex + locks map[string]*sync.Mutex +}{locks: map[string]*sync.Mutex{}} + +func Open(dir string) (*Store, error) { + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, err + } + return &Store{dir: dir}, nil +} + +func (s *Store) MachineLock(machineUID string) func() { + machineLocks.Lock() + l := machineLocks.locks[machineUID] + if l == nil { + l = &sync.Mutex{} + machineLocks.locks[machineUID] = l + } + machineLocks.Unlock() + l.Lock() + return l.Unlock +} + +func (s *Store) Admit(op Operation) (Operation, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + if op.ID == "" { + return Operation{}, false, errors.New("operation ID is required") + } + if existing, err := s.read(op.ID); err == nil { + return existing, false, nil + } else if !errors.Is(err, os.ErrNotExist) { + return Operation{}, false, err + } + now := time.Now().UTC() + op.CreatedAt, op.UpdatedAt, op.Outcome = now, now, Pending + if err := s.write(op); err != nil { + return Operation{}, false, err + } + return op, true, nil +} + +func (s *Store) Get(id string) (Operation, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.read(id) +} + +func (s *Store) List() ([]Operation, error) { + s.mu.Lock() + defer s.mu.Unlock() + entries, err := os.ReadDir(s.dir) + if err != nil { + return nil, err + } + operations := make([]Operation, 0, len(entries)) + for _, entry := range entries { + if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" { + continue + } + id := strings.TrimSuffix(entry.Name(), ".json") + op, err := s.read(id) + if err != nil { + return nil, err + } + operations = append(operations, op) + } + return operations, nil +} + +func (s *Store) Finish(id string, outcome Outcome, status int, evidence string) (Operation, error) { + s.mu.Lock() + defer s.mu.Unlock() + op, err := s.read(id) + if err != nil { + return Operation{}, err + } + op.Outcome, op.HTTPStatus, op.Evidence, op.UpdatedAt = outcome, status, evidence, time.Now().UTC() + if err := s.write(op); err != nil { + return Operation{}, err + } + return op, nil +} + +func (s *Store) read(id string) (Operation, error) { + b, err := os.ReadFile(s.path(id)) + if err != nil { + return Operation{}, err + } + var op Operation + if err := json.Unmarshal(b, &op); err != nil { + return Operation{}, err + } + return op, nil +} + +func (s *Store) write(op Operation) error { + b, err := json.MarshalIndent(op, "", " ") + if err != nil { + return err + } + tmp, err := os.CreateTemp(s.dir, ".operation-*.tmp") + if err != nil { + return err + } + name := tmp.Name() + defer os.Remove(name) + if err := tmp.Chmod(0o600); err != nil { + _ = tmp.Close() + return err + } + if _, err := tmp.Write(b); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + _ = tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + if err := os.Rename(name, s.path(op.ID)); err != nil { + return err + } + d, err := os.Open(s.dir) + if err != nil { + return err + } + defer d.Close() + return d.Sync() +} + +func (s *Store) path(id string) string { + return filepath.Join(s.dir, id+".json") +} diff --git a/internal/journal/journal_test.go b/internal/journal/journal_test.go new file mode 100644 index 00000000..168d511d --- /dev/null +++ b/internal/journal/journal_test.go @@ -0,0 +1,29 @@ +package journal + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestAdmissionIsDurableAndDeduplicated(t *testing.T) { + s, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + op := Operation{ID: "op-1", DeviceName: "device-1", Method: "POST", VirtualTarget: "/reset", AcceptedBody: json.RawMessage(`{"ResetType":"On"}`)} + if _, fresh, err := s.Admit(op); err != nil || !fresh { + t.Fatalf("admit fresh=%v err=%v", fresh, err) + } + if _, fresh, err := s.Admit(op); err != nil || fresh { + t.Fatalf("duplicate fresh=%v err=%v", fresh, err) + } + info, err := os.Stat(filepath.Join(s.dir, "op-1.json")) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0o600 { + t.Fatalf("mode %o", info.Mode().Perm()) + } +} diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go new file mode 100644 index 00000000..e48c5f30 --- /dev/null +++ b/internal/metrics/metrics.go @@ -0,0 +1,21 @@ +// SPDX-License-Identifier: Apache-2.0 + +package metrics + +import ( + "github.com/prometheus/client_golang/prometheus" + controllermetrics "sigs.k8s.io/controller-runtime/pkg/metrics" +) + +var ( + SessionAdmissions = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "fleet_machine_management_session_admissions_total", Help: "Machine-management session admission decisions."}, []string{"outcome"}) + ActiveSessions = prometheus.NewGauge(prometheus.GaugeOpts{Name: "fleet_machine_management_active_sessions", Help: "Active location gateway sessions."}) + RevocationLatency = prometheus.NewHistogram(prometheus.HistogramOpts{Name: "fleet_machine_management_revocation_latency_seconds", Help: "Time from public deletion to location teardown outcome.", Buckets: prometheus.DefBuckets}) + BMCReachability = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "fleet_machine_management_bmc_requests_total", Help: "BMC adapter request outcomes."}, []string{"outcome"}) + Operations = prometheus.NewCounterVec(prometheus.CounterOpts{Name: "fleet_machine_management_operations_total", Help: "Durably journaled mutation outcomes."}, []string{"outcome"}) + UnknownOperations = prometheus.NewGauge(prometheus.GaugeOpts{Name: "fleet_machine_management_unknown_operations", Help: "Operations with an unknown physical outcome."}) +) + +func init() { + controllermetrics.Registry.MustRegister(SessionAdmissions, ActiveSessions, RevocationLatency, BMCReachability, Operations, UnknownOperations) +} diff --git a/internal/protocol/proof.go b/internal/protocol/proof.go new file mode 100644 index 00000000..3d12441d --- /dev/null +++ b/internal/protocol/proof.go @@ -0,0 +1,76 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package protocol defines the Fleet-specific client proof. It is deliberately +// independent of Compute's provisional internal protocol. +package protocol + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "strconv" + "strings" + "time" +) + +const ( + Version = "redfish-v1alpha1" + Domain = "datum-fleet-machine-management-v1" + ClockSkew = 30 * time.Second +) + +type Proof struct { + Timestamp string + Nonce string + Signature string +} + +func PublicKey(key ed25519.PrivateKey) string { + return hex.EncodeToString(key.Public().(ed25519.PublicKey)) +} + +func Sign(key ed25519.PrivateKey, sessionUID, audience string, now time.Time) (Proof, error) { + nonceBytes := make([]byte, 24) + if _, err := rand.Read(nonceBytes); err != nil { + return Proof{}, err + } + p := Proof{Timestamp: strconv.FormatInt(now.Unix(), 10), Nonce: base64.RawURLEncoding.EncodeToString(nonceBytes)} + p.Signature = base64.StdEncoding.EncodeToString(ed25519.Sign(key, message(sessionUID, audience, p.Timestamp, p.Nonce))) + return p, nil +} + +func Verify(publicKey, sessionUID, audience string, p Proof, now time.Time, usedNonce func(string) bool) error { + pub, err := hex.DecodeString(publicKey) + if err != nil || len(pub) != ed25519.PublicKeySize { + return errors.New("invalid session client public key") + } + ts, err := strconv.ParseInt(p.Timestamp, 10, 64) + if err != nil { + return errors.New("missing or malformed proof timestamp") + } + d := now.Sub(time.Unix(ts, 0)) + if d > ClockSkew || d < -ClockSkew { + return fmt.Errorf("proof timestamp outside %s clock skew", ClockSkew) + } + if p.Nonce == "" { + return errors.New("missing proof nonce") + } + sig, err := base64.StdEncoding.DecodeString(p.Signature) + if err != nil { + return errors.New("malformed proof signature") + } + if !ed25519.Verify(ed25519.PublicKey(pub), message(sessionUID, audience, p.Timestamp, p.Nonce), sig) { + return errors.New("proof signature does not match session key and gateway audience") + } + if usedNonce != nil && usedNonce(p.Nonce) { + return errors.New("proof nonce was already consumed") + } + return nil +} + +func message(sessionUID, audience, timestamp, nonce string) []byte { + return []byte(strings.Join([]string{Domain, Version, sessionUID, audience, timestamp, nonce}, "\n")) +} diff --git a/internal/protocol/proof_test.go b/internal/protocol/proof_test.go new file mode 100644 index 00000000..0dab06d2 --- /dev/null +++ b/internal/protocol/proof_test.go @@ -0,0 +1,37 @@ +package protocol + +import ( + "crypto/ed25519" + "crypto/rand" + "testing" + "time" +) + +func TestProofBindingAndReplay(t *testing.T) { + _, key, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + now := time.Unix(1000, 0) + p, err := Sign(key, "session-a", "gateway-a", now) + if err != nil { + t.Fatal(err) + } + used := false + consume := func(string) bool { old := used; used = true; return old } + if err := Verify(PublicKey(key), "session-a", "gateway-a", p, now, consume); err != nil { + t.Fatal(err) + } + if err := Verify(PublicKey(key), "session-a", "gateway-a", p, now, consume); err == nil { + t.Fatal("replay accepted") + } + if err := Verify(PublicKey(key), "session-a", "gateway-b", p, now, nil); err == nil { + t.Fatal("changed audience accepted") + } + if err := Verify(PublicKey(key), "session-b", "gateway-a", p, now, nil); err == nil { + t.Fatal("changed session accepted") + } + if err := Verify(PublicKey(key), "session-a", "gateway-a", p, now.Add(ClockSkew+time.Second), nil); err == nil { + t.Fatal("expired signature accepted") + } +} diff --git a/internal/redfish/adapter.go b/internal/redfish/adapter.go new file mode 100644 index 00000000..b59b2800 --- /dev/null +++ b/internal/redfish/adapter.go @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: Apache-2.0 + +package redfish + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" +) + +var ErrResponseLost = errors.New("BMC may have applied the effect but its response was lost") + +type System struct { + PowerState string + BootTarget string +} + +type Adapter interface { + Observe(context.Context) (System, error) + SetOneTimeBoot(context.Context, string) error + Reset(context.Context, string) error + PhysicalTarget() string +} + +// SushyAdapter calls exactly one internally selected sushy-emulator system. +// Customer URLs, Host headers, links, and IDs never enter these requests. +type SushyAdapter struct { + BaseURL string + SystemID string + Username string + Password string + Client *http.Client + DropResetResponseOnce bool + dropped bool +} + +func (a *SushyAdapter) Observe(ctx context.Context) (System, error) { + var body struct { + PowerState string `json:"PowerState"` + Boot struct { + Target string `json:"BootSourceOverrideTarget"` + } `json:"Boot"` + } + if err := a.doJSON(ctx, http.MethodGet, a.systemPath(), nil, &body); err != nil { + return System{}, err + } + return System{PowerState: body.PowerState, BootTarget: physicalToVirtualBoot(body.Boot.Target)}, nil +} + +func (a *SushyAdapter) SetOneTimeBoot(ctx context.Context, target string) error { + physical, ok := map[string]string{"Pxe": "Pxe", "Hdd": "Hdd"}[target] + if !ok { + return fmt.Errorf("unsupported boot target %q", target) + } + body := map[string]any{"Boot": map[string]any{"BootSourceOverrideEnabled": "Once", "BootSourceOverrideTarget": physical}} + return a.doJSON(ctx, http.MethodPatch, a.systemPath(), body, nil) +} + +func (a *SushyAdapter) Reset(ctx context.Context, resetType string) error { + if !supportedReset(resetType) { + return fmt.Errorf("unsupported ResetType %q", resetType) + } + body := map[string]string{"ResetType": resetType} + err := a.doJSON(ctx, http.MethodPost, a.systemPath()+"/Actions/ComputerSystem.Reset", body, nil) + if err == nil && a.DropResetResponseOnce && !a.dropped { + a.dropped = true + return ErrResponseLost + } + return err +} + +func (a *SushyAdapter) PhysicalTarget() string { return "bmc-system:" + a.SystemID } + +func (a *SushyAdapter) systemPath() string { + return "/redfish/v1/Systems/" + url.PathEscape(a.SystemID) +} + +func (a *SushyAdapter) doJSON(ctx context.Context, method, path string, in, out any) error { + var body io.Reader + if in != nil { + b, err := json.Marshal(in) + if err != nil { + return err + } + body = bytes.NewReader(b) + } + req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(a.BaseURL, "/")+path, body) + if err != nil { + return err + } + req.Header.Set("Accept", "application/json") + if in != nil { + req.Header.Set("Content-Type", "application/json") + } + req.SetBasicAuth(a.Username, a.Password) + client := a.Client + if client == nil { + client = http.DefaultClient + } + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("BMC unavailable: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096)) + return fmt.Errorf("BMC rejected the qualified operation with status %d", resp.StatusCode) + } + if out != nil { + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out); err != nil { + return fmt.Errorf("invalid BMC response: %w", err) + } + } + return nil +} + +func physicalToVirtualBoot(v string) string { + if v == "Pxe" { + return "Pxe" + } + return "Hdd" +} +func supportedReset(v string) bool { + return v == "On" || v == "ForceOff" || v == "GracefulShutdown" || v == "GracefulRestart" || v == "ForceRestart" +} diff --git a/internal/redfish/handler.go b/internal/redfish/handler.go new file mode 100644 index 00000000..a100d0d0 --- /dev/null +++ b/internal/redfish/handler.go @@ -0,0 +1,375 @@ +// SPDX-License-Identifier: Apache-2.0 + +package redfish + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "go.datum.net/fleet/internal/journal" + fleetmetrics "go.datum.net/fleet/internal/metrics" +) + +const SystemID = "allocated" + +type Authority struct { + SessionName string + MachineCapacityName string + DeviceName string + OperationEpoch int64 + ExpiresAt time.Time + FreshUntil time.Time +} + +type Handler struct { + Adapter Adapter + Journal *journal.Store + Authority Authority + CurrentAuthority func() Authority + Now func() time.Time + mu sync.Mutex + tokens map[string]bool +} + +func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + setODataHeaders(w) + if err := h.checkRequest(r); err != nil { + writeError(w, http.StatusBadRequest, "Base.1.18.PropertyValueFormatError", err.Error()) + return + } + authority := h.authority() + if h.now().After(authority.ExpiresAt) { + writeError(w, http.StatusForbidden, "Fleet.1.0.SessionExpired", "The machine-management session has expired.") + return + } + if h.now().After(authority.FreshUntil) { + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.AuthorityStale", "Allocation authority is stale; the gateway has failed closed.") + return + } + switch { + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/": + h.serviceRoot(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/SessionService": + h.sessionService(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/SessionService/Sessions": + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#SessionCollection.SessionCollection", "@odata.id": r.URL.Path, "Name": "Sessions", "Members": []any{}, "Members@odata.count": 0}) + case r.Method == http.MethodPost && r.URL.Path == "/redfish/v1/SessionService/Sessions": + h.login(w, r) + case r.Method == http.MethodDelete && strings.HasPrefix(r.URL.Path, "/redfish/v1/SessionService/Sessions/"): + h.logout(w, r) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/Systems": + h.systems(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/Systems/"+SystemID: + h.system(w, r) + case r.Method == http.MethodPatch && r.URL.Path == "/redfish/v1/Systems/"+SystemID: + h.patchSystem(w, r) + case r.Method == http.MethodPost && r.URL.Path == "/redfish/v1/Systems/"+SystemID+"/Actions/ComputerSystem.Reset": + h.reset(w, r) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/TaskService": + h.taskService(w) + case r.Method == http.MethodGet && r.URL.Path == "/redfish/v1/TaskService/Tasks": + h.tasks(w) + case r.Method == http.MethodGet && strings.HasPrefix(r.URL.Path, "/redfish/v1/TaskService/Tasks/"): + h.task(w, strings.TrimPrefix(r.URL.Path, "/redfish/v1/TaskService/Tasks/")) + default: + writeError(w, http.StatusNotFound, "Base.1.18.ResourceMissingAtURI", "The resource is outside the Fleet Provisioning profile.") + } +} + +func (h *Handler) checkRequest(r *http.Request) error { + if r.URL.RawPath != "" { + if u, err := url.PathUnescape(r.URL.RawPath); err != nil || u != r.URL.Path { + return errors.New("encoded or ambiguous paths are not accepted") + } + } + if strings.Contains(r.URL.Path, "..") || !strings.HasPrefix(r.URL.Path, "/redfish/v1") { + return errors.New("target is outside the virtual Redfish service") + } + if r.URL.IsAbs() || r.RequestURI == "*" { + return errors.New("absolute and arbitrary targets are not accepted") + } + host := r.Host + if i := strings.LastIndex(host, ":"); i >= 0 { + host = host[:i] + } + host = strings.Trim(host, "[]") + if host != "" && host != "127.0.0.1" && host != "localhost" && host != "fleet-gateway" { + return errors.New("Host routing is not accepted") + } + return nil +} + +func (h *Handler) serviceRoot(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ServiceRoot.v1_15_0.ServiceRoot", "@odata.id": "/redfish/v1/", "Id": "RootService", "Name": "Fleet Virtual Redfish Service", "RedfishVersion": "1.18.0", "UUID": virtualUUID(h.authority().SessionName), "Systems": odata("/redfish/v1/Systems"), "SessionService": odata("/redfish/v1/SessionService"), "Tasks": odata("/redfish/v1/TaskService"), "Links": map[string]any{"Sessions": odata("/redfish/v1/SessionService/Sessions")}}) +} + +func virtualUUID(sessionName string) string { + sum := sha256.Sum256([]byte("go.datum.net/fleet/redfish-service-root/v1\n" + sessionName)) + b := sum[:16] + b[6] = (b[6] & 0x0f) | 0x50 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) +} +func (h *Handler) sessionService(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#SessionService.v1_2_0.SessionService", "@odata.id": "/redfish/v1/SessionService", "Id": "SessionService", "Name": "Session Service", "ServiceEnabled": true, "SessionTimeout": 900, "Sessions": odata("/redfish/v1/SessionService/Sessions")}) +} + +func (h *Handler) login(w http.ResponseWriter, r *http.Request) { + var in struct { + UserName string `json:"UserName"` + Password string `json:"Password"` + } + if err := decodeExact(r, &in); err != nil || in.UserName == "" || in.Password == "" { + writeError(w, http.StatusBadRequest, "Base.1.18.MalformedJSON", "UserName and Password are required.") + return + } + b := make([]byte, 24) + _, _ = rand.Read(b) + token := base64.RawURLEncoding.EncodeToString(b) + h.mu.Lock() + if h.tokens == nil { + h.tokens = map[string]bool{} + } + h.tokens[token] = true + h.mu.Unlock() + loc := "/redfish/v1/SessionService/Sessions/local" + w.Header().Set("X-Auth-Token", token) + w.Header().Set("Location", loc) + writeJSON(w, http.StatusCreated, map[string]any{"@odata.type": "#Session.v1_7_0.Session", "@odata.id": loc, "Id": "local", "Name": "Fleet session-local login", "UserName": in.UserName}) +} +func (h *Handler) logout(w http.ResponseWriter, r *http.Request) { + h.mu.Lock() + delete(h.tokens, r.Header.Get("X-Auth-Token")) + h.mu.Unlock() + w.WriteHeader(http.StatusNoContent) +} + +func (h *Handler) systems(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ComputerSystemCollection.ComputerSystemCollection", "@odata.id": "/redfish/v1/Systems", "Name": "Computer System Collection", "Members": []any{odata("/redfish/v1/Systems/" + SystemID)}, "Members@odata.count": 1}) +} + +func (h *Handler) system(w http.ResponseWriter, r *http.Request) { + s, err := h.Adapter.Observe(r.Context()) + if err != nil { + fleetmetrics.BMCReachability.WithLabelValues("unreachable").Inc() + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.BMCUnavailable", "The allocated system management endpoint is unavailable.") + return + } + fleetmetrics.BMCReachability.WithLabelValues("reachable").Inc() + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#ComputerSystem.v1_20_0.ComputerSystem", "@odata.id": r.URL.Path, "Id": SystemID, "Name": "Allocated Machine", "SystemType": "Physical", "PowerState": s.PowerState, "Status": map[string]string{"State": "Enabled", "Health": "OK"}, "Boot": map[string]any{"BootSourceOverrideEnabled": "Once", "BootSourceOverrideTarget": s.BootTarget, "BootSourceOverrideTarget@Redfish.AllowableValues": []string{"Pxe", "Hdd"}}, "Actions": map[string]any{"#ComputerSystem.Reset": map[string]any{"target": r.URL.Path + "/Actions/ComputerSystem.Reset", "ResetType@Redfish.AllowableValues": []string{"On", "ForceOff", "GracefulShutdown", "GracefulRestart", "ForceRestart"}}}}) +} + +func (h *Handler) patchSystem(w http.ResponseWriter, r *http.Request) { + raw, err := readBody(r) + if err != nil { + writeError(w, http.StatusBadRequest, "Base.1.18.MalformedJSON", err.Error()) + return + } + var in struct { + Boot *struct { + Enabled string `json:"BootSourceOverrideEnabled"` + Target string `json:"BootSourceOverrideTarget"` + } `json:"Boot"` + } + if err := json.Unmarshal(raw, &in); err != nil || in.Boot == nil { + writeError(w, http.StatusBadRequest, "Base.1.18.PropertyNotWritable", "Only Boot one-time override is writable.") + return + } + var generic map[string]any + _ = json.Unmarshal(raw, &generic) + boot, bootOK := generic["Boot"].(map[string]any) + if len(generic) != 1 || !bootOK || len(boot) != 2 || in.Boot.Enabled != "Once" || (in.Boot.Target != "Pxe" && in.Boot.Target != "Hdd") { + writeError(w, http.StatusBadRequest, "Base.1.18.PropertyValueNotInList", "Only one-time Pxe or Hdd boot selection is supported.") + return + } + h.mutate(w, r, raw, func() error { return h.Adapter.SetOneTimeBoot(r.Context(), in.Boot.Target) }) +} + +func (h *Handler) reset(w http.ResponseWriter, r *http.Request) { + raw, err := readBody(r) + if err != nil { + writeError(w, http.StatusBadRequest, "Base.1.18.MalformedJSON", err.Error()) + return + } + var in struct { + ResetType string `json:"ResetType"` + } + var generic map[string]any + if json.Unmarshal(raw, &in) != nil || json.Unmarshal(raw, &generic) != nil || len(generic) != 1 || !supportedReset(in.ResetType) { + writeError(w, http.StatusBadRequest, "Base.1.18.ActionParameterNotSupported", "ResetType is not supported by this profile.") + return + } + h.mutate(w, r, raw, func() error { return h.Adapter.Reset(r.Context(), in.ResetType) }) +} + +func (h *Handler) mutate(w http.ResponseWriter, r *http.Request, raw []byte, effect func() error) { + now := h.now() + authority := h.authority() + if now.After(authority.ExpiresAt) { + writeError(w, http.StatusForbidden, "Fleet.1.0.SessionExpired", "The machine-management session has expired.") + return + } + if now.After(authority.FreshUntil) { + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.AuthorityStale", "Allocation authority is stale; the gateway has failed closed.") + return + } + id := journal.Identity(authority.SessionName, r.Method, r.URL.Path, raw) + unlock := h.Journal.MachineLock(authority.DeviceName) + defer unlock() + current := h.authority() + if current.SessionName != authority.SessionName || current.DeviceName != authority.DeviceName || current.MachineCapacityName != authority.MachineCapacityName || current.OperationEpoch != authority.OperationEpoch || !h.now().Before(current.ExpiresAt) || !h.now().Before(current.FreshUntil) { + writeError(w, http.StatusServiceUnavailable, "Fleet.1.0.AuthorityStale", "Hardware authority changed while waiting for serialization.") + return + } + operations, err := h.Journal.List() + if err != nil { + writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "Prior hardware effects could not be verified.") + return + } + for _, operation := range operations { + if operation.DeviceName == authority.DeviceName && operation.ID != id && operation.Outcome != journal.Succeeded { + writeError(w, http.StatusConflict, "Fleet.1.0.OperationUnconfirmed", "A previous hardware effect has not been verified.") + return + } + } + op, fresh, err := h.Journal.Admit(journal.Operation{ID: id, SessionName: authority.SessionName, MachineCapacityName: authority.MachineCapacityName, DeviceName: authority.DeviceName, Method: r.Method, VirtualTarget: r.URL.Path, AcceptedBody: append([]byte(nil), raw...), PhysicalTarget: h.Adapter.PhysicalTarget(), IdempotencyIdentity: id, OperationEpoch: authority.OperationEpoch, ConflictPrecondition: fmt.Sprintf("capacity=%s device=%s fresh-before=%s", authority.MachineCapacityName, authority.DeviceName, authority.FreshUntil.UTC().Format(time.RFC3339))}) + if err != nil { + writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "The mutation could not be durably admitted.") + return + } + if !fresh { + h.writeExistingTask(w, op) + return + } + if err := effect(); err != nil { + if errors.Is(err, ErrResponseLost) { + op, _ = h.Journal.Finish(id, journal.Unknown, 0, "effect submitted; response lost; recover before retry") + fleetmetrics.Operations.WithLabelValues("unknown").Inc() + fleetmetrics.UnknownOperations.Inc() + h.writeExistingTask(w, op) + return + } + op, _ = h.Journal.Finish(id, journal.Unknown, http.StatusBadGateway, "adapter failure does not establish whether the effect occurred") + fleetmetrics.Operations.WithLabelValues("unknown").Inc() + fleetmetrics.UnknownOperations.Inc() + writeError(w, http.StatusBadGateway, "Fleet.1.0.BMCOperationFailed", "The allocated system did not complete the requested operation.") + return + } + op, _ = h.Journal.Finish(id, journal.Succeeded, http.StatusOK, "adapter response received") + fleetmetrics.Operations.WithLabelValues("succeeded").Inc() + w.Header().Set("Location", "/redfish/v1/TaskService/Tasks/"+op.ID) + writeJSON(w, http.StatusAccepted, taskBody(op)) +} + +func (h *Handler) writeExistingTask(w http.ResponseWriter, op journal.Operation) { + w.Header().Set("Location", "/redfish/v1/TaskService/Tasks/"+op.ID) + writeJSON(w, http.StatusAccepted, taskBody(op)) +} +func (h *Handler) taskService(w http.ResponseWriter) { + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#TaskService.v1_2_0.TaskService", "@odata.id": "/redfish/v1/TaskService", "Id": "TaskService", "Name": "Task Service", "ServiceEnabled": true, "Tasks": odata("/redfish/v1/TaskService/Tasks")}) +} +func (h *Handler) tasks(w http.ResponseWriter) { + operations, err := h.Journal.List() + if err != nil { + writeError(w, http.StatusInternalServerError, "Fleet.1.0.JournalUnavailable", "Tasks could not be read from the durable journal.") + return + } + members := make([]any, 0, len(operations)) + for _, operation := range operations { + if operation.SessionName == h.authority().SessionName { + members = append(members, odata("/redfish/v1/TaskService/Tasks/"+operation.ID)) + } + } + writeJSON(w, http.StatusOK, map[string]any{"@odata.type": "#TaskCollection.TaskCollection", "@odata.id": "/redfish/v1/TaskService/Tasks", "Name": "Tasks", "Members": members, "Members@odata.count": len(members)}) +} +func (h *Handler) task(w http.ResponseWriter, id string) { + op, err := h.Journal.Get(id) + if err != nil || op.SessionName != h.authority().SessionName { + writeError(w, http.StatusNotFound, "Base.1.18.ResourceMissingAtURI", "Task not found.") + return + } + writeJSON(w, http.StatusOK, taskBody(op)) +} + +func taskBody(op journal.Operation) map[string]any { + state, status := "Running", "OK" + if op.Outcome == journal.Succeeded { + state = "Completed" + } + if op.Outcome == journal.Failed { + state = "Exception" + status = "Critical" + } + if op.Outcome == journal.Unknown { + state = "Exception" + status = "Warning" + } + return map[string]any{"@odata.type": "#Task.v1_7_4.Task", "@odata.id": "/redfish/v1/TaskService/Tasks/" + op.ID, "Id": op.ID, "Name": "Fleet machine operation", "TaskState": state, "TaskStatus": status, "Messages": []any{map[string]any{"MessageId": "Fleet.1.0." + string(op.Outcome), "Message": op.Evidence, "MessageSeverity": status, "Resolution": "Inspect or recover the existing operation; do not resubmit an unknown effect."}}} +} +func odata(path string) map[string]string { return map[string]string{"@odata.id": path} } +func setODataHeaders(w http.ResponseWriter) { + w.Header().Set("OData-Version", "4.0") + w.Header().Set("Content-Type", "application/json") +} +func writeJSON(w http.ResponseWriter, status int, v any) { + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} +func writeError(w http.ResponseWriter, status int, id, message string) { + writeJSON(w, status, map[string]any{ + "error": map[string]any{ + "code": id, + "message": message, + "@Message.ExtendedInfo": []any{map[string]any{ + "MessageId": id, + "Message": message, + "Severity": "Critical", + "Resolution": "Use only resources and values declared by the Fleet Provisioning profile.", + }}, + }, + }) +} +func readBody(r *http.Request) ([]byte, error) { + defer r.Body.Close() + b, err := io.ReadAll(io.LimitReader(r.Body, 64<<10)) + if err != nil { + return nil, err + } + if len(b) == 0 { + return nil, errors.New("request body is required") + } + var v any + if json.Unmarshal(b, &v) != nil { + return nil, errors.New("request body must be valid JSON") + } + return b, nil +} +func decodeExact(r *http.Request, v any) error { + defer r.Body.Close() + d := json.NewDecoder(io.LimitReader(r.Body, 64<<10)) + d.DisallowUnknownFields() + return d.Decode(v) +} +func (h *Handler) now() time.Time { + if h.Now != nil { + return h.Now() + } + return time.Now() +} + +func (h *Handler) authority() Authority { + if h.CurrentAuthority != nil { + return h.CurrentAuthority() + } + return h.Authority +} diff --git a/internal/redfish/handler_test.go b/internal/redfish/handler_test.go new file mode 100644 index 00000000..888137b8 --- /dev/null +++ b/internal/redfish/handler_test.go @@ -0,0 +1,221 @@ +package redfish + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "go.datum.net/fleet/internal/journal" +) + +type fakeAdapter struct { + resets int + boots int + lost bool +} + +func (a *fakeAdapter) Observe(context.Context) (System, error) { + return System{PowerState: "Off", BootTarget: "Hdd"}, nil +} +func (a *fakeAdapter) SetOneTimeBoot(context.Context, string) error { a.boots++; return nil } +func (a *fakeAdapter) Reset(context.Context, string) error { + a.resets++ + if a.lost { + a.lost = false + return ErrResponseLost + } + return nil +} +func (a *fakeAdapter) PhysicalTarget() string { return "private-target" } + +func newHandler(t *testing.T, a Adapter) *Handler { + t.Helper() + s, err := journal.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + now := time.Unix(1000, 0) + return &Handler{Adapter: a, Journal: s, Now: func() time.Time { return now }, Authority: Authority{SessionName: "session", MachineCapacityName: "capacity", DeviceName: "device", OperationEpoch: 1, ExpiresAt: now.Add(time.Hour), FreshUntil: now.Add(time.Minute)}} +} + +func request(h http.Handler, method, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.Host = "127.0.0.1:9443" + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +func TestNarrowProfileAndSingleSystem(t *testing.T) { + h := newHandler(t, &fakeAdapter{}) + for _, p := range []string{"/redfish/v1/AccountService", "/redfish/v1/Managers", "/redfish/v1/UpdateService", "/redfish/v1/Systems/guessed", "/redfish/v1/Systems/allocated/Oem/Reset"} { + if got := request(h, http.MethodGet, p, "").Code; got != http.StatusNotFound { + t.Errorf("%s: %d", p, got) + } + } + w := request(h, http.MethodGet, "/redfish/v1/Systems", "") + if w.Code != 200 || strings.Contains(w.Body.String(), "private-target") { + t.Fatalf("systems: %d %s", w.Code, w.Body.String()) + } + var body map[string]any + if json.Unmarshal(w.Body.Bytes(), &body) != nil || body["Members@odata.count"].(float64) != 1 { + t.Fatalf("unexpected collection %s", w.Body.String()) + } + r := httptest.NewRequest(http.MethodGet, "/redfish/v1/Systems", nil) + r.Host = "second-bmc.internal" + rr := httptest.NewRecorder() + h.ServeHTTP(rr, r) + if rr.Code != http.StatusBadRequest { + t.Fatalf("Host manipulation accepted: %d", rr.Code) + } +} + +func TestUnsupportedMutationsRejected(t *testing.T) { + a := &fakeAdapter{} + h := newHandler(t, a) + bad := []string{`{"Boot":{"BootSourceOverrideEnabled":"Once","BootSourceOverrideTarget":"Usb"}}`, `{"AssetTag":"x"}`} + for _, body := range bad { + if got := request(h, http.MethodPatch, "/redfish/v1/Systems/allocated", body).Code; got != 400 { + t.Fatalf("patch %s: %d", body, got) + } + } + if got := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"Nmi"}`).Code; got != 400 { + t.Fatalf("reset: %d", got) + } + if a.boots != 0 || a.resets != 0 { + t.Fatal("rejected request reached adapter") + } +} + +func TestServiceRootUsesStandardTaskAndSessionLinks(t *testing.T) { + handler := newHandler(t, &fakeAdapter{}) + response := request(handler, http.MethodGet, "/redfish/v1/", "") + if response.Code != http.StatusOK { + t.Fatalf("service root: %d %s", response.Code, response.Body.String()) + } + var root struct { + Tasks map[string]string + Links map[string]map[string]string + TaskService json.RawMessage + } + if err := json.Unmarshal(response.Body.Bytes(), &root); err != nil { + t.Fatal(err) + } + if root.TaskService != nil { + t.Fatal("ServiceRoot exposed the nonstandard TaskService property") + } + if root.Tasks["@odata.id"] != "/redfish/v1/TaskService" { + t.Fatalf("incorrect task link: %v", root.Tasks) + } + if root.Links["Sessions"]["@odata.id"] != "/redfish/v1/SessionService/Sessions" { + t.Fatalf("incorrect session link: %v", root.Links) + } +} + +func TestLostResponseIsUnknownAndNeverDuplicatesReset(t *testing.T) { + a := &fakeAdapter{lost: true} + h := newHandler(t, a) + body := `{"ResetType":"ForceRestart"}` + w1 := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", body) + w2 := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", body) + if w1.Code != 202 || w2.Code != 202 { + t.Fatalf("codes %d %d", w1.Code, w2.Code) + } + if a.resets != 1 { + t.Fatalf("reset executed %d times", a.resets) + } + if !strings.Contains(w2.Body.String(), "Unknown") { + t.Fatalf("retry did not preserve unknown: %s", w2.Body.String()) + } + conflicting := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"ForceOff"}`) + if conflicting.Code != http.StatusConflict || a.resets != 1 { + t.Fatal("a new power effect bypassed an unresolved prior effect") + } +} + +func TestQueuedMutationRechecksAuthority(t *testing.T) { + adapter := &fakeAdapter{} + handler := newHandler(t, adapter) + reads := 0 + handler.CurrentAuthority = func() Authority { + reads++ + authority := handler.Authority + if reads > 1 { + authority.FreshUntil = handler.Now().Add(-time.Second) + } + return authority + } + response := request(handler, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if response.Code != http.StatusServiceUnavailable || adapter.resets != 0 { + t.Fatalf("stale queued mutation executed: %d, %d", response.Code, adapter.resets) + } +} + +func TestTaskCollectionListsOnlyCurrentSession(t *testing.T) { + h := newHandler(t, &fakeAdapter{}) + mutation := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if mutation.Code != http.StatusAccepted { + t.Fatalf("mutation: %d %s", mutation.Code, mutation.Body.String()) + } + collection := request(h, http.MethodGet, "/redfish/v1/TaskService/Tasks", "") + if collection.Code != http.StatusOK || !strings.Contains(collection.Body.String(), `"Members@odata.count":1`) { + t.Fatalf("tasks: %d %s", collection.Code, collection.Body.String()) + } +} + +func TestStaleAuthorityFailsClosed(t *testing.T) { + h := newHandler(t, &fakeAdapter{}) + h.Authority.FreshUntil = time.Unix(999, 0) + w := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "AuthorityStale") { + t.Fatalf("%d %s", w.Code, w.Body.String()) + } +} + +func TestExpiredSessionFailsClosed(t *testing.T) { + a := &fakeAdapter{} + h := newHandler(t, a) + h.Authority.ExpiresAt = time.Unix(999, 0) + w := request(h, http.MethodPost, "/redfish/v1/Systems/allocated/Actions/ComputerSystem.Reset", `{"ResetType":"On"}`) + if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "SessionExpired") || a.resets != 0 { + t.Fatalf("expired request: code=%d resets=%d body=%s", w.Code, a.resets, w.Body.String()) + } +} + +func TestAdapterResponseLostSentinel(t *testing.T) { + if !errors.Is(ErrResponseLost, ErrResponseLost) { + t.Fatal("sentinel") + } +} + +func TestTaskMessageSeverityPreservesOperationOutcome(t *testing.T) { + for _, test := range []struct { + outcome journal.Outcome + state string + status string + }{ + {journal.Pending, "Running", "OK"}, + {journal.Succeeded, "Completed", "OK"}, + {journal.Failed, "Exception", "Critical"}, + {journal.Unknown, "Exception", "Warning"}, + } { + t.Run(string(test.outcome), func(t *testing.T) { + body := taskBody(journal.Operation{ID: "operation", Outcome: test.outcome, Evidence: "retained evidence"}) + if body["TaskState"] != test.state || body["TaskStatus"] != test.status { + t.Fatalf("operation outcome changed: %v", body) + } + message := body["Messages"].([]any)[0].(map[string]any) + if message["MessageSeverity"] != test.status || message["MessageId"] != "Fleet.1.0."+string(test.outcome) { + t.Fatalf("incorrect operation message: %v", message) + } + if _, present := message["Severity"]; present { + t.Fatal("deprecated message Severity remains exposed") + } + }) + } +} diff --git a/internal/relay/relay.go b/internal/relay/relay.go new file mode 100644 index 00000000..a9a5fb2b --- /dev/null +++ b/internal/relay/relay.go @@ -0,0 +1,143 @@ +// SPDX-License-Identifier: Apache-2.0 + +// Package relay pairs one outbound location connection with one client. After +// pairing it copies opaque bytes and cannot inspect the inner TLS/Redfish data. +package relay + +import ( + "bufio" + "crypto/subtle" + "fmt" + "io" + "net" + "strings" + "sync" + "time" +) + +type Server struct { + GatewayToken string + mu sync.Mutex + routes map[string]net.Conn +} + +func NewServer(token string) *Server { + return &Server{GatewayToken: token, routes: map[string]net.Conn{}} +} + +func (s *Server) Serve(l net.Listener) error { + for { + c, err := l.Accept() + if err != nil { + return err + } + go s.handle(c) + } +} + +func (s *Server) handle(c net.Conn) { + _ = c.SetReadDeadline(time.Now().Add(10 * time.Second)) + br := bufio.NewReader(io.LimitReader(c, 4096)) + line, err := br.ReadString('\n') + if err != nil { + _ = c.Close() + return + } + parts := strings.Fields(line) + switch { + case len(parts) == 3 && parts[0] == "GATEWAY": + if subtle.ConstantTimeCompare([]byte(parts[2]), []byte(s.GatewayToken)) != 1 { + reject(c, "gateway authentication failed") + return + } + s.register(parts[1], c) + case len(parts) == 2 && parts[0] == "CLIENT": + s.connect(parts[1], c) + default: + reject(c, "invalid relay preface") + } +} + +func (s *Server) register(route string, c net.Conn) { + s.mu.Lock() + if old := s.routes[route]; old != nil { + s.mu.Unlock() + reject(c, "route already registered") + return + } + s.routes[route] = c + s.mu.Unlock() + _ = c.SetDeadline(time.Time{}) + if _, err := io.WriteString(c, "WAIT\n"); err != nil { + s.remove(route, c) + _ = c.Close() + } +} + +func (s *Server) connect(route string, client net.Conn) { + s.mu.Lock() + gateway := s.routes[route] + delete(s.routes, route) // the first connector consumes the route + s.mu.Unlock() + if gateway == nil { + reject(client, "route unavailable or already consumed") + return + } + _ = client.SetDeadline(time.Time{}) + if _, err := io.WriteString(client, "OK\n"); err != nil { + _ = client.Close() + _ = gateway.Close() + return + } + if _, err := io.WriteString(gateway, "OK\n"); err != nil { + _ = client.Close() + _ = gateway.Close() + return + } + proxy(client, gateway) +} + +func (s *Server) remove(route string, c net.Conn) { + s.mu.Lock() + defer s.mu.Unlock() + if s.routes[route] == c { + delete(s.routes, route) + } +} + +func reject(c net.Conn, reason string) { _, _ = fmt.Fprintf(c, "ERROR %s\n", reason); _ = c.Close() } + +func proxy(a, b net.Conn) { + var once sync.Once + closeBoth := func() { _ = a.Close(); _ = b.Close() } + go func() { _, _ = io.Copy(a, b); once.Do(closeBoth) }() + go func() { _, _ = io.Copy(b, a); once.Do(closeBoth) }() +} + +func Register(conn net.Conn, route, token string) error { + if _, err := fmt.Fprintf(conn, "GATEWAY %s %s\n", route, token); err != nil { + return err + } + line, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + return err + } + if line != "WAIT\n" { + return fmt.Errorf("relay rejected gateway: %s", strings.TrimSpace(line)) + } + return nil +} + +func Connect(conn net.Conn, route string) error { + if _, err := fmt.Fprintf(conn, "CLIENT %s\n", route); err != nil { + return err + } + line, err := bufio.NewReader(conn).ReadString('\n') + if err != nil { + return err + } + if line != "OK\n" { + return fmt.Errorf("relay refused route: %s", strings.TrimSpace(line)) + } + return nil +} diff --git a/internal/relay/relay_test.go b/internal/relay/relay_test.go new file mode 100644 index 00000000..3758b5e5 --- /dev/null +++ b/internal/relay/relay_test.go @@ -0,0 +1,30 @@ +package relay + +import ( + "bufio" + "net" + "strings" + "testing" +) + +func TestFirstConnectorConsumesRoute(t *testing.T) { + s := NewServer("separate-gateway-token") + g, relayGateway := net.Pipe() + go s.handle(relayGateway) + if err := Register(g, "route-a", "separate-gateway-token"); err != nil { + t.Fatal(err) + } + c1, relayClient1 := net.Pipe() + go s.handle(relayClient1) + if err := Connect(c1, "route-a"); err != nil { + t.Fatal(err) + } + if line, _ := bufio.NewReader(g).ReadString('\n'); line != "OK\n" { + t.Fatalf("gateway got %q", line) + } + c2, relayClient2 := net.Pipe() + go s.handle(relayClient2) + if err := Connect(c2, "route-a"); err == nil || !strings.Contains(err.Error(), "consumed") { + t.Fatalf("second connector: %v", err) + } +} diff --git a/internal/staging/sessionfixture/authority.go b/internal/staging/sessionfixture/authority.go new file mode 100644 index 00000000..44e9203f --- /dev/null +++ b/internal/staging/sessionfixture/authority.go @@ -0,0 +1,117 @@ +package sessionfixture + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type Grant struct { + Principal string `json:"principal"` + MachineNamespace string `json:"machineNamespace"` + MachineName string `json:"machineName"` + MachineGeneration int64 `json:"machineGeneration"` + CapacityGeneration int64 `json:"capacityGeneration"` + Access controller.ManagementAccess `json:"access"` +} + +type Resolver struct { + Client client.Client + PrivateNamespace string +} + +func grantName(uid types.UID) string { + digest := sha256.Sum256([]byte(uid)) + return "synthetic-session-" + hex.EncodeToString(digest[:16]) +} + +func (r Resolver) ResolveManagementAccess(ctx context.Context, binding sessionv1.MachineManagementSessionBindingSpec) (controller.ManagementAccess, error) { + var secret corev1.Secret + if err := r.Client.Get(ctx, client.ObjectKey{Namespace: r.PrivateNamespace, Name: grantName(binding.MachineUID)}, &secret); err != nil { + return controller.ManagementAccess{}, err + } + var grant Grant + if err := json.Unmarshal(secret.Data["grant.json"], &grant); err != nil { + return controller.ManagementAccess{}, err + } + access := grant.Access + if secret.Immutable == nil || !*secret.Immutable || secret.DeletionTimestamp != nil || grant.Principal == "" || grant.Principal != binding.RequestingPrincipal || grant.MachineNamespace != binding.MachineNamespace || grant.MachineName != binding.MachineName || access.MachineUID != binding.MachineUID || binding.Protocol != "Redfish" || binding.AccessProfile != "Provisioning" { + return controller.ManagementAccess{}, controller.ErrUnsupported + } + var claim fleetv1.Machine + var capacity fleetv1.MachineCapacity + var consumer, provider corev1.Namespace + for _, item := range []struct { + key client.ObjectKey + obj client.Object + }{ + {client.ObjectKey{Namespace: grant.MachineNamespace, Name: grant.MachineName}, &claim}, + {client.ObjectKey{Namespace: access.CapacityNamespace, Name: access.CapacityName}, &capacity}, + {client.ObjectKey{Name: grant.MachineNamespace}, &consumer}, + {client.ObjectKey{Name: access.CapacityNamespace}, &provider}, + } { + if err := r.Client.Get(ctx, item.key, item.obj); err != nil { + return controller.ManagementAccess{}, err + } + if item.obj.GetDeletionTimestamp() != nil { + return controller.ManagementAccess{}, controller.ErrRecordInvalid + } + } + if claim.UID != access.MachineUID || claim.Generation != grant.MachineGeneration || consumer.UID != access.NamespaceUID || provider.UID != access.ProviderProject.UID || capacity.UID != access.CapacityUID || capacity.Generation != grant.CapacityGeneration || capacity.Spec.DeviceRef.Name != access.DeviceName || claim.Spec.LocationRef.Name != access.LocationName || capacity.Spec.AllocationPolicy != "Enabled" { + return controller.ManagementAccess{}, controller.ErrRecordInvalid + } + return access, nil +} + +func NewAuthority(kube client.Client, namespace string) (*controller.LifecycleSessionAuthority, error) { + coordinator, err := controller.NewCoordinator(kube, namespace, unavailableExecutor{}, controller.LocalDigestImageResolver{}, nil, time.Minute) + if err != nil { + return nil, err + } + return &controller.LifecycleSessionAuthority{Coordinator: coordinator, Resolver: Resolver{Client: kube, PrivateNamespace: namespace}}, nil +} + +type unavailableExecutor struct{} + +func (unavailableExecutor) Execute(context.Context, simulator.Request) (simulator.OperationResult, error) { + return simulator.OperationResult{}, executor.ErrOutcomeUnknown +} + +func (unavailableExecutor) Lookup(context.Context, string) (simulator.OperationResult, bool, error) { + return simulator.OperationResult{}, false, executor.ErrOutcomeUnknown +} + +func saveGrant(ctx context.Context, kube client.Client, namespace string, grant Grant) error { + data, err := json.Marshal(grant) + if err != nil { + return err + } + immutable := true + secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: grantName(grant.Access.MachineUID)}, Immutable: &immutable, Data: map[string][]byte{"grant.json": data}} + var existing corev1.Secret + err = kube.Get(ctx, client.ObjectKeyFromObject(secret), &existing) + if client.IgnoreNotFound(err) != nil { + return err + } + if err == nil { + if existing.Immutable == nil || !*existing.Immutable || string(existing.Data["grant.json"]) != string(data) || existing.DeletionTimestamp != nil { + return errors.New("synthetic grant differs from retained immutable inputs") + } + return nil + } + return kube.Create(ctx, secret) +} diff --git a/internal/staging/sessionfixture/executor.go b/internal/staging/sessionfixture/executor.go new file mode 100644 index 00000000..249816c7 --- /dev/null +++ b/internal/staging/sessionfixture/executor.go @@ -0,0 +1,26 @@ +package sessionfixture + +import ( + "context" + "fmt" + + "go.datum.net/fleet/internal/executor" + "go.datum.net/fleet/internal/simulator" +) + +type StoreExecutor struct { + Store *simulator.Store +} + +func (e StoreExecutor) Execute(_ context.Context, request simulator.Request) (simulator.OperationResult, error) { + operation, lost, err := e.Store.Submit(request) + if err != nil || lost { + return simulator.OperationResult{}, fmt.Errorf("%w: synthetic submit: %v (lost=%t)", executor.ErrOutcomeUnknown, err, lost) + } + return operation.ResultView(), nil +} + +func (e StoreExecutor) Lookup(_ context.Context, id string) (simulator.OperationResult, bool, error) { + operation, found := e.Store.Get(id) + return operation.ResultView(), found, nil +} diff --git a/internal/staging/sessionfixture/fixture.go b/internal/staging/sessionfixture/fixture.go new file mode 100644 index 00000000..a209b575 --- /dev/null +++ b/internal/staging/sessionfixture/fixture.go @@ -0,0 +1,99 @@ +package sessionfixture + +import ( + "context" + "errors" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" +) + +type Fixture struct { + Client client.Client + Coordinator *controller.Coordinator + PrivateNamespace string +} + +func (f Fixture) Allocate(ctx context.Context, machineKey, capacityKey client.ObjectKey, principal, member string) (*controller.AssetRecord, error) { + if principal == "" || member == "" { + return nil, errors.New("explicit synthetic principal and member cluster are required") + } + var claim fleetv1.Machine + var capacity fleetv1.MachineCapacity + var consumer, provider corev1.Namespace + for _, item := range []struct { + key client.ObjectKey + obj client.Object + }{{machineKey, &claim}, {capacityKey, &capacity}, {client.ObjectKey{Name: machineKey.Namespace}, &consumer}, {client.ObjectKey{Name: capacityKey.Namespace}, &provider}} { + if err := f.Client.Get(ctx, item.key, item.obj); err != nil { + return nil, err + } + if item.obj.GetUID() == "" || item.obj.GetDeletionTimestamp() != nil { + return nil, controller.ErrRecordInvalid + } + } + if claim.Spec.LocationRef.Name == "" || claim.Spec.MachineClassRef.Name == "" || claim.Spec.MachineProfileRef.Name == "" || claim.Spec.PowerState != "Off" || capacity.Spec.DeviceRef.Name == "" || capacity.Spec.AllocationPolicy != "Enabled" || len(claim.Spec.NetworkInterfaces) != 0 || claim.Spec.InitialInstallationRef != nil { + return nil, errors.New("synthetic fixture requires a location, class, profile, device, enabled capacity and powered-off networkless claim without installation") + } + grant := Grant{Principal: principal, MachineNamespace: claim.Namespace, MachineName: claim.Name, MachineGeneration: claim.Generation, CapacityGeneration: capacity.Generation, Access: controller.ManagementAccess{ + Scope: controller.LocalClaimScope(consumer.UID), NamespaceUID: consumer.UID, MachineUID: claim.UID, + ConsumerProject: controller.ProjectIdentity{AuthorityID: "local", RouteName: consumer.Name, UID: consumer.UID}, + ProviderProject: controller.ProjectIdentity{AuthorityID: "local", RouteName: provider.Name, UID: provider.UID}, + CapacityNamespace: capacity.Namespace, CapacityName: capacity.Name, CapacityUID: capacity.UID, DeviceName: capacity.Spec.DeviceRef.Name, + LocationName: claim.Spec.LocationRef.Name, MemberCluster: member, + }} + if err := saveGrant(ctx, f.Client, f.PrivateNamespace, grant); err != nil { + return nil, err + } + admission := controller.AdmissionAuthority{PrincipalUID: principal, DecisionID: "synthetic-session-fixture"} + if err := f.Coordinator.EnsureClaimCustody(ctx, &claim, consumer.UID, admission); err != nil { + return nil, err + } + if !controllerutil.ContainsFinalizer(&claim, controller.MachineFinalizer) { + controllerutil.AddFinalizer(&claim, controller.MachineFinalizer) + if err := f.Client.Update(ctx, &claim); err != nil { + return nil, err + } + } + capacity.Status.Conditions = nil + for _, condition := range []string{"Prepared", "Healthy", "Available"} { + capacity.Status.Conditions = append(capacity.Status.Conditions, metav1.Condition{Type: condition, Status: metav1.ConditionTrue, ObservedGeneration: capacity.Generation, LastTransitionTime: metav1.Now(), Reason: "SyntheticFixture"}) + } + capacity.Status.Hardware.CPU.Architecture = "amd64" + class := &fleetv1.MachineClass{ObjectMeta: metav1.ObjectMeta{Name: claim.Spec.MachineClassRef.Name, UID: "synthetic-class"}, Spec: fleetv1.MachineClassSpec{Capacity: &fleetv1.CapacityPolicy{MachineCapacities: fleetv1.MachineSelector{Namespace: capacity.Namespace}}}} + profile := &fleetv1.MachineProfile{ObjectMeta: metav1.ObjectMeta{Name: claim.Spec.MachineProfileRef.Name, UID: "synthetic-profile"}, Spec: fleetv1.MachineProfileSpec{CPU: fleetv1.CPURequirement{Architecture: "amd64"}}} + return f.Coordinator.Allocate(ctx, controller.AllocationRequest{Claim: &claim, Class: class, Profile: profile, MachineCapacities: []fleetv1.MachineCapacity{capacity}, NamespaceUID: consumer.UID, Admission: admission, EvidenceObservedAt: map[types.UID]time.Time{capacity.UID: time.Now()}}) +} + +func (f Fixture) Release(ctx context.Context, machineKey client.ObjectKey, uid types.UID) (controller.ReleaseResult, error) { + if uid == "" { + return controller.ReleaseResult{}, errors.New("exact --machine-uid required for release") + } + result, err := f.Coordinator.Release(ctx, uid) + if err != nil { + return result, err + } + if !result.SafeToRemoveFinalizer { + return result, errors.New("release is not verified; retain custody and retry") + } + err = retry.RetryOnConflict(retry.DefaultRetry, func() error { + var claim fleetv1.Machine + if err := f.Client.Get(ctx, machineKey, &claim); err != nil { + return client.IgnoreNotFound(err) + } + if claim.UID != uid || !controllerutil.ContainsFinalizer(&claim, controller.MachineFinalizer) { + return nil + } + controllerutil.RemoveFinalizer(&claim, controller.MachineFinalizer) + return f.Client.Update(ctx, &claim) + }) + return result, err +} diff --git a/internal/staging/sessionfixture/fixture_test.go b/internal/staging/sessionfixture/fixture_test.go new file mode 100644 index 00000000..338837fa --- /dev/null +++ b/internal/staging/sessionfixture/fixture_test.go @@ -0,0 +1,181 @@ +package sessionfixture + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + sessionv1 "go.datum.net/fleet/internal/api/session/v1alpha1" + fleetv1 "go.datum.net/fleet/internal/api/v1alpha1" + "go.datum.net/fleet/internal/controller" + "go.datum.net/fleet/internal/simulator" +) + +func newFixture(t *testing.T) (Fixture, *controller.LifecycleSessionAuthority, *fleetv1.Machine, *fleetv1.MachineCapacity, *simulator.Store) { + t.Helper() + scheme := runtime.NewScheme() + for _, add := range []func(*runtime.Scheme) error{corev1.AddToScheme, fleetv1.AddToScheme, sessionv1.AddToScheme} { + if err := add(scheme); err != nil { + t.Fatal(err) + } + } + claim := &fleetv1.Machine{ObjectMeta: metav1.ObjectMeta{Namespace: "consumer", Name: "db-01", UID: "claim-1", Generation: 1}, Spec: fleetv1.MachineSpec{MachineClassRef: fleetv1.LocalReference{Name: "synthetic"}, MachineProfileRef: fleetv1.LocalReference{Name: "synthetic"}, LocationRef: fleetv1.LocalReference{Name: "location"}, PowerState: "Off"}} + capacity := &fleetv1.MachineCapacity{ObjectMeta: metav1.ObjectMeta{Namespace: "provider", Name: "capacity", UID: "capacity-1", Generation: 1}, Spec: fleetv1.MachineCapacitySpec{DeviceRef: fleetv1.LocalReference{Name: "device"}, AllocationPolicy: "Enabled"}} + kube := fake.NewClientBuilder().WithScheme(scheme).WithStatusSubresource(&sessionv1.MachineManagementSession{}, &sessionv1.MachineManagementSessionBinding{}).WithObjects(claim, capacity, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "consumer", UID: "consumer-1"}}, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "provider", UID: "provider-1"}}).Build() + store, err := simulator.Open(filepath.Join(t.TempDir(), "executor.json")) + if err != nil { + t.Fatal(err) + } + coordinator, err := controller.NewCoordinator(kube, "private", StoreExecutor{Store: store}, controller.LocalDigestImageResolver{}, nil, time.Minute) + if err != nil { + t.Fatal(err) + } + authority, err := NewAuthority(kube, "private") + if err != nil { + t.Fatal(err) + } + return Fixture{Client: kube, Coordinator: coordinator, PrivateNamespace: "private"}, authority, claim, capacity, store +} + +func allocate(t *testing.T, fixture Fixture, claim *fleetv1.Machine, capacity *fleetv1.MachineCapacity) *controller.AssetRecord { + t.Helper() + asset, err := fixture.Allocate(context.Background(), client.ObjectKeyFromObject(claim), client.ObjectKeyFromObject(capacity), "alice", "cell") + if err != nil { + t.Fatal(err) + } + return asset +} + +func proposed(claim *fleetv1.Machine) sessionv1.MachineManagementSessionBindingSpec { + return sessionv1.MachineManagementSessionBindingSpec{MachineNamespace: claim.Namespace, MachineName: claim.Name, MachineUID: claim.UID, RequestingPrincipal: "alice", Protocol: "Redfish", AccessProfile: "Provisioning", SessionNamespace: claim.Namespace, SessionName: "access", SessionUID: "session-1", ClientPublicKey: "key", ConnectBefore: metav1.NewTime(time.Now().Add(time.Minute)), ExpiresAt: metav1.NewTime(time.Now().Add(time.Hour)), SessionCorrelationID: "session-correlation", OperationCorrelationID: "operation-correlation"} +} + +func TestFixtureWiresSessionReconcilerToRealCustody(t *testing.T) { + fixture, authority, claim, capacity, _ := newFixture(t) + asset := allocate(t, fixture, claim, capacity) + session := &sessionv1.MachineManagementSession{ObjectMeta: metav1.ObjectMeta{Name: "access", Namespace: claim.Namespace, UID: "session-1", Annotations: map[string]string{controller.PrincipalAnnotation: "alice"}}, Spec: sessionv1.MachineManagementSessionSpec{MachineRef: sessionv1.LocalReference{Name: claim.Name}, Protocol: "Redfish", AccessProfile: "Provisioning", ClientPublicKey: "key", TTL: metav1.Duration{Duration: time.Minute}}} + ctx := context.Background() + if err := fixture.Client.Create(ctx, session); err != nil { + t.Fatal(err) + } + reconciler := controller.SessionReconciler{Client: fixture.Client, Lifecycle: authority} + if _, err := reconciler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(session)}); err != nil { + t.Fatal(err) + } + var bindings sessionv1.MachineManagementSessionBindingList + if err := fixture.Client.List(ctx, &bindings); err != nil || len(bindings.Items) != 1 { + t.Fatalf("missing binding: %+v %v", bindings, err) + } + binding := &bindings.Items[0] + if binding.Spec.AllocationUID != types.UID(asset.BindingID) || binding.Spec.DeviceName != capacity.Spec.DeviceRef.Name || !authority.Active(ctx, binding) { + t.Fatalf("binding did not retain real custody: %+v", binding.Spec) + } +} + +func TestReleaseBlocksUntilVerifiedTeardownThenReusesNextEpoch(t *testing.T) { + fixture, authority, claim, capacity, store := newFixture(t) + asset := allocate(t, fixture, claim, capacity) + ctx := context.Background() + retained, err := authority.Acquire(ctx, proposed(claim)) + if err != nil { + t.Fatal(err) + } + binding := &sessionv1.MachineManagementSessionBinding{ObjectMeta: metav1.ObjectMeta{Generation: 1}, Spec: retained} + if err := authority.BeginProjection(ctx, binding); err != nil { + t.Fatal(err) + } + for attempt := 0; attempt < 2; attempt++ { + result, err := fixture.Release(ctx, client.ObjectKeyFromObject(claim), claim.UID) + if !errors.Is(err, controller.ErrManagementActive) || result.SafeToRemoveFinalizer || authority.Active(ctx, binding) { + t.Fatalf("release crossed management barrier: %+v %v", result, err) + } + } + if _, found := store.Get("cleanup-" + asset.BindingID); found { + t.Fatal("cleanup executed before verified session teardown") + } + other := claim.DeepCopyObject().(*fleetv1.Machine) + other.Name, other.UID, other.ResourceVersion = "db-02", "claim-2", "" + if err := fixture.Client.Create(ctx, other); err != nil { + t.Fatal(err) + } + if _, err := fixture.Allocate(ctx, client.ObjectKeyFromObject(other), client.ObjectKeyFromObject(capacity), "alice", "cell"); !errors.Is(err, controller.ErrInsufficientCapacity) { + t.Fatalf("reuse before teardown: %v", err) + } + binding.Annotations = map[string]string{controller.RevokedAtAnnotation: "revoked"} + binding.Status.Conditions = []metav1.Condition{{Type: "CleanupConfirmed", Status: metav1.ConditionUnknown, ObservedGeneration: 1}} + if err := authority.Complete(ctx, binding); !errors.Is(err, controller.ErrManagementActive) { + t.Fatalf("unknown teardown cleared custody: %v", err) + } + binding.Status.Conditions[0].Status = metav1.ConditionTrue + if err := authority.Complete(ctx, binding); err != nil { + t.Fatal(err) + } + result, err := fixture.Release(ctx, client.ObjectKeyFromObject(claim), claim.UID) + if err != nil || !result.SafeToRemoveFinalizer { + t.Fatalf("verified release: %+v %v", result, err) + } + next := allocate(t, fixture, other, capacity) + if next.Epoch != asset.Epoch+1 || next.BindingID == asset.BindingID { + t.Fatalf("reuse did not advance allocation: %+v", next) + } +} + +func TestSyntheticGrantCannotAuthorizeMissingCustodyOrChangedLifetimes(t *testing.T) { + for _, change := range []string{"principal", "machine", "capacity", "namespace", "provider", "device", "grant-only"} { + t.Run(change, func(t *testing.T) { + fixture, authority, claim, capacity, _ := newFixture(t) + allocate(t, fixture, claim, capacity) + binding := proposed(claim) + ctx := context.Background() + switch change { + case "principal": + binding.RequestingPrincipal = "mallory" + case "machine", "capacity", "namespace", "provider", "device": + var object client.Object = claim.DeepCopyObject().(*fleetv1.Machine) + if change == "capacity" || change == "device" { + object = capacity.DeepCopyObject().(*fleetv1.MachineCapacity) + } else if change == "namespace" { + object = &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "consumer"}} + } else if change == "provider" { + object = &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "provider"}} + } + if err := fixture.Client.Get(ctx, client.ObjectKeyFromObject(object), object); err != nil { + t.Fatal(err) + } + if change == "device" { + object.(*fleetv1.MachineCapacity).Spec.DeviceRef.Name = "different" + } else { + object.SetUID("replacement") + } + if err := fixture.Client.Update(ctx, object); err != nil { + t.Fatal(err) + } + case "grant-only": + var secrets corev1.SecretList + if err := fixture.Client.List(ctx, &secrets); err != nil { + t.Fatal(err) + } + for _, secret := range secrets.Items { + if secret.Name != grantName(claim.UID) { + if err := fixture.Client.Delete(ctx, &secret); err != nil { + t.Fatal(err) + } + } + } + } + if _, err := authority.Acquire(ctx, binding); err == nil { + t.Fatal("changed authority or missing custody was accepted") + } + }) + } +} diff --git a/test/e2e/machine-management/Dockerfile.prebuilt b/test/e2e/machine-management/Dockerfile.prebuilt new file mode 100644 index 00000000..43dc9ac9 --- /dev/null +++ b/test/e2e/machine-management/Dockerfile.prebuilt @@ -0,0 +1,5 @@ +FROM debian:12.12-slim +ARG BINARY +COPY ${BINARY} /usr/local/bin/app +USER 65532:65532 +ENTRYPOINT ["/usr/local/bin/app"] diff --git a/test/e2e/machine-management/compose.openvpn.yaml b/test/e2e/machine-management/compose.openvpn.yaml new file mode 100644 index 00000000..c425a199 --- /dev/null +++ b/test/e2e/machine-management/compose.openvpn.yaml @@ -0,0 +1,4 @@ +services: + virtual-bmc: + environment: + FLEET_OPENVPN: "1" diff --git a/test/e2e/machine-management/compose.yaml b/test/e2e/machine-management/compose.yaml new file mode 100644 index 00000000..6424391a --- /dev/null +++ b/test/e2e/machine-management/compose.yaml @@ -0,0 +1,21 @@ +services: + virtual-bmc: + platform: linux/amd64 + build: ./virtual-bmc + container_name: fleet-e2e-virtual-bmc + privileged: true + environment: + FLEET_FORCE_QEMU: ${FLEET_FORCE_QEMU:-0} + networks: + management: + ipv4_address: 172.30.0.10 + volumes: + - ${FLEET_E2E_STATE:?set FLEET_E2E_STATE}/evidence:/evidence + - ${FLEET_E2E_STATE:?set FLEET_E2E_STATE}/images:/var/lib/libvirt/images +networks: + management: + name: fleet-management-e2e + internal: true + ipam: + config: + - subnet: 172.30.0.0/24 diff --git a/test/e2e/machine-management/generic-client.py b/test/e2e/machine-management/generic-client.py new file mode 100755 index 00000000..81516b03 --- /dev/null +++ b/test/e2e/machine-management/generic-client.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +"""Exercise Fleet through DMTF's unmodified Python Redfish client.""" + +import json +import os + +import redfish + + +with open(os.environ["FLEET_CREDENTIAL_FILE"], encoding="utf-8") as source: + credential = json.load(source) + +client = redfish.redfish_client( + base_url=credential["endpoint"].removesuffix("/redfish/v1/"), + username=credential["username"], + password=credential["password"], + cafile=os.environ.get("FLEET_CA_BUNDLE", credential["caBundle"]), + default_prefix="/redfish/v1", +) +client.login(auth="session") +root = client.get("/redfish/v1/") +systems = client.get("/redfish/v1/Systems") +system = client.get("/redfish/v1/Systems/allocated") +assert root.status == 200, root.status +assert systems.status == 200 and systems.dict["Members@odata.count"] == 1 +assert system.status == 200 and system.dict["Id"] == "allocated" +assert "Managers" not in root.dict and "AccountService" not in root.dict +client.logout() +print("generic DMTF Redfish client: PASS") diff --git a/test/e2e/machine-management/kind-location.yaml b/test/e2e/machine-management/kind-location.yaml new file mode 100644 index 00000000..1543cccb --- /dev/null +++ b/test/e2e/machine-management/kind-location.yaml @@ -0,0 +1,11 @@ +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +networking: + apiServerAddress: 127.0.0.1 +nodes: + - role: control-plane + extraPortMappings: + - containerPort: 30443 + hostPort: 30443 + listenAddress: 127.0.0.1 + protocol: TCP diff --git a/test/e2e/machine-management/kind-management.yaml b/test/e2e/machine-management/kind-management.yaml new file mode 100644 index 00000000..c5a38ea0 --- /dev/null +++ b/test/e2e/machine-management/kind-management.yaml @@ -0,0 +1,9 @@ +kind: Cluster +apiVersion: kind.x-k8s.io/v1alpha4 +nodes: + - role: control-plane + extraPortMappings: + - containerPort: 32443 + hostPort: 32443 + listenAddress: 127.0.0.1 + protocol: TCP diff --git a/test/e2e/machine-management/openvpn/Dockerfile b/test/e2e/machine-management/openvpn/Dockerfile new file mode 100644 index 00000000..bbdaf95a --- /dev/null +++ b/test/e2e/machine-management/openvpn/Dockerfile @@ -0,0 +1,5 @@ +FROM debian:12.12-slim +RUN apt-get update && apt-get install -y --no-install-recommends curl iptables openvpn && rm -rf /var/lib/apt/lists/* +COPY entrypoint.sh /usr/local/bin/entrypoint +RUN chmod 0755 /usr/local/bin/entrypoint +ENTRYPOINT ["/usr/local/bin/entrypoint"] diff --git a/test/e2e/machine-management/openvpn/client.yaml b/test/e2e/machine-management/openvpn/client.yaml new file mode 100644 index 00000000..42b314ce --- /dev/null +++ b/test/e2e/machine-management/openvpn/client.yaml @@ -0,0 +1,26 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: fleet-openvpn-client + namespace: machine-access-system +spec: + selector: {matchLabels: {app.kubernetes.io/name: fleet-openvpn-client}} + template: + metadata: {labels: {app.kubernetes.io/name: fleet-openvpn-client}} + spec: + hostNetwork: true + automountServiceAccountToken: false + containers: + - name: openvpn + image: fleet-openvpn-client:e2e + imagePullPolicy: IfNotPresent + securityContext: + privileged: true + volumeMounts: + - {name: key, mountPath: /var/run/openvpn, readOnly: true} + - {name: tun, mountPath: /dev/net/tun} + volumes: + - name: key + secret: {secretName: fleet-openvpn-key, defaultMode: 0400} + - name: tun + hostPath: {path: /dev/net/tun, type: CharDevice} diff --git a/test/e2e/machine-management/openvpn/entrypoint.sh b/test/e2e/machine-management/openvpn/entrypoint.sh new file mode 100755 index 00000000..59da712e --- /dev/null +++ b/test/e2e/machine-management/openvpn/entrypoint.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +openvpn --daemon --dev tun --ifconfig 10.88.0.2 10.88.0.1 \ + --secret /var/run/openvpn/openvpn.key --remote 172.30.0.10 1194 --proto udp \ + --cipher AES-256-CBC --auth SHA256 +for _ in $(seq 1 30); do + ip link show tun0 >/dev/null 2>&1 && break + sleep 1 +done +ip link show tun0 >/dev/null +iptables -t nat -A POSTROUTING -d 10.88.0.1/32 -j MASQUERADE +exec sleep infinity diff --git a/test/e2e/machine-management/seed/allocation.yaml b/test/e2e/machine-management/seed/allocation.yaml new file mode 100644 index 00000000..83b8fc2e --- /dev/null +++ b/test/e2e/machine-management/seed/allocation.yaml @@ -0,0 +1,10 @@ +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineCapacity +metadata: + name: allocated-capacity + namespace: fleet-provider +spec: + deviceRef: {name: device-allocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain diff --git a/test/e2e/machine-management/seed/location-management.yaml b/test/e2e/machine-management/seed/location-management.yaml new file mode 100644 index 00000000..1a130ef0 --- /dev/null +++ b/test/e2e/machine-management/seed/location-management.yaml @@ -0,0 +1,51 @@ +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineCapacity +metadata: + name: allocated-capacity + namespace: machine-access-system +spec: + deviceRef: {name: device-allocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain +--- +apiVersion: v1 +kind: Secret +metadata: + name: enrollment-device-allocated + namespace: machine-access-system + labels: + fleet.datumapis.com/device-name: device-allocated +type: Opaque +stringData: + adapter: sushy-libvirt-v1 + endpoint: http://172.30.0.10:8000 + system-id: allocated + username: fleet-gateway + password: synthetic-e2e-only +--- +apiVersion: metal.datumapis.com/v1alpha1 +kind: MachineCapacity +metadata: + name: db02-capacity + namespace: machine-access-system +spec: + deviceRef: {name: device-unallocated} + allocationPolicy: Enabled + cleaningPolicyRef: {name: synthetic-e2e} + reclaimPolicy: Retain +--- +apiVersion: v1 +kind: Secret +metadata: + name: enrollment-device-unallocated + namespace: machine-access-system + labels: + fleet.datumapis.com/device-name: device-unallocated +type: Opaque +stringData: + adapter: sushy-libvirt-v1 + endpoint: http://172.30.0.10:8000 + system-id: unallocated + username: fleet-gateway + password: synthetic-e2e-only diff --git a/test/e2e/machine-management/seed/machine.yaml b/test/e2e/machine-management/seed/machine.yaml new file mode 100644 index 00000000..6658b732 --- /dev/null +++ b/test/e2e/machine-management/seed/machine.yaml @@ -0,0 +1,10 @@ +apiVersion: metal.datumapis.com/v1alpha1 +kind: Machine +metadata: + name: db-01 + namespace: default +spec: + machineClassRef: {name: synthetic-libvirt} + machineProfileRef: {name: synthetic-libvirt} + locationRef: {name: location-e2e} + powerState: "Off" diff --git a/test/e2e/machine-management/seed/test-identities.yaml b/test/e2e/machine-management/seed/test-identities.yaml new file mode 100644 index 00000000..ff0661c1 --- /dev/null +++ b/test/e2e/machine-management/seed/test-identities.yaml @@ -0,0 +1,25 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-authorized, namespace: default} +--- +apiVersion: v1 +kind: ServiceAccount +metadata: {name: fleet-viewer, namespace: default} +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-authorized-claim-view, namespace: default} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machine-viewer} +subjects: [{kind: ServiceAccount, name: fleet-authorized, namespace: default}] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-viewer-claim-view, namespace: default} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machine-viewer} +subjects: [{kind: ServiceAccount, name: fleet-viewer, namespace: default}] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: {name: fleet-authorized-machine-management, namespace: default} +roleRef: {apiGroup: rbac.authorization.k8s.io, kind: ClusterRole, name: fleet-machine-management-session-creator} +subjects: [{kind: ServiceAccount, name: fleet-authorized, namespace: default}] diff --git a/test/e2e/machine-management/tools/Dockerfile b/test/e2e/machine-management/tools/Dockerfile new file mode 100644 index 00000000..9e9a5ff8 --- /dev/null +++ b/test/e2e/machine-management/tools/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.13.9-slim-bookworm + +RUN python -m pip install --no-cache-dir \ + redfish==3.4.2 \ + redfish-service-validator==3.1.8 \ + redfish-interop-validator==3.0.3 + +WORKDIR /work +ENTRYPOINT ["/bin/sh", "-c"] diff --git a/test/e2e/machine-management/virtual-bmc/Dockerfile b/test/e2e/machine-management/virtual-bmc/Dockerfile new file mode 100644 index 00000000..4c0a2aa6 --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/Dockerfile @@ -0,0 +1,15 @@ +FROM ubuntu:24.04@sha256:2198e4c65076e9cb0b3d695219df667c0e3b0072da64ca3c2648aca17dcecaf5 +ENV DEBIAN_FRONTEND=noninteractive +RUN apt-get update && apt-get install -y --no-install-recommends \ + busybox-static cpio curl dnsmasq-base iptables ipxe libvirt-clients \ + libvirt-daemon-system linux-image-virtual nginx openvpn ovmf pxelinux python3 \ + python3-libvirt python3-venv qemu-system-x86 qemu-utils syslinux-common zstd && \ + rm -rf /var/lib/apt/lists/* && \ + python3 -m venv --system-site-packages /opt/sushy && \ + /opt/sushy/bin/pip install --no-cache-dir sushy-tools==2.2.0 +COPY emulator.conf /etc/sushy-emulator.conf +COPY callback.py /usr/local/bin/pxe-callback +COPY entrypoint.sh /usr/local/bin/virtual-bmc-entrypoint +RUN chmod 0755 /usr/local/bin/virtual-bmc-entrypoint /usr/local/bin/pxe-callback +EXPOSE 8000 +ENTRYPOINT ["/usr/local/bin/virtual-bmc-entrypoint"] diff --git a/test/e2e/machine-management/virtual-bmc/callback.py b/test/e2e/machine-management/virtual-bmc/callback.py new file mode 100755 index 00000000..a27c873e --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/callback.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +import datetime +import http.server +import json +import pathlib + +LOG = pathlib.Path('/evidence/pxe-callbacks.jsonl') +BOOT_DIR = pathlib.Path('/var/lib/libvirt/dnsmasq/tftp') + +class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + entry = {'time': datetime.datetime.now(datetime.timezone.utc).isoformat(), + 'path': self.path, 'client': self.client_address[0]} + with LOG.open('a', encoding='utf-8') as out: + out.write(json.dumps(entry) + '\n') + out.flush() + if self.path == '/boot.ipxe': + body = (b'#!ipxe\n' + b'kernel http://192.168.124.1:8080/vmlinuz console=ttyS0 ip=dhcp\n' + b'initrd http://192.168.124.1:8080/initramfs.gz\n' + b'boot\n') + self.send_response(200) + self.send_header('Content-Type', 'text/plain') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if self.path in ('/vmlinuz', '/initramfs.gz'): + body = (BOOT_DIR / self.path.removeprefix('/')).read_bytes() + self.send_response(200) + self.send_header('Content-Type', 'application/octet-stream') + self.send_header('Content-Length', str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if not self.path.startswith('/pxe/'): + self.send_error(404) + return + self.send_response(204) + self.end_headers() + def log_message(self, *_): + pass + +http.server.ThreadingHTTPServer(('192.168.124.1', 8080), Handler).serve_forever() diff --git a/test/e2e/machine-management/virtual-bmc/emulator.conf b/test/e2e/machine-management/virtual-bmc/emulator.conf new file mode 100644 index 00000000..9c5908d3 --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/emulator.conf @@ -0,0 +1,6 @@ +SUSHY_EMULATOR_LISTEN_IP = '0.0.0.0' +SUSHY_EMULATOR_LISTEN_PORT = 8000 +SUSHY_EMULATOR_FEATURE_SET = 'minimum' +SUSHY_EMULATOR_LIBVIRT_URI = 'qemu:///system' +SUSHY_EMULATOR_IGNORE_BOOT_DEVICE = False +SUSHY_EMULATOR_STATE_DIR = '/var/lib/sushy-emulator' diff --git a/test/e2e/machine-management/virtual-bmc/entrypoint.sh b/test/e2e/machine-management/virtual-bmc/entrypoint.sh new file mode 100755 index 00000000..02f064f9 --- /dev/null +++ b/test/e2e/machine-management/virtual-bmc/entrypoint.sh @@ -0,0 +1,157 @@ +#!/usr/bin/env bash +set -euo pipefail + +mkdir -p /run/libvirt /var/lib/libvirt/images /var/lib/sushy-emulator /evidence +# Karmada's controllers increase the number of inotify instances in the shared +# CI Docker kernel. The privileged, disposable BMC appliance raises the common +# Kind test ceiling so libvirt's dnsmasq can still create its required watcher. +current_inotify=$(sysctl -n fs.inotify.max_user_instances) +if (( current_inotify < 1024 )); then + sysctl -w fs.inotify.max_user_instances=1024 >/dev/null +fi +# Docker/Lima exposes cgroup v2 to this privileged test appliance, but nested +# per-domain cgroup creation is not portable across runners. Libvirt still owns +# the QEMU process lifecycle; resource isolation is supplied by the container. +sed -i 's/^#cgroup_controllers = .*/cgroup_controllers = []/' /etc/libvirt/qemu.conf +# The persisted test disks are bind-mounted so diagnostics survive appliance +# recreation. macOS/virtiofs does not permit libvirt's DAC ownership rewrites; +# the appliance is already isolated and privileged, so keep QEMU root-owned and +# disable dynamic ownership inside this test-only container. +sed -i \ + -e 's/^#security_driver = .*/security_driver = "none"/' \ + -e 's/^#user = .*/user = "root"/' \ + -e 's/^#group = .*/group = "root"/' \ + -e 's/^#dynamic_ownership = .*/dynamic_ownership = 0/' \ + /etc/libvirt/qemu.conf +virtlogd >/evidence/virtlogd.log 2>&1 & +libvirtd >/evidence/libvirtd.log 2>&1 & +for _ in $(seq 1 60); do + virsh -c qemu:///system list >/dev/null 2>&1 && break + sleep 1 +done +virsh -c qemu:///system list >/dev/null + +domain_type=qemu +if [[ ${FLEET_FORCE_QEMU:-0} != 1 && -c /dev/kvm && -r /dev/kvm && -w /dev/kvm ]]; then + domain_type=kvm +fi +echo "domain_type=${domain_type}" > /evidence/acceleration.txt + +mkdir -p /var/lib/libvirt/dnsmasq/tftp/pxelinux.cfg /tmp/initramfs/{bin,dev,etc,proc,sys,lib} +cp /usr/lib/PXELINUX/pxelinux.0 /var/lib/libvirt/dnsmasq/tftp/ +cp /usr/lib/syslinux/modules/bios/ldlinux.c32 /var/lib/libvirt/dnsmasq/tftp/ +kernel_path=$(find /boot -maxdepth 1 -name 'vmlinuz-*' -type f | sort | tail -1) +kernel_version=${kernel_path##*/vmlinuz-} +cp "${kernel_path}" /var/lib/libvirt/dnsmasq/tftp/vmlinuz +e1000_module=$(modinfo -k "${kernel_version}" -F filename e1000) +case "${e1000_module}" in + *.zst) zstd -q -d -c "${e1000_module}" > /tmp/initramfs/lib/e1000.ko ;; + *.ko) cp "${e1000_module}" /tmp/initramfs/lib/e1000.ko ;; + *) echo "unsupported e1000 module format: ${e1000_module}" >&2; exit 1 ;; +esac +cp /bin/busybox /tmp/initramfs/bin/busybox +for app in sh mount ip udhcpc wget poweroff sleep insmod; do ln -sf busybox "/tmp/initramfs/bin/${app}"; done +cat >/tmp/initramfs/bin/udhcpc-script <<'DHCP' +#!/bin/sh +case "$1" in + bound|renew) + ip addr flush dev "$interface" + ip addr add "$ip/24" dev "$interface" + ip link set "$interface" up + ;; +esac +DHCP +chmod +x /tmp/initramfs/bin/udhcpc-script +cat >/tmp/initramfs/init <<'INIT' +#!/bin/sh +mount -t proc proc /proc +mount -t sysfs sysfs /sys +mount -t devtmpfs devtmpfs /dev +insmod /lib/e1000.ko +ip link set eth0 up +udhcpc -i eth0 -q -n -s /bin/udhcpc-script +mac=$(cat /sys/class/net/eth0/address | tr ':' '-') +wget -q -O /dev/null "http://192.168.124.1:8080/pxe/${mac}" +sleep 2 +poweroff -f +INIT +chmod +x /tmp/initramfs/init +(cd /tmp/initramfs && find . -print0 | cpio --null -o --format=newc | gzip -9) >/var/lib/libvirt/dnsmasq/tftp/initramfs.gz +cat >/var/lib/libvirt/dnsmasq/tftp/pxelinux.cfg/default <<'PXE' +DEFAULT fleet +PROMPT 0 +TIMEOUT 1 +LABEL fleet + KERNEL vmlinuz + INITRD initramfs.gz + APPEND console=ttyS0 ip=dhcp +PXE + +cat >/tmp/provisioning.xml <<'XML' + + fleet-provisioning + + + + + + + + + + +XML +virsh net-define /tmp/provisioning.xml >/dev/null 2>&1 || true +if [[ $(virsh net-info fleet-provisioning | awk '/Active:/ {print $2}') != yes ]]; then + virsh net-start fleet-provisioning >/dev/null +fi +for _ in $(seq 1 30); do + ip addr show virbr-pxe 2>/dev/null | grep -q '192.168.124.1' && break + sleep 1 +done +ip addr show virbr-pxe | grep -q '192.168.124.1' + +define_domain() { + local name=$1 mac=$2 + if [[ ! -f "/var/lib/libvirt/images/${name}.qcow2" ]]; then + qemu-img create -f qcow2 "/var/lib/libvirt/images/${name}.qcow2" 128M >/dev/null + fi + cat >"/tmp/${name}.xml" < + ${name} + 256 + 1 + hvm + + + + + + + + +XML + virsh define "/tmp/${name}.xml" >/dev/null +} + +define_domain allocated 52:54:00:aa:00:01 +define_domain unallocated 52:54:00:aa:00:02 + +/usr/local/bin/pxe-callback & +# The optional qualification profile moves gateway traffic onto a real tun +# interface. The default profile admits only the attached location Kind node. +if [[ ${FLEET_OPENVPN:-0} == 1 ]]; then + if [[ ! -f /evidence/openvpn.key ]]; then + openvpn --genkey secret /evidence/openvpn.key + chmod 0600 /evidence/openvpn.key + fi + openvpn --daemon --dev tun --ifconfig 10.88.0.1 10.88.0.2 \ + --secret /evidence/openvpn.key --proto udp --local 172.30.0.10 --port 1194 \ + --cipher AES-256-CBC --auth SHA256 + iptables -I INPUT -p tcp --dport 8000 -s 10.88.0.2 -j ACCEPT +else + iptables -I INPUT -p tcp --dport 8000 -s 172.30.0.20 -j ACCEPT +fi +iptables -A INPUT -p tcp --dport 8000 -j DROP + +exec /opt/sushy/bin/sushy-emulator --config /etc/sushy-emulator.conf