From 8d2f0a258923f4f0ce361a7b294147dd46e22227 Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:15:49 -0600 Subject: [PATCH 1/3] fix(bmc-discovery): Drop get from the credential Role Discovery reads credential Secrets only through its label-selected cache and the --once list, so the Role's get verb was never used. Drop it and pin the Role with a manifest test and an envtest that runs the real Secret cache and --once list under the shipped Role, and checks that a get by name and another namespace are refused. Co-Authored-By: Claude Opus 5.5 --- config/base/bmc-discovery/rbac.yaml | 9 +- internal/bmcdiscovery/manifest_test.go | 29 +++++ internal/bmcdiscovery/rbac_envtest_test.go | 127 +++++++++++++++++++++ internal/bmcdiscovery/runtime.go | 18 ++- 4 files changed, 173 insertions(+), 10 deletions(-) create mode 100644 internal/bmcdiscovery/rbac_envtest_test.go diff --git a/config/base/bmc-discovery/rbac.yaml b/config/base/bmc-discovery/rbac.yaml index ca8fed6b..5c831bc3 100644 --- a/config/base/bmc-discovery/rbac.yaml +++ b/config/base/bmc-discovery/rbac.yaml @@ -3,9 +3,10 @@ kind: ServiceAccount metadata: name: fleet-bmc-discovery --- -# Reads credential Secrets in its own namespace only. Kubernetes RBAC cannot -# narrow this to the labelled Secrets, so keep discovery in a namespace that -# holds nothing else it should not read. +# Lists and watches credential Secrets in its own namespace; discovery never +# gets one by name. Kubernetes RBAC cannot narrow this to the labelled +# Secrets, so keep discovery in a namespace that holds credential Secrets +# only. hack/validate-bmc-credential-namespace.sh checks every render here. apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: @@ -13,7 +14,7 @@ metadata: rules: - apiGroups: [""] resources: [secrets] - verbs: [get, list, watch] + verbs: [list, watch] --- apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding diff --git a/internal/bmcdiscovery/manifest_test.go b/internal/bmcdiscovery/manifest_test.go index 8ceba6ba..b88b1daf 100644 --- a/internal/bmcdiscovery/manifest_test.go +++ b/internal/bmcdiscovery/manifest_test.go @@ -3,9 +3,12 @@ package bmcdiscovery import ( "os" "path/filepath" + "reflect" + "strings" "testing" appsv1 "k8s.io/api/apps/v1" + rbacv1 "k8s.io/api/rbac/v1" "sigs.k8s.io/yaml" ) @@ -47,3 +50,29 @@ func TestDeploymentIsSingleUnprivilegedReplica(t *testing.T) { t.Fatalf("container security context = %+v", sc) } } + +// Discovery reads Secrets only through its label-selected cache and --once's +// list, so its Role grants list and watch on Secrets and nothing else. +func TestCredentialRoleListsAndWatchesSecretsOnly(t *testing.T) { + data, err := os.ReadFile(filepath.Join(baseDir, "rbac.yaml")) + if err != nil { + t.Fatal(err) + } + var role *rbacv1.Role + for _, doc := range strings.Split(string(data), "\n---\n") { + var r rbacv1.Role + if err := yaml.Unmarshal([]byte(doc), &r); err != nil { + t.Fatal(err) + } + if r.Kind == "Role" && r.Name == "fleet-bmc-discovery-credentials" { + role = &r + } + } + if role == nil { + t.Fatal("rbac.yaml has no fleet-bmc-discovery-credentials Role") + } + want := []rbacv1.PolicyRule{{APIGroups: []string{""}, Resources: []string{"secrets"}, Verbs: []string{"list", "watch"}}} + if !reflect.DeepEqual(role.Rules, want) { + t.Fatalf("credential Role rules = %+v, want %+v", role.Rules, want) + } +} diff --git a/internal/bmcdiscovery/rbac_envtest_test.go b/internal/bmcdiscovery/rbac_envtest_test.go new file mode 100644 index 00000000..9c85100c --- /dev/null +++ b/internal/bmcdiscovery/rbac_envtest_test.go @@ -0,0 +1,127 @@ +package bmcdiscovery + +import ( + "bytes" + "context" + "errors" + "io" + "os" + "path/filepath" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/envtest" +) + +// The shipped credential Role is enough for discovery's Secret cache and for +// --once, and grants no get by name. A Secret that is not a credential is +// still returned by an unselected list, which is why the render check keeps +// other Secrets out of discovery's namespace. +func TestShippedRoleServesTheCredentialCacheAndRefusesGet(t *testing.T) { + if os.Getenv("KUBEBUILDER_ASSETS") == "" { + t.Skip("KUBEBUILDER_ASSETS required") + } + environment := &envtest.Environment{} + admin, err := environment.Start() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := environment.Stop(); err != nil { + t.Error(err) + } + }) + scheme, err := NewScheme() + if err != nil { + t.Fatal(err) + } + if err := rbacv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + adminClient, err := client.New(admin, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + create := func(object client.Object) { + t.Helper() + if err := adminClient.Create(ctx, object); err != nil { + t.Fatal(err) + } + } + create(&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: credNS}}) + data, err := os.ReadFile(filepath.Join(baseDir, "rbac.yaml")) + if err != nil { + t.Fatal(err) + } + decoder := utilyaml.NewYAMLOrJSONDecoder(bytes.NewReader(data), 4096) + for { + var object unstructured.Unstructured + if err := decoder.Decode(&object.Object); errors.Is(err, io.EOF) { + break + } else if err != nil { + t.Fatal(err) + } + object.SetNamespace(credNS) + create(&object) + } + credential := secret("device-a", "") + credential.UID, credential.ResourceVersion = "", "" + create(credential) + create(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "unrelated", Namespace: credNS}, Data: map[string][]byte{"token": []byte("synthetic")}}) + + discovery := rest.CopyConfig(admin) + discovery.Impersonate = rest.ImpersonationConfig{UserName: "system:serviceaccount:" + credNS + ":fleet-bmc-discovery", + Groups: []string{"system:serviceaccounts", "system:serviceaccounts:" + credNS, "system:authenticated"}} + c := Config{CredentialNamespace: credNS} + secrets, err := credentialCluster(c, discovery, scheme) + if err != nil { + t.Fatal(err) + } + go func() { _ = secrets.Start(ctx) }() + if !secrets.GetCache().WaitForCacheSync(ctx) { + t.Fatal("credential Secret cache did not sync under the shipped Role") + } + var cached corev1.SecretList + if err := secrets.GetCache().List(ctx, &cached, client.InNamespace(credNS), client.MatchingLabels{CredentialLabel: "true"}); err != nil { + t.Fatal(err) + } + if len(cached.Items) != 1 || cached.Items[0].Name != credential.Name { + t.Fatalf("cached credential Secrets = %v, want only %s", cached.Items, credential.Name) + } + + direct, err := client.New(discovery, client.Options{Scheme: scheme}) + if err != nil { + t.Fatal(err) + } + // --once lists the labelled Secrets directly. + var listed corev1.SecretList + if err := direct.List(ctx, &listed, client.InNamespace(credNS), client.MatchingLabels{CredentialLabel: "true"}); err != nil { + t.Fatalf("--once list under the shipped Role: %v", err) + } + if len(listed.Items) != 1 { + t.Fatalf("listed credential Secrets = %d, want 1", len(listed.Items)) + } + if err := direct.Get(ctx, client.ObjectKey{Namespace: credNS, Name: credential.Name}, &corev1.Secret{}); !apierrors.IsForbidden(err) { + t.Fatalf("get credential Secret by name = %v, want Forbidden", err) + } + var everything corev1.SecretList + if err := direct.List(ctx, &everything, client.InNamespace(credNS)); err != nil { + t.Fatal(err) + } + if len(everything.Items) != 2 { + t.Fatalf("unselected list = %d Secrets; RBAC was expected to return every Secret in the namespace", len(everything.Items)) + } + if err := direct.List(ctx, &corev1.SecretList{}, client.InNamespace("default")); !apierrors.IsForbidden(err) { + t.Fatalf("list Secrets in another namespace = %v, want Forbidden", err) + } +} diff --git a/internal/bmcdiscovery/runtime.go b/internal/bmcdiscovery/runtime.go index 71366e6c..c390c606 100644 --- a/internal/bmcdiscovery/runtime.go +++ b/internal/bmcdiscovery/runtime.go @@ -65,12 +65,7 @@ func NewManager(c Config, milo, local *rest.Config, scheme *runtime.Scheme, bmc if err != nil { return nil, fmt.Errorf("build Milo project manager: %w", err) } - selector := labels.SelectorFromSet(labels.Set{CredentialLabel: "true"}) - secrets, err := cluster.New(local, func(o *cluster.Options) { - o.Scheme = scheme - o.Cache = cache.Options{DefaultNamespaces: map[string]cache.Config{c.CredentialNamespace: {}}, - ByObject: map[client.Object]cache.ByObject{&corev1.Secret{}: {Label: selector}}, DefaultTransform: cache.TransformStripManagedFields()} - }) + secrets, err := credentialCluster(c, local, scheme) if err != nil { return nil, fmt.Errorf("build credential Secret cache: %w", err) } @@ -153,6 +148,17 @@ func NewManager(c Config, milo, local *rest.Config, scheme *runtime.Scheme, bmc return mgr, nil } +// credentialCluster reads only labelled Secrets in the credential namespace, +// by list and watch; the Role in config/base/bmc-discovery grants no more. +func credentialCluster(c Config, local *rest.Config, scheme *runtime.Scheme) (cluster.Cluster, error) { + selector := labels.SelectorFromSet(labels.Set{CredentialLabel: "true"}) + return cluster.New(local, func(o *cluster.Options) { + o.Scheme = scheme + o.Cache = cache.Options{DefaultNamespaces: map[string]cache.Config{c.CredentialNamespace: {}}, + ByObject: map[client.Object]cache.ByObject{&corev1.Secret{}: {Label: selector}}, DefaultTransform: cache.TransformStripManagedFields()} + }) +} + // OnceResult is what --once would write for one Device. type OnceResult struct { Namespace string `json:"namespace"` From e38e3ae30825799e88c6f42b50f974d14d6b6a6f Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:15:49 -0600 Subject: [PATCH 2/3] ci: Keep non-credential Secrets out of BMC namespaces RBAC cannot narrow discovery's Secret Role to the labelled credential Secrets, so any Secret in its namespace is readable by discovery. Render every Kustomize entry point under config/ and fail when a Secret without the credential label and Device annotations lands in a namespace that holds discovery, a credential Secret, or the new credential-namespace label, which the site's Redfish credential namespace now carries. A namespace found in any root is checked in every root, and discovery's own Milo kubeconfig is admitted only beside discovery. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 + config/site/redfish/base/credentials.yaml | 4 + hack/bmc-credential-namespace-validator.go | 221 +++++++++++++++++++++ hack/test-bmc-credential-namespace.sh | 221 +++++++++++++++++++++ hack/validate-bmc-credential-namespace.sh | 10 + 5 files changed, 458 insertions(+) create mode 100644 hack/bmc-credential-namespace-validator.go create mode 100755 hack/test-bmc-credential-namespace.sh create mode 100755 hack/validate-bmc-credential-namespace.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 779f4dfa..1fa1794c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,8 @@ jobs: - run: ./hack/validate-synthetic-staging-render.sh - run: ./hack/validate-overlay-isolation.sh - run: ./hack/test-overlay-isolation.sh + - run: ./hack/validate-bmc-credential-namespace.sh + - run: ./hack/test-bmc-credential-namespace.sh - run: ./hack/validate-standalone-render.sh - run: ./hack/test-standalone-source-id.sh - run: ./hack/test-standalone-preflight.sh diff --git a/config/site/redfish/base/credentials.yaml b/config/site/redfish/base/credentials.yaml index e8b69bd8..e3790f76 100644 --- a/config/site/redfish/base/credentials.yaml +++ b/config/site/redfish/base/credentials.yaml @@ -7,6 +7,10 @@ apiVersion: v1 kind: Namespace metadata: name: fleet-site-credentials + labels: + # Holds only credential Secrets; hack/validate-bmc-credential-namespace.sh + # fails a render that adds any other Secret here. + fleet.datumapis.com/bmc-credential-namespace: "true" annotations: # Deleting the namespace deletes the enrolled credentials. Never prune it. kustomize.toolkit.fluxcd.io/prune: disabled diff --git a/hack/bmc-credential-namespace-validator.go b/hack/bmc-credential-namespace-validator.go new file mode 100644 index 00000000..1af790bf --- /dev/null +++ b/hack/bmc-credential-namespace-validator.go @@ -0,0 +1,221 @@ +//go:build ignore + +// Renders every Kustomize entry point below a config root and fails when a +// Secret that is not a BMC credential Secret lands in a BMC credential +// namespace. Kubernetes RBAC cannot narrow BMC discovery's Secret Role to the +// labelled credential Secrets, so discovery reads every Secret in its +// namespace; this check keeps that namespace holding credentials only. +package main + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + utilyaml "k8s.io/apimachinery/pkg/util/yaml" + "sigs.k8s.io/yaml" +) + +const ( + // Discovery's ServiceAccount and Secret Role, from config/base/bmc-discovery. + discoveryAccount = "fleet-bmc-discovery" + discoveryRole = "fleet-bmc-discovery-credentials" + // discoveryKubeconfig is the Milo kubeconfig Secret discovery mounts. + discoveryKubeconfig = "fleet-bmc-discovery-milo-kubeconfig" + // namespaceLabel marks a Namespace that holds BMC credential Secrets + // under discovery's contract but does not run discovery itself. + namespaceLabel = "fleet.datumapis.com/bmc-credential-namespace" + + // The credential Secret contract in internal/bmcdiscovery. + credentialLabel = "fleet.datumapis.com/bmc-credential" + projectAnnotation = "fleet.datumapis.com/device-project" + namespaceAnnotation = "fleet.datumapis.com/device-namespace" + nameAnnotation = "fleet.datumapis.com/device-name" +) + +func main() { + if len(os.Args) != 2 { + fatalf("usage: %s CONFIG_ROOT", os.Args[0]) + } + root, err := filepath.Abs(os.Args[1]) + check(err) + entries, err := discover(root) + check(err) + if len(entries) == 0 { + fatalf("no Kustomize entry points found below %s", root) + } + // A namespace marked in one root is a credential namespace in every root, + // since Flux may apply the Namespace and the objects in it from different + // Kustomizations. The unset namespace is the deploying repository's only + // within a render that leaves discovery's namespace unset. + type render struct { + relative string + objects []*unstructured.Unstructured + local namespaces + } + var renders []render + global := namespaces{credential: map[string]bool{}, discovery: map[string]bool{}} + var covered []string + for _, entry := range entries { + dir := filepath.Dir(entry) + relative, err := filepath.Rel(root, dir) + check(err) + objects, err := build(dir) + if err != nil { + fatalf("build %s: %v", relative, err) + } + local := credentialNamespaces(objects) + if len(local.credential) != 0 { + covered = append(covered, filepath.ToSlash(relative)) + } + for namespace := range local.credential { + if namespace != "" { + global.credential[namespace] = true + } + } + for namespace := range local.discovery { + if namespace != "" { + global.discovery[namespace] = true + } + } + renders = append(renders, render{relative: relative, objects: objects, local: local}) + } + var failures []string + for _, r := range renders { + for _, object := range r.objects { + namespace := object.GetNamespace() + if !isCoreKind(object, "Secret") || !(global.credential[namespace] || namespace == "" && r.local.credential[""]) { + continue + } + // Discovery mounts its own Milo kubeconfig, so the Role exposes + // nothing new by letting it read that Secret beside discovery. + if object.GetName() == discoveryKubeconfig && (global.discovery[namespace] || namespace == "" && r.local.discovery[""]) { + continue + } + if reason := notCredential(object); reason != "" { + failures = append(failures, fmt.Sprintf("%s: Secret %q in BMC credential namespace %s %s", filepath.ToSlash(r.relative), object.GetName(), describe(namespace), reason)) + } + } + } + if len(failures) != 0 { + sort.Strings(failures) + for _, failure := range failures { + fmt.Fprintln(os.Stderr, failure) + } + os.Exit(1) + } + if len(covered) == 0 { + fatalf("no Kustomize entry point below %s renders a BMC credential namespace", root) + } + fmt.Printf("%d of %d Kustomize entry points render a BMC credential namespace, each holding only credential Secrets: %s\n", len(covered), len(entries), strings.Join(covered, ", ")) +} + +// namespaces are the credential namespaces of a render, and those of them +// that run discovery. +type namespaces struct { + credential, discovery map[string]bool +} + +// credentialNamespaces is every namespace in one render that discovery reads +// Secrets from, or that is marked as holding credential Secrets. The empty +// namespace is the deploying repository's namespace for a render that leaves +// discovery's namespace unset. +func credentialNamespaces(objects []*unstructured.Unstructured) namespaces { + found := namespaces{credential: map[string]bool{}, discovery: map[string]bool{}} + for _, object := range objects { + switch { + case isCoreKind(object, "ServiceAccount") && object.GetName() == discoveryAccount, + object.GetAPIVersion() == "rbac.authorization.k8s.io/v1" && object.GetKind() == "Role" && object.GetName() == discoveryRole: + found.credential[object.GetNamespace()] = true + found.discovery[object.GetNamespace()] = true + case isCoreKind(object, "Secret") && object.GetLabels()[credentialLabel] == "true": + found.credential[object.GetNamespace()] = true + case isCoreKind(object, "Namespace") && object.GetLabels()[namespaceLabel] == "true": + found.credential[object.GetName()] = true + } + } + return found +} + +// notCredential says why a Secret does not meet the credential contract, or +// returns "" when it does. +func notCredential(secret *unstructured.Unstructured) string { + if secret.GetLabels()[credentialLabel] != "true" { + return fmt.Sprintf("is not a credential Secret: it lacks label %s: \"true\"", credentialLabel) + } + for _, annotation := range []string{projectAnnotation, namespaceAnnotation, nameAnnotation} { + if secret.GetAnnotations()[annotation] == "" { + return fmt.Sprintf("names no Device: it lacks annotation %s", annotation) + } + } + return "" +} + +func describe(namespace string) string { + if namespace == "" { + return "(set by the deploying repository)" + } + return namespace +} + +func isCoreKind(object *unstructured.Unstructured, kind string) bool { + return object.GetAPIVersion() == "v1" && object.GetKind() == kind +} + +func build(root string) ([]*unstructured.Unstructured, error) { + output, err := exec.Command("kustomize", "build", root).CombinedOutput() + if err != nil { + return nil, fmt.Errorf("kustomize build: %w: %s", err, bytes.TrimSpace(output)) + } + reader := utilyaml.NewYAMLReader(bufio.NewReader(bytes.NewReader(output))) + var objects []*unstructured.Unstructured + for { + doc, err := reader.Read() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + return nil, err + } + if len(bytes.TrimSpace(doc)) == 0 { + continue + } + var object map[string]any + if err := yaml.Unmarshal(doc, &object); err != nil { + return nil, err + } + objects = append(objects, &unstructured.Unstructured{Object: object}) + } + return objects, nil +} + +func discover(root string) ([]string, error) { + var entries []string + err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { + if err != nil { + return err + } + if name := entry.Name(); !entry.IsDir() && (name == "kustomization.yaml" || name == "kustomization.yml" || name == "Kustomization") { + entries = append(entries, path) + } + return nil + }) + sort.Strings(entries) + return entries, err +} + +func check(err error) { + if err != nil { + fatalf("%v", err) + } +} + +func fatalf(format string, args ...any) { fmt.Fprintf(os.Stderr, format+"\n", args...); os.Exit(1) } diff --git a/hack/test-bmc-credential-namespace.sh b/hack/test-bmc-credential-namespace.sh new file mode 100755 index 00000000..052a3e3b --- /dev/null +++ b/hack/test-bmc-credential-namespace.sh @@ -0,0 +1,221 @@ +#!/bin/sh +# Proves hack/validate-bmc-credential-namespace.sh passes the real config tree +# and fails when a Secret that is not a BMC credential Secret renders into a +# BMC credential namespace. +set -eu + +repo_root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd -P) +work_root=$(mktemp -d) +fixture_root="$work_root/path with spaces" +trap 'rm -rf "$work_root"' EXIT + +validate() { + "$repo_root/hack/validate-bmc-credential-namespace.sh" "$1" >"$work_root/output" 2>&1 +} + +expect_pass() { + if ! validate "$2"; then + echo "$1 was rejected:" >&2 + cat "$work_root/output" >&2 + exit 1 + fi +} + +expect_failure() { + description=$1 + expected=$2 + if validate "$3"; then + echo "$description was not rejected" >&2 + exit 1 + fi + if ! grep -F "$expected" "$work_root/output" >/dev/null; then + echo "$description failed for the wrong reason:" >&2 + cat "$work_root/output" >&2 + exit 1 + fi +} + +stray_secret() { + cat </dev/null +grep -F "site/redfish/base" "$work_root/output" >/dev/null + +# A stray Secret in discovery's base lands in whatever namespace the +# deploying repository chooses for discovery. +discovery="$real/config/base/bmc-discovery" +cp "$discovery/kustomization.yaml" "$work_root/discovery-kustomization" +stray_secret synthetic-stray >"$discovery/stray-secret.yaml" +awk '{ print } /^ - deployment.yaml$/ { print " - stray-secret.yaml" }' "$work_root/discovery-kustomization" >"$discovery/kustomization.yaml" +if cmp -s "$work_root/discovery-kustomization" "$discovery/kustomization.yaml"; then + echo "discovery stray Secret fixture did not change the Kustomization" >&2 + exit 1 +fi +expect_failure "stray Secret in the discovery base" 'base/bmc-discovery: Secret "synthetic-stray" in BMC credential namespace (set by the deploying repository) is not a credential Secret' "$real/config" +mv "$work_root/discovery-kustomization" "$discovery/kustomization.yaml" +rm "$discovery/stray-secret.yaml" + +# A generated Secret is checked after generation, under its hashed name. +cp "$discovery/kustomization.yaml" "$work_root/discovery-kustomization" +cat >>"$discovery/kustomization.yaml" <<'EOF' +secretGenerator: + - name: synthetic-generated + literals: [token=synthetic-not-a-credential] +EOF +expect_failure "generated Secret in the discovery base" 'Secret "synthetic-generated-' "$real/config" +mv "$work_root/discovery-kustomization" "$discovery/kustomization.yaml" + +# A stray Secret in the site's credential namespace. +site="$real/config/site/redfish/base" +cp "$site/credentials.yaml" "$work_root/site-credentials" +{ echo '---'; stray_secret synthetic-site-stray fleet-site-credentials; } >>"$site/credentials.yaml" +expect_failure "stray Secret in the site credential namespace" 'site/redfish/base: Secret "synthetic-site-stray" in BMC credential namespace fleet-site-credentials is not a credential Secret' "$real/config" +mv "$work_root/site-credentials" "$site/credentials.yaml" +expect_pass "the restored config tree" "$real/config" + +# A Secret added to the site credential namespace from another root, or from +# a Component rendered on its own, is still in that namespace once applied. +mkdir -p "$real/config/multiplane/stray" "$real/config/components/stray" +stray_secret synthetic-cross-root fleet-site-credentials >"$real/config/multiplane/stray/secret.yaml" +cat >"$real/config/multiplane/stray/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [secret.yaml] +EOF +expect_failure "stray Secret added to the site credential namespace from another root" 'multiplane/stray: Secret "synthetic-cross-root" in BMC credential namespace fleet-site-credentials' "$real/config" +rm -rf "$real/config/multiplane/stray" +stray_secret synthetic-component fleet-site-credentials >"$real/config/components/stray/secret.yaml" +cat >"$real/config/components/stray/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component +resources: [secret.yaml] +EOF +expect_failure "stray Secret added to the site credential namespace by a Component" 'components/stray: Secret "synthetic-component" in BMC credential namespace fleet-site-credentials' "$real/config" +rm -rf "$real/config/components/stray" +expect_pass "the restored config tree" "$real/config" + +# Synthetic roots: a namespaced discovery overlay, a labelled namespace and +# the credential contract itself. +synthetic="$fixture_root/synthetic/config" +mkdir -p "$synthetic/base/bmc-discovery" "$synthetic/overlays/discovery" +cp "$repo_root/config/base/bmc-discovery/rbac.yaml" "$synthetic/base/bmc-discovery/" +cat >"$synthetic/base/bmc-discovery/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [rbac.yaml] +EOF +cat >"$synthetic/overlays/discovery/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +namespace: synthetic-bmc-credentials +resources: [../../base/bmc-discovery, credential.yaml] +EOF +credential_secret synthetic-credential >"$synthetic/overlays/discovery/credential.yaml" +expect_pass "a namespaced discovery overlay with a credential Secret" "$synthetic" + +stray_secret synthetic-overlay-stray >"$synthetic/overlays/discovery/stray.yaml" +sed -i.bak 's/credential.yaml\]/credential.yaml, stray.yaml]/' "$synthetic/overlays/discovery/kustomization.yaml" +expect_failure "stray Secret in a namespaced discovery overlay" 'overlays/discovery: Secret "synthetic-overlay-stray" in BMC credential namespace synthetic-bmc-credentials is not a credential Secret' "$synthetic" +mv "$synthetic/overlays/discovery/kustomization.yaml.bak" "$synthetic/overlays/discovery/kustomization.yaml" +rm "$synthetic/overlays/discovery/stray.yaml" + +# Discovery's own Milo kubeconfig may sit beside discovery, and nowhere else. +stray_secret fleet-bmc-discovery-milo-kubeconfig >"$synthetic/overlays/discovery/kubeconfig.yaml" +sed -i.bak 's/credential.yaml\]/credential.yaml, kubeconfig.yaml]/' "$synthetic/overlays/discovery/kustomization.yaml" +expect_pass "discovery's Milo kubeconfig beside discovery" "$synthetic" +mv "$synthetic/overlays/discovery/kustomization.yaml.bak" "$synthetic/overlays/discovery/kustomization.yaml" +rm "$synthetic/overlays/discovery/kubeconfig.yaml" + +# A Secret elsewhere in the same render is not discovery's concern. +mkdir -p "$synthetic/overlays/elsewhere" +stray_secret synthetic-elsewhere synthetic-other >"$synthetic/overlays/elsewhere/stray.yaml" +cat >"$synthetic/overlays/elsewhere/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [../discovery, stray.yaml] +EOF +expect_pass "a Secret outside the credential namespace" "$synthetic" +rm -rf "$synthetic/overlays/elsewhere" + +# A credential Secret must name its Device. +credential_secret synthetic-unnamed | grep -v 'device-name:' >"$synthetic/overlays/discovery/credential.yaml" +expect_failure "credential Secret naming no Device" 'lacks annotation fleet.datumapis.com/device-name' "$synthetic" +credential_secret synthetic-credential | sed 's/bmc-credential: "true"/bmc-credential: "false"/' >"$synthetic/overlays/discovery/credential.yaml" +expect_failure "credential label set to false" 'lacks label fleet.datumapis.com/bmc-credential: "true"' "$synthetic" +credential_secret synthetic-credential >"$synthetic/overlays/discovery/credential.yaml" + +# A labelled Namespace is a credential namespace without discovery in it. +mkdir -p "$synthetic/overlays/labelled" +cat >"$synthetic/overlays/labelled/resources.yaml" <<'EOF' +apiVersion: v1 +kind: Namespace +metadata: + name: synthetic-site-credentials + labels: {fleet.datumapis.com/bmc-credential-namespace: "true"} +--- +apiVersion: v1 +kind: Secret +metadata: {name: synthetic-labelled-stray, namespace: synthetic-site-credentials} +stringData: {token: synthetic-not-a-credential} +EOF +cat >"$synthetic/overlays/labelled/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [resources.yaml] +EOF +expect_failure "stray Secret in a labelled namespace" 'overlays/labelled: Secret "synthetic-labelled-stray" in BMC credential namespace synthetic-site-credentials' "$synthetic" +cat >"$synthetic/overlays/labelled/resources.yaml" <<'EOF' +apiVersion: v1 +kind: Namespace +metadata: + name: synthetic-site-credentials + labels: {fleet.datumapis.com/bmc-credential-namespace: "true"} +--- +apiVersion: v1 +kind: Secret +metadata: {name: fleet-bmc-discovery-milo-kubeconfig, namespace: synthetic-site-credentials} +stringData: {kubeconfig: synthetic} +EOF +expect_failure "discovery's kubeconfig name in a namespace without discovery" 'Secret "fleet-bmc-discovery-milo-kubeconfig" in BMC credential namespace synthetic-site-credentials' "$synthetic" +rm -rf "$synthetic/overlays/labelled" + +# A tree with no credential namespace checked nothing, and says so. +rm -rf "$synthetic/base/bmc-discovery" "$synthetic/overlays/discovery" +mkdir -p "$synthetic/overlays/empty" +cat >"$synthetic/overlays/empty/kustomization.yaml" <<'EOF' +apiVersion: kustomize.config.k8s.io/v1beta1 +kind: Kustomization +resources: [] +EOF +expect_failure "a tree without a credential namespace" "renders a BMC credential namespace" "$synthetic" + +echo "BMC credential namespace check: all cases passed" diff --git a/hack/validate-bmc-credential-namespace.sh b/hack/validate-bmc-credential-namespace.sh new file mode 100755 index 00000000..b46e3e04 --- /dev/null +++ b/hack/validate-bmc-credential-namespace.sh @@ -0,0 +1,10 @@ +#!/bin/sh +# Fails when a Secret other than a BMC credential Secret renders into a BMC +# credential namespace. See docs/operations/bmc-discovery.md. +set -eu + +repo_root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd -P) +GOCACHE=${GOCACHE:-${TMPDIR:-/tmp}/fleet-bmc-credential-namespace-go-cache} +export GOCACHE +mkdir -p "$GOCACHE" +exec go run "$repo_root/hack/bmc-credential-namespace-validator.go" "${1:-config}" From 1f2fe4560660d7c663d9c4523edf1bb97842623b Mon Sep 17 00:00:00 2001 From: Scot Wells Date: Wed, 25 Nov 2026 21:15:49 -0600 Subject: [PATCH 3/3] docs(bmc-discovery): Explain the credential namespace rule Record why the Secret Role stays namespace-wide, what the render check enforces, and how a sidecar deployment keeps its credential namespace separate from the host pod's. Co-Authored-By: Claude Opus 5.5 --- docs/operations/bmc-discovery.md | 60 ++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 6 deletions(-) diff --git a/docs/operations/bmc-discovery.md b/docs/operations/bmc-discovery.md index cb149386..b52e166a 100644 --- a/docs/operations/bmc-discovery.md +++ b/docs/operations/bmc-discovery.md @@ -42,7 +42,8 @@ never runs two. It needs: - a kubeconfig for **one Milo project**, mounted from a Secret; -- read access to credential Secrets in the namespace where it runs; +- list and watch on Secrets in the namespace where it runs, which must hold + credential Secrets only (see [Credential namespace](#credential-namespace)); - network reachability to each `spec.bmc.endpoint`. It needs no privilege, capability or host networking of its own. @@ -62,9 +63,48 @@ filesystem, no privilege escalation, all capabilities dropped and the | Configuration | A patch of `config.yaml` or the generated ConfigMap. | The ServiceAccount token is mounted because discovery reads Secrets through -the Kubernetes API. Kubernetes RBAC cannot narrow a Role to labelled Secrets, -so run discovery in a namespace that holds nothing else it should not read. -To avoid the token, set `localKubeconfig` and mount a kubeconfig instead. +the Kubernetes API. To avoid the token, set `localKubeconfig` and mount a +kubeconfig instead. + +### Credential namespace + +The Role grants `list` and `watch` on Secrets in discovery's namespace, and no +`get`: discovery reads Secrets only through a label-selected watch and, for +`--once`, a label-selected list. RBAC cannot filter by label, so the Role +still lets discovery read every Secret in that namespace. The namespace must +therefore hold credential Secrets only, plus discovery's own Milo kubeconfig +Secret. A pod mounts Secrets from its own namespace only, so that Secret sits +beside discovery and the Role can read it. That exposes nothing discovery +does not already mount. + +`hack/validate-bmc-credential-namespace.sh` runs in CI. It renders every +Kustomize entry point under `config/` and fails when a Secret without the +credential label and the three Device annotations lands in a credential +namespace. A credential namespace is one that holds discovery's +ServiceAccount or Role, holds a labelled credential Secret, or is a Namespace +labelled `fleet.datumapis.com/bmc-credential-namespace: "true"`. The site's +Redfish credential namespace carries that label. A namespace found in any +root is checked in every root, because Flux may apply a namespace and the +objects in it from different Kustomizations. For a render that leaves the +namespace unset, such as `config/base/bmc-discovery`, every unnamespaced +Secret in that render counts. The only other Secret admitted is +`fleet-bmc-discovery-milo-kubeconfig`, and only in a namespace that runs +discovery. The check covers this repository's roots only. A deploying +repository that adds Secrets to discovery's namespace must keep the same rule. + +The Role stays namespace-wide for these reasons: + +- `resourceNames` does not apply to an unfiltered `list` or `watch`. A Role + limited by name would need discovery to `get` each Device's Secret by a + derived name, as the Redfish site workers do. Today a discovery Secret may + have any name; requiring the derived name changes the credential contract + for every deploying repository. +- The names would have to be rendered from the Devices enrolled in Milo, + which change at run time. No root in this repository deploys discovery, so + the deploying repository would need to re-render the Role on every + enrollment. A Device added before the Role updates gets no credential. +- Polling by name loses the watch. Today an approved pin takes effect at once. + Keeping that would need one name-filtered watch per Device. ### Sidecar in another pod @@ -77,7 +117,10 @@ and volume snippet to merge into that pod's template. In that case: - create the ConfigMap and Milo kubeconfig Secret yourself; the snippet uses fixed names; - bind the Role in `rbac.yaml` to that pod's ServiceAccount, or set - `localKubeconfig`; + `localKubeconfig`. Either identity reads every Secret in the credential + namespace. When the pod's own namespace holds other Secrets, create the + Role and its binding in a namespace that holds credential Secrets only, and + set `credentialNamespace` to it; - set `healthProbeAddress: ""` if port 8081 is already in use in the pod. The snippet defines no probes. @@ -356,7 +399,12 @@ sessions. Basic authentication is used; no Redfish session is created. with no credential sent, then approval yields inventory and `IdentityMatched=True`; - the Device status schema, the discoverer role, and the shipped Deployment's - single unprivileged replica. + single unprivileged replica; +- with envtest assets, that the shipped Role serves the credential cache and + `--once`, refuses `get` and any other namespace. + +`./hack/test-bmc-credential-namespace.sh` proves the render check passes the +real roots and fails on a stray Secret in each kind of credential namespace. ## Not yet qualified