Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 5 additions & 4 deletions config/base/bmc-discovery/rbac.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,18 @@ 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:
name: fleet-bmc-discovery-credentials
rules:
- apiGroups: [""]
resources: [secrets]
verbs: [get, list, watch]
verbs: [list, watch]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
Expand Down
4 changes: 4 additions & 0 deletions config/site/redfish/base/credentials.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
60 changes: 54 additions & 6 deletions docs/operations/bmc-discovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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

Expand All @@ -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.

Expand Down Expand Up @@ -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

Expand Down
221 changes: 221 additions & 0 deletions hack/bmc-credential-namespace-validator.go
Original file line number Diff line number Diff line change
@@ -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) }
Loading
Loading