Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 12: Multi-Tenancy

Ziel: Ein Team bekommt einen eigenen Namespace und liefert selbst aus, darf aber nichts außerhalb anfassen. Du erlebst, wie ein Team aus einer schlecht abgesicherten Installation ausbricht, und sperrst Flux so ab, dass es nicht mehr geht. · Dauer: ca. 90 min · Voraussetzung: Tag 11

Briefing

  • Bisher wendet der kustomize-controller alles mit seinen eigenen Rechten an, und die sind cluster-admin. Für ein Plattform-Team, das selbst das Fleet-Repo pflegt, ist das in Ordnung. Für fremde Teams nicht.
  • Ein Mandant (Tenant) ist ein Team mit eigenem Namespace und eigenem ServiceAccount. Seine Kustomization bekommt serviceAccountName, und Flux wendet die Manifeste dann als dieser ServiceAccount an (Impersonation). Was der ServiceAccount nicht darf, darf auch Flux für das Team nicht.
  • Im Lab liefert das Team als OCI-Artefakt in die Registry aus Tag 3. Ein eigenes Git-Repo pro Team funktioniert genauso, nur mit einer GitRepository.
 Team blau:  flux push artifact ──► Registry team-blau/apps:1.x
 Plattform:  tenants/team-blau/
               rbac.yaml   Namespace, ServiceAccount team-blau, RoleBinding (nur im Namespace)
               sync.yaml   OCIRepository + Kustomization (serviceAccountName: team-blau)
                                   │ wendet an als system:serviceaccount:team-blau:team-blau
                                   ▼
                           Namespace team-blau

Drill 1: Ein Mandant

Zuerst die Seite des Teams. Es hat eine kleine notes-api ohne Datenbank, auf Port 30092, und schiebt sie als Version 1.0.0 in die Registry:

mkdir -p ~/flux-lab/team-blau
cd ~/flux-lab/team-blau
cat > app.yaml <<'EOF'
apiVersion: v1
kind: Secret
metadata:
  name: notes-api
stringData:
  apiKey: blau-key-123
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: notes
spec:
  replicas: 1
  selector:
    matchLabels:
      app: notes
  template:
    metadata:
      labels:
        app: notes
    spec:
      containers:
        - name: api
          image: ghcr.io/thomaszachmann/notes-api:0.7.1
          env:
            - name: NOTES_API_KEY
              valueFrom:
                secretKeyRef:
                  name: notes-api
                  key: apiKey
---
apiVersion: v1
kind: Service
metadata:
  name: notes
spec:
  type: NodePort
  selector:
    app: notes
  ports:
    - port: 80
      targetPort: 8080
      nodePort: 30092
EOF
flux push artifact oci://localhost:30500/team-blau/apps:1.0.0 --path=. \
  --source=local --revision=1.0.0 --insecure-registry

Erwartet (gekürzt):

✔ artifact successfully pushed to localhost:30500/team-blau/apps@sha256:ee73bebe…

Keine Namespaces in den Manifesten: Wohin es geht, bestimmt die Plattform.

Jetzt die Seite der Plattform. flux create tenant erzeugt Namespace, ServiceAccount und Rechte:

cd ~/flux-lab/fleet
mkdir -p tenants/team-blau
flux create tenant team-blau --with-namespace=team-blau --export \
  > tenants/team-blau/rbac.yaml
grep -A3 -E 'roleRef|^kind' tenants/team-blau/rbac.yaml

Erwartet (gekürzt):

kind: Namespace
...
kind: ServiceAccount
...
kind: RoleBinding
...
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin

cluster-admin klingt nach viel. Über eine RoleBinding gilt die Rolle aber nur im Namespace team-blau. Dort darf das Team alles, außerhalb nichts.

Quelle und Kustomization des Teams liegen in seinem Namespace:

flux create source oci apps --namespace=team-blau \
  --url=oci://registry.registry.svc.cluster.local:5000/team-blau/apps \
  --tag-semver=">=1.0.0" --insecure --interval=1m --export > tenants/team-blau/sync.yaml
flux create kustomization apps --namespace=team-blau --source=OCIRepository/apps \
  --path=./ --prune=true --interval=5m --target-namespace=team-blau \
  --service-account=team-blau --export >> tenants/team-blau/sync.yaml
grep -E 'serviceAccountName|targetNamespace|semver' tenants/team-blau/sync.yaml

Erwartet:

    semver: '>=1.0.0'
  serviceAccountName: team-blau
  targetNamespace: team-blau

flux create setzt den Bereich in einfache Anführungszeichen. Eine Kustomization tenants wendet den ganzen Ordner an, egal wie viele Teams dazukommen:

flux create kustomization tenants --source=GitRepository/flux-system \
  --path=./tenants --prune=true --interval=10m --export > clusters/lab/tenants.yaml
git add -A
git commit -m "Mandant team-blau"
git push
flux reconcile kustomization flux-system --with-source
flux reconcile kustomization tenants
flux get kustomizations -n team-blau
curl -s localhost:30092/version; echo

Erwartet (gekürzt):

NAME    REVISION                SUSPENDED   READY   MESSAGE
apps    1.0.0@sha256:ee73bebe   False       True    Applied revision: 1.0.0@sha256:ee73bebe
0.7.1

Ab jetzt liefert das Team selbst aus: neue Version pushen, fertig. Die Plattform muss dafür nichts committen.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Das Team probiert es

Ein Team-Mitglied will mehr Rechte und legt eine ClusterRoleBinding dazu:

cd ~/flux-lab/team-blau
cat > escape.yaml <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: team-blau-admin
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
  - kind: ServiceAccount
    name: team-blau
    namespace: team-blau
EOF
flux push artifact oci://localhost:30500/team-blau/apps:1.1.0 --path=. \
  --source=local --revision=1.1.0 --insecure-registry
flux reconcile source oci apps -n team-blau
flux get kustomizations -n team-blau

Erwartet (gekürzt):

NAME    REVISION                SUSPENDED   READY   MESSAGE
apps    1.0.0@sha256:ee73bebe   False       False   ClusterRoleBinding/team-blau-admin dry-run failed (Forbidden): clusterrolebindings.rbac.authorization.k8s.io "team-blau-admin" is forbidden: User "system:serviceaccount:team-blau:team-blau" cannot patch resource "clusterrolebindings" …

Die Impersonation greift. Flux hat die Manifeste als team-blau:team-blau geprüft, und der darf keine cluster-weiten Objekte anlegen.

Das Team-Mitglied gibt nicht auf. Wenn die eigene Kustomization zu wenig darf, warum nicht eine zweite mitliefern? Die ClusterRoleBinding wandert in ein eigenes Artefakt, und das App-Artefakt bekommt eine Flux-Kustomization, die es anwendet, ohne serviceAccountName:

mkdir -p ~/flux-lab/team-blau-extra
mv escape.yaml ~/flux-lab/team-blau-extra/
flux push artifact oci://localhost:30500/team-blau/extra:1.0.0 \
  --path=$HOME/flux-lab/team-blau-extra --source=local --revision=1.0.0 \
  --insecure-registry
cat > boss.yaml <<'EOF'
apiVersion: source.toolkit.fluxcd.io/v1
kind: OCIRepository
metadata:
  name: extra
spec:
  interval: 1m
  insecure: true
  url: oci://registry.registry.svc.cluster.local:5000/team-blau/extra
  ref:
    tag: 1.0.0
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: boss
spec:
  interval: 1m
  path: ./
  prune: true
  sourceRef:
    kind: OCIRepository
    name: extra
EOF
flux push artifact oci://localhost:30500/team-blau/apps:1.2.0 --path=. \
  --source=local --revision=1.2.0 --insecure-registry
flux reconcile source oci apps -n team-blau
flux reconcile kustomization apps -n team-blau

Eine OCIRepository und eine Kustomization im eigenen Namespace anzulegen, darf das Team. Eine halbe Minute später:

flux get kustomizations -n team-blau
kubectl get clusterrolebinding team-blau-admin

Erwartet:

NAME    REVISION                SUSPENDED   READY   MESSAGE
apps    1.2.0@sha256:1e9db563   False       True    Applied revision: 1.2.0@sha256:1e9db563
boss    1.0.0@sha256:997e06e8   False       True    Applied revision: 1.0.0@sha256:997e06e8
NAME              ROLE                        AGE
team-blau-admin   ClusterRole/cluster-admin   22s

Ausgebrochen. Die Kustomization boss hat keinen serviceAccountName, also hat der kustomize-controller sie mit seinen eigenen Rechten angewendet. Das Team ist jetzt cluster-admin, im ganzen Cluster.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Die Plattform vorbereiten

Die Lösung ist eine Startoption der Controller: --default-service-account=default. Jede Kustomization und jeder HelmRelease ohne serviceAccountName läuft dann als ServiceAccount default seines Namespaces, und der darf nichts.

Das gilt aber auch für deine eigenen Kustomizations in flux-system und für deine HelmReleases. Schaltest du die Option einfach ein, sperrt sich die Plattform selbst aus. Also zuerst vorbereiten.

Die Demos aus Tag 7 entfernen. notes-git und podinfo-helm haben ihren Zweck erfüllt. notes-git würde den Lockdown ohnehin nicht überleben: Sein HelmRelease liest eine Quelle aus flux-system, einem fremden Namespace.

cd ~/flux-lab/fleet
git rm -q -r apps/notes-git apps/podinfo-helm \
  clusters/lab/notes-git.yaml clusters/lab/podinfo-helm.yaml

notes-helm bekommt einen eigenen ServiceAccount, mit Admin-Rechten nur im eigenen Namespace:

cat > apps/notes-helm/rbac.yaml <<'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
  name: notes-helm
  namespace: notes-helm
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: notes-helm-reconciler
  namespace: notes-helm
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: admin
subjects:
  - kind: ServiceAccount
    name: notes-helm
    namespace: notes-helm
EOF
sed -i 's/  - namespace.yaml/  - namespace.yaml\n  - rbac.yaml/' apps/notes-helm/kustomization.yaml
sed -i 's/^  interval: 10m0s/  interval: 10m0s\n  serviceAccountName: notes-helm/' \
  apps/notes-helm/release.yaml

Der Alert notes liest Ereignisse aus notes-helm, ebenfalls ein fremder Namespace. Diese Quelle fliegt raus:

sed -i '/  - kind: HelmRelease/,/    namespace: notes-helm/d' clusters/lab/alerts.yaml

Alle Kustomizations in flux-system sollen weiter als kustomize-controller laufen. Statt jede Datei anzufassen, bekommt clusters/lab eine eigene kustomization.yaml mit einem Patch für alle:

cd clusters/lab
printf 'apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n' \
  > kustomization.yaml
for f in flux-system $(ls *.yaml | grep -v kustomization.yaml); do
  echo "  - $f" >> kustomization.yaml
done
cat >> kustomization.yaml <<'EOF'
patches:
  - patch: |
      - op: add
        path: /spec/serviceAccountName
        value: kustomize-controller
    target:
      kind: Kustomization
      namespace: flux-system
EOF
cd ~/flux-lab/fleet
kubectl kustomize clusters/lab | grep -c 'serviceAccountName: kustomize-controller'

Erwartet:

11

Zehn Kustomizations, einschließlich flux-system selbst, laufen nach dem Patch ausdrücklich als kustomize-controller. Der elfte Treffer ist das Deployment des kustomize-controllers, das diesen ServiceAccount schon immer hatte.

Merke: Mit einer eigenen kustomization.yaml in clusters/lab liest Flux nicht mehr automatisch jede Datei im Ordner, sondern nur noch die unter resources. Jede neue Datei muss ab jetzt dort eingetragen werden.

git add -A
git commit -m "Vorbereitung Lockdown: ServiceAccounts, Demos entfernt"
git push
flux reconcile kustomization flux-system --with-source
flux reconcile kustomization notes-helm
flux get helmreleases -A

Erwartet (gekürzt):

NAMESPACE   NAME    REVISION            SUSPENDED   READY   MESSAGE
notes-helm  notes   0.4.0+5de96b4085b8  False       True    Helm upgrade succeeded for release notes-helm/notes.v12 …

Fortschritt speichern? Kostenlos registrieren

Drill 4: Der Lockdown

Die Optionen kommen als Patches an die Controller. Dafür ist die kustomization.yaml in clusters/lab/flux-system gedacht, die der Bootstrap angelegt hat:

cat >> clusters/lab/flux-system/kustomization.yaml <<'EOF'
patches:
  - patch: |
      - op: add
        path: /spec/template/spec/containers/0/args/-
        value: --no-cross-namespace-refs=true
    target:
      kind: Deployment
      name: "(kustomize-controller|helm-controller|notification-controller|image-reflector-controller|image-automation-controller)"
  - patch: |
      - op: add
        path: /spec/template/spec/containers/0/args/-
        value: --no-remote-bases=true
    target:
      kind: Deployment
      name: kustomize-controller
  - patch: |
      - op: add
        path: /spec/template/spec/containers/0/args/-
        value: --default-service-account=default
    target:
      kind: Deployment
      name: "(kustomize-controller|helm-controller)"
EOF
git commit -am "Flux: Mandanten-Lockdown"
git push
flux reconcile kustomization flux-system --with-source
Option Wirkung
--no-cross-namespace-refs Objekte dürfen nur auf Quellen und Provider im eigenen Namespace zeigen
--no-remote-bases Kustomize darf keine Basen aus dem Internet laden, nur aus der Quelle
--default-service-account=default ohne serviceAccountName gilt der ServiceAccount default

Die Controller starten neu. Nach einer halben Minute:

kubectl -n flux-system get deploy kustomize-controller \
  -o jsonpath='{.spec.template.spec.containers[0].args}{"\n"}' | tr , '\n' | tail -3
flux get kustomizations -A

Erwartet (gekürzt):

"--no-cross-namespace-refs=true"
"--no-remote-bases=true"
"--default-service-account=default"]
NAMESPACE   NAME            …   READY   MESSAGE
flux-system echo            …   True    Applied revision: main@sha1:d8c26069
flux-system flux-system     …   True    Applied revision: main@sha1:d8c26069
...
team-blau   apps            …   True    Applied revision: 1.2.0@sha256:1e9db563
team-blau   boss            …   False   ClusterRoleBinding/team-blau-admin dry-run failed (Forbidden): … User "system:serviceaccount:team-blau:default" cannot patch resource "clusterrolebindings" …

Alles von der Plattform ist bereit. boss läuft jetzt als team-blau:default und scheitert.

Fortschritt speichern? Kostenlos registrieren

Drill 5: Aufräumen nach dem Einbruch

Der Lockdown verhindert neue Einbrüche. Die ClusterRoleBinding von vorhin steht aber noch:

kubectl get clusterrolebinding team-blau-admin

Erwartet:

NAME              ROLE                        AGE
team-blau-admin   ClusterRole/cluster-admin   3m14s

Das Team entfernt boss aus seinem Artefakt:

cd ~/flux-lab/team-blau
rm boss.yaml
flux push artifact oci://localhost:30500/team-blau/apps:1.3.0 --path=. \
  --source=local --revision=1.3.0 --insecure-registry
flux reconcile source oci apps -n team-blau
flux reconcile kustomization apps -n team-blau
kubectl -n team-blau get kustomization boss \
  -o jsonpath='{.metadata.finalizers} {.metadata.deletionTimestamp}{"\n"}'

Erwartet (gekürzt):

...
["finalizers.fluxcd.io"] 2026-11-12T17:12:52Z

boss soll gelöscht werden, hängt aber. Beim Löschen räumt eine Kustomization mit prune: true ihre Objekte ab, und dafür müsste sie die ClusterRoleBinding löschen. Das darf sie als team-blau:default nicht. Das muss ein Admin von Hand erledigen:

kubectl delete clusterrolebinding team-blau-admin
kubectl -n team-blau patch kustomization boss --type=json \
  -p='[{"op":"remove","path":"/metadata/finalizers"}]'
kubectl -n team-blau get kustomizations,ocirepositories

Erwartet (gekürzt):

clusterrolebinding.rbac.authorization.k8s.io "team-blau-admin" deleted
kustomization.kustomize.toolkit.fluxcd.io/boss patched
NAME                                             AGE     READY   STATUS
kustomization.kustomize.toolkit.fluxcd.io/apps   5m56s   True    Applied revision: 1.3.0@sha256:1421e2ea…
NAME                                              …   READY   STATUS
ocirepository.source.toolkit.fluxcd.io/apps       …   True    stored artifact for digest '1.3.0@sha256:1421e2ea…'

Der Finalizer ist Flux’ Zusage, beim Löschen aufzuräumen. Entfernst du ihn, gibst du diese Zusage auf. Das ist hier richtig, weil du die einzige fremde Hinterlassenschaft selbst gelöscht hast.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

flux get all -A --status-selector ready=false

Erwartet: keine Ausgabe, alles ist bereit.

kubectl auth can-i create clusterrolebindings \
  --as=system:serviceaccount:team-blau:team-blau

Erwartet (gekürzt):

no
diff -r ~/flux-lab/fleet/tenants ~/flux-lab/code/loesung/tag12/tenants -x 'team-gruen'

Erwartet: keine Ausgabe.

Challenge

Team grün kommt dazu: eigener Namespace team-gruen, Artefakt team-gruen/apps, notes-api auf Port 30093. Wie viele Dateien musst du im Fleet-Repo anlegen, und musst du clusters/lab/kustomization.yaml anfassen?

Lösung

Das Team:

mkdir -p ~/flux-lab/team-gruen
sed 's/blau-key-123/gruen-key-123/; s/30092/30093/' ~/flux-lab/team-blau/app.yaml \
  > ~/flux-lab/team-gruen/app.yaml
flux push artifact oci://localhost:30500/team-gruen/apps:1.0.0 \
  --path=$HOME/flux-lab/team-gruen --source=local --revision=1.0.0 --insecure-registry

Die Plattform, zwei Dateien:

cd ~/flux-lab/fleet
mkdir -p tenants/team-gruen
flux create tenant team-gruen --with-namespace=team-gruen --export \
  > tenants/team-gruen/rbac.yaml
sed 's/team-blau/team-gruen/g' tenants/team-blau/sync.yaml > tenants/team-gruen/sync.yaml
git add -A
git commit -m "Mandant team-gruen"
git push
flux reconcile kustomization flux-system --with-source
flux reconcile kustomization tenants
flux get kustomizations -n team-gruen
curl -s localhost:30093/version; echo

Erwartet (gekürzt):

NAME    REVISION                SUSPENDED   READY   MESSAGE
apps    1.0.0@sha256:57c8e47c   False       True    Applied revision: 1.0.0@sha256:57c8e47c
0.7.1

clusters/lab/kustomization.yaml bleibt unverändert. Die Kustomization tenants zeigt auf den Ordner tenants/, und dort hat Flux keine kustomization.yaml, also liest es jede Datei in jedem Unterordner. Ein neues Team sind zwei neue Dateien.

Fortschritt speichern? Kostenlos registrieren

Enterprise-Notiz

  • Lockdown von Anfang an: Die Patches aus Drill 4 gehören in einen neuen Cluster, bevor das erste Team kommt. Nachträglich muss jedes Objekt der Plattform einen ServiceAccount bekommen, wie in Drill 3.
  • Policies dazu: RBAC regelt, was ein Team anlegen darf, aber nicht wie. Ob Images aus der richtigen Registry kommen, ob Ressourcen-Limits gesetzt sind, prüft ein Admission-Controller wie Kyverno (siehe „Kyverno & NetworkPolicies zum Anfassen“).
  • Flux Operator: Der Flux Operator bringt Multi-Tenancy als Einstellung mit (multitenant: true). Er setzt die Patches aus Drill 4 selbst und hält sie bei jedem Upgrade aktuell.