Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 6: Autorisierung

Ziel: In notes darf nur noch sprechen, wer muss: last → web → notes-api → postgres und web → helper. Alles andere wird abgelehnt, Probes und Prometheus laufen weiter. · Dauer: ca. 75 min · Voraussetzung: Tag 5

Briefing

  • Ein Server beschreibt einen Port einer Pod-Gruppe. Sein accessPolicy gilt für alles, was keine Regel trifft – Standard deny.
  • Eine AuthorizationPolicy verbindet ein Ziel (Server oder Route) mit einer Authentifizierung: MeshTLSAuthentication (Identitäten) oder NetworkAuthentication (IP-Netze, für Klartext).
  • Ports ohne Server folgen der Default-Policy des Proxys (config.linkerd.io/default-inbound-policy), festgelegt beim Pod-Start.
  • Reihenfolge im Betrieb: Server im Audit-Modus, Regeln, auswerten, scharf schalten.
  • Abgelehnt wird mit HTTP 403, bei TCP wird die Verbindung geschlossen.
 last ──> web ──> notes-api ──> postgres      erlaubt (MeshTLS)
           └────> helper                      erlaubt (MeshTLS)
 Kubelet ──> Probes                           automatisch erlaubt
 Prometheus (ohne Proxy) ──> :4191            erlaubt (NetworkAuthentication)
 tag06/fremd, tag06/ohne ──> alles            403 bzw. Verbindung zu

Drill 1: Zwei Eindringlinge

fremd hat einen Proxy und eine eigene Identität, ohne hat gar keinen. Beide haben neben curl einen psql-Container.

mkdir -p ~/linkerd/tag06 && cd ~/linkerd/tag06
kubectl create namespace tag06
kubectl annotate namespace tag06 linkerd.io/inject=enabled
kubectl -n tag06 create serviceaccount fremd
cat > clients.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata: {name: fremd, namespace: tag06}
spec:
  replicas: 1
  selector: {matchLabels: {app: fremd}}
  template:
    metadata: {labels: {app: fremd}}
    spec:
      serviceAccountName: fremd
      containers:
      - name: curl
        image: docker.io/curlimages/curl:8.23.0
        command: [sleep, infinity]
      - name: psql
        image: docker.io/library/postgres:18.7-alpine
        command: [sleep, infinity]
---
apiVersion: apps/v1
kind: Deployment
metadata: {name: ohne, namespace: tag06}
spec:
  replicas: 1
  selector: {matchLabels: {app: ohne}}
  template:
    metadata:
      labels: {app: ohne}
      annotations: {linkerd.io/inject: disabled}
    spec:
      containers:
      - name: curl
        image: docker.io/curlimages/curl:8.23.0
        command: [sleep, infinity]
      - name: psql
        image: docker.io/library/postgres:18.7-alpine
        command: [sleep, infinity]
EOF
kubectl apply -f clients.yaml
kubectl -n tag06 rollout status deploy/fremd --timeout=120s
kubectl -n tag06 get pods

Erwartet (gekürzt):

NAME                    READY   STATUS    RESTARTS   AGE
fremd-5f65fcf95-x792g   3/3     Running   0          7s
ohne-ccfc5cbd9-jnvjf    2/2     Running   0          6s

Jetzt greifen beide auf alles zu, was notes bietet:

for c in fremd ohne; do
  for u in web.notes/ notes-api.notes/notes helper.notes/get; do
    kubectl -n tag06 exec deploy/$c -c curl -- curl -s -o /dev/null \
      -w "$c $u %{http_code}\n" -H 'X-API-Key: lab-key-123' http://$u
  done
done
DB=postgres://notes:[email protected]:5432/notes
for c in fremd ohne; do
  kubectl -n tag06 exec deploy/$c -c psql -- psql $DB -tAc 'select count(*) from notes'
done

Erwartet:

fremd web.notes/ 200
fremd notes-api.notes/notes 200
fremd helper.notes/get 200
ohne web.notes/ 200
ohne notes-api.notes/notes 200
ohne helper.notes/get 200
1
1

Das ist der Stand nach Tag 5: alles verschlüsselt, nichts gesperrt. Der API-Schlüssel ist kein Schutz – er steht in der Konfiguration von web und damit bei jedem, der sie lesen kann.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Server im Audit-Modus

linkerd viz authz -n notes deploy/helper

Erwartet (gekürzt):

ROUTE    SERVER                       AUTHORIZATION                UNAUTHORIZED  SUCCESS
default  default:all-unauthenticated  default/all-unauthenticated        0.0rps   79.66%
probe    default:all-unauthenticated  default/probe                      0.0rps  100.00%

Kein Server, also gilt die Default-Policy all-unauthenticated. Die Zeile probe sind die Readiness-Probes. Jetzt ein Server pro Port, zunächst mit accessPolicy: audit – er sperrt nichts, markiert aber alles, was keine Regel trifft. Server liegt aktuell in policy.linkerd.io/v1beta3, ältere Anleitungen zeigen noch v1beta1.

cat > servers.yaml <<'EOF'
apiVersion: policy.linkerd.io/v1beta3
kind: Server
metadata: {name: web-http, namespace: notes}
spec:
  podSelector: {matchLabels: {app: web}}
  port: http
  proxyProtocol: HTTP/1
  accessPolicy: audit
---
apiVersion: policy.linkerd.io/v1beta3
kind: Server
metadata: {name: notes-api-http, namespace: notes}
spec:
  podSelector: {matchLabels: {app: notes-api}}
  port: http
  proxyProtocol: HTTP/1
  accessPolicy: audit
---
apiVersion: policy.linkerd.io/v1beta3
kind: Server
metadata: {name: helper-http, namespace: notes}
spec:
  podSelector: {matchLabels: {app: helper}}
  port: http
  proxyProtocol: HTTP/1
  accessPolicy: audit
---
apiVersion: policy.linkerd.io/v1beta3
kind: Server
metadata: {name: postgres, namespace: notes}
spec:
  podSelector: {matchLabels: {app: postgres}}
  port: postgres
  proxyProtocol: opaque
  accessPolicy: audit
EOF
kubectl apply -f servers.yaml
kubectl -n notes get server
for c in fremd ohne; do
  kubectl -n tag06 exec deploy/$c -c curl -- \
    curl -s -o /dev/null http://helper.notes/get
done
sleep 70
linkerd viz authz -n notes deploy/helper
kubectl -n notes logs -l app=helper -c linkerd-proxy --since=2m \
  | grep 'Request allowed' \
  | grep -oE 'Name\("[^.]*\.[^.]*|client.tls=None' | sort | uniq -c

Erwartet (gekürzt):

NAME             PORT       PROTOCOL   ACCESS POLICY
helper-http      http       HTTP/1     audit
notes-api-http   http       HTTP/1     audit
postgres         postgres   opaque     audit
web-http         http       HTTP/1     audit
ROUTE    SERVER                       AUTHORIZATION                UNAUTHORIZED  SUCCESS
default  default:all-unauthenticated  default/all-unauthenticated        0.0rps  100.00%
probe    default:all-unauthenticated  default/probe                      0.0rps  100.00%
default  helper-http                  default/audit                      0.0rps   66.67%
probe    helper-http                  default/probe                      0.0rps  100.00%
      1 Name("fremd.tag06
     89 Name("web.notes
      1 client.tls=None

Port 8080 hängt jetzt am Server helper-http. Die Zeilen mit default:all-unauthenticated sind der Admin-Port 4191: Prometheus-Scrapes und die Probes des Proxys selbst. Um den kümmerst du dich in Drill 6. Im Log steht jeder Request, den nur audit durchlässt: web (noch ohne Regel), fremd mit Identität und ohne als client.tls=None – kein Proxy, kein Zertifikat.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Identitäten erlauben

Pro Client eine MeshTLSAuthentication, pro Kante eine AuthorizationPolicy. identityRefs auf ServiceAccounts erspart dir die langen Identitätsnamen:

cat > authz.yaml <<'EOF'
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata: {name: last, namespace: notes}
spec:
  identityRefs: [{kind: ServiceAccount, name: last}]
---
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata: {name: web, namespace: notes}
spec:
  identityRefs: [{kind: ServiceAccount, name: web}]
---
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata: {name: notes-api, namespace: notes}
spec:
  identityRefs: [{kind: ServiceAccount, name: notes-api}]
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata: {name: web-von-last, namespace: notes}
spec:
  targetRef: {group: policy.linkerd.io, kind: Server, name: web-http}
  requiredAuthenticationRefs:
  - {group: policy.linkerd.io, kind: MeshTLSAuthentication, name: last}
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata: {name: notes-api-von-web, namespace: notes}
spec:
  targetRef: {group: policy.linkerd.io, kind: Server, name: notes-api-http}
  requiredAuthenticationRefs:
  - {group: policy.linkerd.io, kind: MeshTLSAuthentication, name: web}
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata: {name: helper-von-web, namespace: notes}
spec:
  targetRef: {group: policy.linkerd.io, kind: Server, name: helper-http}
  requiredAuthenticationRefs:
  - {group: policy.linkerd.io, kind: MeshTLSAuthentication, name: web}
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata: {name: postgres-von-notes-api, namespace: notes}
spec:
  targetRef: {group: policy.linkerd.io, kind: Server, name: postgres}
  requiredAuthenticationRefs:
  - {group: policy.linkerd.io, kind: MeshTLSAuthentication, name: notes-api}
EOF
kubectl apply -f authz.yaml
sleep 65
linkerd viz authz -n notes deploy/helper | grep helper-http
linkerd viz authz -n notes deploy/web | grep web-http

Erwartet (gekürzt, Zahlen schwanken):

default  helper-http  authorizationpolicy/helper-von-web        0.0rps   68.18%  0.7rps
probe    helper-http  default/probe                             0.0rps  100.00%  0.2rps
default  web-http     authorizationpolicy/web-von-last          0.0rps   86.41%  1.7rps
default  web-http     default/audit                             0.0rps   91.67%  0.2rps

helper sieht web jetzt unter der eigenen Regel. Bei web läuft aber noch ein Teil unter audit – obwohl außer last niemand anfragt. Warum?

for p in $(kubectl -n notes get pod -l app=web -o name); do
  linkerd diagnostics policy -n notes $p 8080 -o json \
    | jq -c '[.authorizations[].labels.name]'
done

Erwartet (Reihenfolge kann bei dir anders sein):

["audit","web-von-last"]
["web-von-last","audit"]

Im Audit-Modus liefert die Control Plane audit als zusätzliche Erlaubnis mit, und die Reihenfolge ist nicht festgelegt. Steht audit vorn, zählt der Proxy auch erlaubten Verkehr als audit. Merke: Im Audit-Modus beweist authz_name="audit" noch keinen Verstoß – entscheidend ist, wer dort auftaucht.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Audit auswerten

Erst lässt du die Eindringlinge aus Drill 1 noch einmal anklopfen – im Audit-Modus kommen sie durch, werden aber gezählt:

for c in fremd ohne; do
  for u in web.notes/ notes-api.notes/notes helper.notes/get; do
    kubectl -n tag06 exec deploy/$c -c curl -- curl -s -o /dev/null \
      -w "$c $u %{http_code}\n" -H 'X-API-Key: lab-key-123' http://$u
  done
done
sleep 30

Erwartet: sechs Zeilen mit 200, wie in Drill 1.

Dann nach Client-Identität fragen. Prometheus läuft seit Tag 4:

kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9090 \
  >/dev/null 2>&1 &
sleep 4
Q='sum by (deployment, client_id) (increase(inbound_http_authz_allow_total{
 namespace="notes", authz_name="audit"}[10m]))'
curl -s localhost:9090/api/v1/query --data-urlencode "query=$Q" \
  | jq -r '.data.result[] | .metric.deployment + " " + (.metric.client_id // "-")
  + " " + .value[1]'
kill %1

Erwartet (gekürzt, Zahlen schwanken):

helper web.notes.serviceaccount.identity.linkerd.cluster.local 212.4171857142857
helper fremd.tag06.serviceaccount.identity.linkerd.cluster.local 2.0825214285714284
helper - 2.0825214285714284
web last.notes.serviceaccount.identity.linkerd.cluster.local 639.4215133126947
notes-api web.notes.serviceaccount.identity.linkerd.cluster.local 423.33642857142854
web fremd.tag06.serviceaccount.identity.linkerd.cluster.local 0
notes-api fremd.tag06.serviceaccount.identity.linkerd.cluster.local 0
web - 0
notes-api - 0

Die Zeilen mit web und last aus notes passen zu den Regeln (Drill 3). fremd und - (ohne Identität, also ohne) sind deine Eindringlinge – genau die sollen ab gleich scheitern. Die 0 heißt nicht „kein Zugriff“: Die Serie entsteht mit dem ersten Request, und increase() zählt nur, was danach dazukommt. Bei helper klopften beide schon in Drill 2 an. Gäbe es hier einen Client, den du nicht kennst, wäre jetzt der Moment, ihn zu erlauben oder zu klären.

Postgres ist Opaque, also TCP. Dafür zählt der Proxy Verbindungen:

linkerd diagnostics proxy-metrics -n notes po/postgres-0 \
  | grep '^inbound_tcp_authz_allow_total' \
  | grep -oE '(authz_name|client_id)="[^"]*"|\} [0-9]+' | paste - - -

Erwartet (gekürzt):

authz_name="postgres-von-notes-api"  client_id="notes-api.notes.serviceacco...  } 7

Fortschritt speichern? Kostenlos registrieren

Drill 5: Scharf schalten

sed -i 's/accessPolicy: audit/accessPolicy: deny/' servers.yaml
kubectl apply -f servers.yaml
kubectl -n notes get server
for c in fremd ohne; do
  for u in web.notes/ notes-api.notes/notes helper.notes/get; do
    kubectl -n tag06 exec deploy/$c -c curl -- curl -s -o /dev/null \
      -w "$c $u %{http_code}\n" -H 'X-API-Key: lab-key-123' http://$u
  done
done
for c in fremd ohne; do
  kubectl -n tag06 exec deploy/$c -c psql -- psql $DB -tAc 'select count(*) from notes'
done

Erwartet (gekürzt):

NAME             PORT       PROTOCOL   ACCESS POLICY
helper-http      http       HTTP/1     deny
...
fremd web.notes/ 403
fremd notes-api.notes/notes 403
fremd helper.notes/get 403
ohne web.notes/ 403
ohne notes-api.notes/notes 403
ohne helper.notes/get 403
psql: error: connection to server at "postgres.notes" (10.109.208.153), port 5432
failed: server closed the connection unexpectedly
psql: error: connection to server at "postgres.notes" (10.109.208.153), port 5432
failed: server closed the connection unexpectedly

HTTP wird mit 403 beantwortet – auch für ohne, denn der Proxy von web erkennt HTTP und antwortet selbst. Postgres ist Opaque: Dort schließt der Proxy die Verbindung. Und der legitime Verkehr?

sleep 50
kubectl -n notes logs deploy/last -c last --since=45s | awk '{print $2, $3}' \
  | sort | uniq -c

Erwartet (Zahlen schwanken):

     64 /api/notes 200
     22 /flaky 200
     10 /flaky 500

Unverändert. Jetzt die Ablehnungen sichtbar machen:

kubectl -n tag06 exec deploy/fremd -c curl -- sh -c 'for i in $(seq 60); do
  curl -s -o /dev/null -w "%{http_code}\n" http://helper.notes/get; sleep 0.5
  done' | sort | uniq -c
sleep 20
linkerd viz authz -n notes deploy/helper | grep helper-http
linkerd diagnostics proxy-metrics -n notes po/postgres-0 \
  | grep '^inbound_tcp_authz_deny_total' \
  | grep -oE '(client_id|tls|no_tls_reason)="[^"]*"'

Erwartet (gekürzt):

     60 403
default  helper-http                                                  1.1rps    0.00%
default  helper-http  authorizationpolicy/helper-von-web              0.0rps   69.05%
probe    helper-http  default/probe                                   0.0rps  100.00%
tls="no_identity"
no_tls_reason="port_skipped"
tls="true"
client_id="fremd.tag06.serviceaccount.identity.linkerd.cluster.local"

Die Spalte UNAUTHORIZED zeigt die abgelehnten Requests von fremd. Bei Postgres steht fremd mit Identität, ohne als Klartext auf dem Opaque Port (port_skipped, wie an Tag 3). Die Probes laufen weiter: Solange ein Server keine Routen hat, erlaubt Linkerd die Probe-Pfade aus der Pod-Spec automatisch. Im Proxy-Log steht jede Ablehnung mit Identität:

kubectl -n notes logs deploy/helper -c linkerd-proxy --since=2m \
  | grep 'Request denied' | tail -1 | grep -oE 'server.name=[^ ]*|Name\("[^"]*'

Erwartet:

server.name=helper-http
Name("fremd.tag06.serviceaccount.identity.linkerd.cluster.local

Fortschritt speichern? Kostenlos registrieren

Drill 6: Default-Deny für den Rest

Die Server decken nur die App-Ports ab. Jeder andere Port, auch ein neuer, folgt der Default-Policy. Die setzt du für den ganzen Namespace auf deny. Sie wirkt nur bei neuen Pods:

kubectl annotate namespace notes config.linkerd.io/default-inbound-policy=deny
kubectl -n notes rollout restart deploy/web deploy/helper deploy/notes-api deploy/last
kubectl -n notes rollout restart statefulset/postgres
kubectl -n notes rollout status deploy/notes-api --timeout=180s
kubectl -n notes rollout status statefulset/postgres --timeout=180s
kubectl -n notes get pod -l app=web -o yaml | grep -m1 -A1 INBOUND_DEFAULT_POLICY

Erwartet:

      - name: LINKERD2_PROXY_INBOUND_DEFAULT_POLICY
        value: deny

Alle Pods werden 2/2 – die Probes des Proxys auf 4191 sind ebenfalls automatisch erlaubt. Aber nach einer Minute:

sleep 60
linkerd viz authz -n notes deploy/helper
kubectl -n monitoring port-forward svc/kps-kube-prometheus-stack-prometheus 9090 \
  >/dev/null 2>&1 &
sleep 4
curl -s localhost:9090/api/v1/targets?state=active | jq -r '.data.activeTargets[]
  | select(.labels.namespace=="notes") | .labels.pod + " " + .lastError' | head -3

Erwartet (gekürzt):

ROUTE  SERVER  AUTHORIZATION  UNAUTHORIZED  SUCCESS  RPS  LATENCY_P50  LATENCY_P95
helper-55bb5dfbbb-xqb59 server returned HTTP status 403 Forbidden
web-5967795fd8-8kzww server returned HTTP status 403 Forbidden
postgres-0 server returned HTTP status 403 Forbidden

Prometheus läuft ohne Proxy und scrapt 4191 im Klartext – unter deny verboten. viz und Grafana sind leer. Dafür gibt es die NetworkAuthentication. Die Pod-IP von Prometheus wechselt, also erlaubst du das Pod-Netz (bei Cilium im Labor 10.0.0.0/16, bei dir: kubectl get ciliumnodes -o jsonpath='{..podCIDRs}'):

cat > admin.yaml <<'EOF'
apiVersion: policy.linkerd.io/v1beta3
kind: Server
metadata: {name: proxy-admin, namespace: notes}
spec:
  podSelector: {}
  port: linkerd-admin
  proxyProtocol: HTTP/1
---
apiVersion: policy.linkerd.io/v1alpha1
kind: NetworkAuthentication
metadata: {name: pod-netz, namespace: notes}
spec:
  networks:
  - cidr: 10.0.0.0/16
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata: {name: admin-von-prometheus, namespace: notes}
spec:
  targetRef: {group: policy.linkerd.io, kind: Server, name: proxy-admin}
  requiredAuthenticationRefs:
  - {group: policy.linkerd.io, kind: NetworkAuthentication, name: pod-netz}
EOF
kubectl apply -f admin.yaml
sleep 30
curl -s localhost:9090/api/v1/query \
  --data-urlencode 'query=up{job="monitoring/linkerd-proxy", namespace="notes"}' \
  | jq -r '.data.result[] | .metric.pod + " " + .value[1]' | head -3
kill %1

Erwartet (gekürzt):

web-5967795fd8-gr4fz 1
postgres-0 1
helper-55bb5dfbbb-xqb59 1

Die Freigabe gilt nur für Pods in notes – Server und AuthorizationPolicy wirken nie über den Namespace hinaus. Hat ein Pod in einem anderen Namespace einen eigenen Server für linkerd-admin (etwa das Multicluster-Gateway an Tag 12), lehnt er den Scrape mit 403 ab, bis dort eine eigene Regel für Prometheus steht.

Achtung: In Produktion legst du proxy-admin an, bevor du die Default-Policy umstellst – sonst fehlen Minuten an Metriken. Und 10.0.0.0/16 heißt: Jeder Pod im Cluster darf /metrics lesen. Enger geht es nur mit Prometheus im Mesh und einer MeshTLSAuthentication auf seine Identität.

linkerd viz tap läuft weiter, ohne eigene Regel: Der Tap-Port 4190 prüft selbst, dass der Aufrufer die Identität von tap aus linkerd-viz hat. Auch linkerd identity und linkerd diagnostics gehen weiter – sie kommen per Port-Forward über localhost, das der Proxy immer zulässt.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Der Init-Container aus Tag 2

An Tag 2 lief migrate ohne nativen Sidecar vor dem Proxy. Jetzt mit der Identität von notes-api, also mit allen Rechten – eigentlich:

cat > migrate-alt.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata: {name: migrate-alt, namespace: notes}
spec:
  replicas: 1
  selector: {matchLabels: {app: migrate-alt}}
  template:
    metadata:
      labels: {app: migrate-alt}
      annotations:
        config.beta.linkerd.io/proxy-enable-native-sidecar: "false"
    spec:
      serviceAccountName: notes-api
      initContainers:
      - name: migrate
        image: ghcr.io/thomaszachmann/notes-api:0.7.1
        args: [migrate]
        env:
        - name: NOTES_DB_URL
          valueFrom: {secretKeyRef: {name: notes-db, key: url}}
      containers:
      - name: pause
        image: registry.k8s.io/pause:3.10
EOF
kubectl apply -f migrate-alt.yaml
sleep 40
kubectl -n notes get pod -l app=migrate-alt
kubectl -n notes logs deploy/migrate-alt -c migrate --tail=1
linkerd diagnostics proxy-metrics -n notes po/postgres-0 \
  | grep '^inbound_tcp_authz_deny_total' | grep -oE 'no_tls_reason="[^"]*"|\} [0-9]+'

Erwartet (gekürzt):

NAME                           READY   STATUS       RESTARTS      AGE
migrate-alt-5c97994d8b-s24vd   0/2     Init:Error   2 (34s ago)   40s
time=2026-11-19T16:22:50.801Z level=ERROR msg="database unreachable" source=env
err="failed to connect to `user=notes database=notes`: 10.109.208.153:5432 (postgres):
failed to receive message: unexpected EOF"
no_tls_reason="port_skipped"
} 5

Der richtige ServiceAccount nützt nichts: migrate läuft, bevor es einen Proxy gibt, also ohne Zertifikat. Postgres sieht Klartext und lehnt ab. Mit nativem Sidecar:

kubectl -n notes patch deploy migrate-alt --type=json \
  -p '[{"op":"remove","path":"/spec/template/metadata/annotations"}]'
kubectl -n notes rollout status deploy/migrate-alt --timeout=120s
kubectl -n notes logs deploy/migrate-alt -c migrate --tail=1
kubectl -n notes delete deploy migrate-alt

Erwartet (gekürzt):

deployment "migrate-alt" successfully rolled out
time=2026-11-19T16:23:26.437Z level=INFO msg="migration complete" table=notes

Fortschritt speichern? Kostenlos registrieren

Drill 8: Bilanz

kubectl -n notes logs deploy/last -c last --since=55s | awk '{print $2, $3}' \
  | sort | uniq -c
linkerd viz stat -n notes deploy
linkerd viz authz -n notes deploy/web
linkerd check --proxy -n notes 2>&1 | tail -1

Erwartet (gekürzt, Zahlen schwanken):

     80 /api/notes 200
     29 /flaky 200
     11 /flaky 500
NAME        MESHED   SUCCESS      RPS   LATENCY_P50   LATENCY_P95   LATENCY_P99
helper         2/2    86.32%   1.6rps           1ms          32ms          38ms
last           1/1   100.00%   0.3rps           1ms          49ms          50ms
notes-api      2/2   100.00%   2.2rps           6ms          39ms          89ms
web            2/2    92.12%   2.8rps          14ms          92ms         170ms
ROUTE    SERVER       AUTHORIZATION                             UNAUTHORIZED  SUCCESS
default  proxy-admin  authorizationpolicy/admin-von-prometheus        0.0rps  100.00%
probe    proxy-admin  default/probe                                   0.0rps  100.00%
default  web-http     authorizationpolicy/web-von-last                0.0rps   89.92%
Status check results are √

Gleiche Quoten wie an Tag 0, kein audit, kein default:all-unauthenticated mehr. Im Grafana-Dashboard „Linkerd Deployment“ siehst du eine Lücke von wenigen Minuten (Drill 6), danach laufen die Kurven weiter. Diese Policies bleiben für den Rest des Trainings aktiv.

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

  1. Zeig alle Policy-Ressourcen in notes mit einem Befehl. Zeitziel: 20 s
  2. Zeig, welche Default-Policy der Proxy von helper hat. Zeitziel: 45 s
  3. Zeig, welche Autorisierungen der Proxy von notes-api für Port 8080 kennt. Zeitziel: 45 s
  4. Weise nach, dass fremd nicht mehr in die Datenbank kommt. Zeitziel: 30 s

Lösung

kubectl -n notes get server,authorizationpolicy,meshtlsauthentication,\
networkauthentication
kubectl -n notes get pod -l app=helper -o yaml | grep -m1 -A1 INBOUND_DEFAULT_POLICY
P=$(kubectl -n notes get pod -l app=notes-api -o name | head -1)
linkerd diagnostics policy -n notes $P 8080 -o json \
  | jq -r '.authorizations[].labels.name'
kubectl -n tag06 exec deploy/fremd -c psql -- psql $DB -tAc 'select 1'

Erwartet (gekürzt):

NAME                                      PORT            PROTOCOL   ACCESS POLICY
server.policy.linkerd.io/helper-http      http            HTTP/1     deny
server.policy.linkerd.io/notes-api-http   http            HTTP/1     deny
server.policy.linkerd.io/postgres         postgres        opaque     deny
server.policy.linkerd.io/proxy-admin      linkerd-admin   HTTP/1     deny
server.policy.linkerd.io/web-http         http            HTTP/1     deny
      - name: LINKERD2_PROXY_INBOUND_DEFAULT_POLICY
        value: deny
notes-api-von-web
psql: error: connection to server at "postgres.notes" (10.109.208.153), port 5432
failed: server closed the connection unexpectedly

linkerd diagnostics policy will einen Pod oder Service, kein Deployment.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

kubectl -n tag06 exec deploy/fremd -c curl -- curl -s -o /dev/null \
  -w '%{http_code}\n' http://helper.notes/get

Erwartet: 403

kubectl -n notes get server -o custom-columns=NAME:.metadata.name,\
POLICY:.spec.accessPolicy

Erwartet: fünf Server, alle deny (ohne Angabe bei proxy-admin gilt deny).

kubectl -n notes logs deploy/last -c last --since=55s | awk '{print $2, $3}' \
  | sort | uniq -c

Erwartet: /api/notes nur 200, /flaky um 70 Prozent 200.

Challenge

Leg in tag06 eine Kopie von helper an (ServiceAccount helper, eine Replika) und erlaube fremd dort nur GET /get. Die Readiness-Probe darf nicht brechen.

Hinweis: Sobald an einem Server eine Route hängt, erlaubt Linkerd die Probes nicht mehr von selbst – und das Kubelet hat keine Identität.

Lösung

kubectl -n tag06 create serviceaccount helper
sed -e 's/namespace: notes/namespace: tag06/' -e 's/replicas: 2/replicas: 1/' \
  ~/linkerd/tag00/helper.yaml > helper-kopie.yaml
kubectl apply -f helper-kopie.yaml
kubectl -n tag06 set serviceaccount deploy/helper helper
kubectl -n tag06 rollout status deploy/helper --timeout=120s
cat > challenge.yaml <<'EOF'
apiVersion: policy.linkerd.io/v1beta3
kind: Server
metadata: {name: helper-http, namespace: tag06}
spec:
  podSelector: {matchLabels: {app: helper}}
  port: http
  proxyProtocol: HTTP/1
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: helper-get, namespace: tag06}
spec:
  parentRefs:
  - {group: policy.linkerd.io, kind: Server, name: helper-http}
  rules:
  - matches:
    - path: {type: Exact, value: /get}
      method: GET
---
apiVersion: policy.linkerd.io/v1alpha1
kind: MeshTLSAuthentication
metadata: {name: fremd, namespace: tag06}
spec:
  identityRefs: [{kind: ServiceAccount, name: fremd}]
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata: {name: helper-get-von-fremd, namespace: tag06}
spec:
  targetRef: {group: gateway.networking.k8s.io, kind: HTTPRoute, name: helper-get}
  requiredAuthenticationRefs:
  - {group: policy.linkerd.io, kind: MeshTLSAuthentication, name: fremd}
EOF
kubectl apply -f challenge.yaml
sleep 45
kubectl -n tag06 get pods -l app=helper
kubectl -n tag06 get events --field-selector reason=Unhealthy | tail -1

Erwartet (gekürzt):

NAME                      READY   STATUS    RESTARTS   AGE
helper-79d57fbbbb-xx9jg   1/2     Running   0          54s
8s   Warning   Unhealthy   pod/helper-79d57fbbbb-xx9jg   Readiness probe failed: HTTP
probe failed with statuscode: 404

Die Probe /status/200 trifft keine Route mehr: 404. Also eine Route für die Probe und eine Regel für das Kubelet. Woher es kommt, zeigt das Log, sobald die Route steht:

cat > probe-route.yaml <<'EOF'
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata: {name: helper-probe, namespace: tag06}
spec:
  parentRefs:
  - {group: policy.linkerd.io, kind: Server, name: helper-http}
  rules:
  - matches:
    - path: {type: Exact, value: /status/200}
      method: GET
EOF
kubectl apply -f probe-route.yaml
sleep 25
kubectl -n tag06 logs deploy/helper -c linkerd-proxy --since=20s \
  | grep 'Request denied' | grep -oE 'route.name=[^ ]*|client.ip=[0-9.]*' | sort -u
kubectl get ciliumnodes \
  -o jsonpath='{..addresses[?(@.type=="CiliumInternalIP")].ip}{"\n"}'

Erwartet:

client.ip=10.0.1.116
route.name=helper-probe
10.0.0.88 10.0.1.116 10.0.2.241

Bei Cilium kommt das Kubelet über die Adresse cilium_host des Nodes. Die trägst du ein (bei dir andere IPs):

cat > kubelet.yaml <<'EOF'
apiVersion: policy.linkerd.io/v1alpha1
kind: NetworkAuthentication
metadata: {name: kubelet, namespace: tag06}
spec:
  networks:
  - cidr: 10.0.0.88/32
  - cidr: 10.0.1.116/32
  - cidr: 10.0.2.241/32
---
apiVersion: policy.linkerd.io/v1alpha1
kind: AuthorizationPolicy
metadata: {name: helper-probe-von-kubelet, namespace: tag06}
spec:
  targetRef: {group: gateway.networking.k8s.io, kind: HTTPRoute, name: helper-probe}
  requiredAuthenticationRefs:
  - {group: policy.linkerd.io, kind: NetworkAuthentication, name: kubelet}
EOF
kubectl apply -f kubelet.yaml
sleep 25
kubectl -n tag06 get pods -l app=helper
for u in /get /status/200 /headers; do
  kubectl -n tag06 exec deploy/fremd -c curl -- curl -s -o /dev/null \
    -w "$u %{http_code}\n" http://helper.tag06$u
done

Erwartet:

NAME                      READY   STATUS    RESTARTS   AGE
helper-79d57fbbbb-xx9jg   2/2     Running   0          2m3s
/get 200
/status/200 403
/headers 404

/get erlaubt, die Probe nur für das Kubelet, alles andere trifft keine Route (404).

Fortschritt speichern? Kostenlos registrieren

Aufräumen

kubectl delete namespace tag06

Die Policies in notes bleiben.

Interview-Notiz

  • Wie führst du Autorisierung ohne Ausfall ein? Server mit accessPolicy: audit, Regeln anlegen, Audit nach Client-Identität auswerten, dann deny. Zuletzt die Default-Policy des Namespace auf deny für neue Ports.
  • Was passiert mit Probes und Prometheus? Probes erlaubt Linkerd automatisch, solange der Server keine Routen hat. Prometheus ohne Proxy braucht eine NetworkAuthentication auf den Admin-Port 4191.
  • 403 oder Verbindungsabbruch? HTTP bekommt 403 vom Proxy, Opaque/TCP wird geschlossen.

Enterprise-Notiz

  • Policies gehören ins Git neben die Deployments; jede neue Kante ist ein Review.
  • Default-Policy clusterweit per Helm (proxy.defaultInboundPolicy) statt pro Namespace – wirkt aber erst nach Neustart aller Pods.
  • Prometheus ins Mesh holen und per Identität erlauben statt Pod-Netz freizugeben.
  • Alarm auf inbound_http_authz_deny_total und inbound_tcp_authz_deny_total: Ein Anstieg ist entweder ein Angriff oder ein vergessener legitimer Client.
  • Jobs, Migrationen und Backups mit nativem Sidecar betreiben, sonst laufen sie unter Default-Deny gegen die Wand.