Kubernetes autentifikacija sa GitHub OAuth i Dex

Predstavljam vašoj pažnji tutorijal za generisanje pristupa Kubernetes klasteru koristeći Dex, dex-k8s-authenticator i GitHub.

Kubernetes autentifikacija sa GitHub OAuth i Dex
Lokalni meme iz Kubernetes chata na ruskom jeziku telegram

Uvod

Koristimo Kubernetes za kreiranje dinamičnih okruženja za razvojni i QA tim. Dakle, želimo im dati pristup klasteru i za kontrolnu ploču i za kubectl. Za razliku od OpenShift-a, vanilla Kubernetes nema izvornu autentifikaciju, pa za to koristimo alate treće strane.

U ovoj konfiguraciji koristimo:

  • dex-k8s-autentikator  — web aplikacija za generisanje kubectl konfiguracije
  • dex — OpenID Connect provajder
  • GitHub - jednostavno zato što koristimo GitHub u našoj kompaniji

Pokušali smo koristiti Google OIDC, ali nažalost nije uspio da ih započnemo sa grupama, tako da nam je integracija sa GitHub-om sasvim odgovarala. Bez grupnog mapiranja, neće biti moguće kreirati RBAC politike zasnovane na grupama.

Dakle, kako naš Kubernetes proces autorizacije funkcionira u vizualnom prikazu:

Kubernetes autentifikacija sa GitHub OAuth i Dex
Proces autorizacije

Malo više detalja i tačku po tačku:

  1. Korisnik se prijavljuje na dex-k8s-authenticator (login.k8s.example.com)
  2. dex-k8s-authenticator prosljeđuje zahtjev Dexu (dex.k8s.example.com)
  3. Dex preusmjerava na stranicu za prijavu na GitHub
  4. GitHub generiše potrebne informacije o autorizaciji i vraća ih u Dex
  5. Dex prosljeđuje primljene informacije dex-k8s-authenticatoru
  6. Korisnik prima OIDC token od GitHub-a
  7. dex-k8s-authenticator dodaje token u kubeconfig
  8. kubectl prosljeđuje token KubeAPIServeru
  9. KubeAPIServer vraća pristup kubectl-u na osnovu proslijeđenog tokena
  10. Korisnik dobija pristup iz kubectl

Pripremne radnje

Naravno, već imamo instaliran Kubernetes klaster (k8s.example.com), a također dolazi s unaprijed instaliranim HELM-om. Imamo i organizaciju na GitHubu (super-org).
Ako nemate HELM, instalirajte ga vrlo jednostavno.

Prvo moramo postaviti GitHub.

Idite na stranicu postavki organizacije, (https://github.com/organizations/super-org/settings/applications) i kreirajte novu aplikaciju (Authorized OAuth App):
Kubernetes autentifikacija sa GitHub OAuth i Dex
Kreiranje nove aplikacije na GitHub-u

Popunite polja potrebnim URL-ovima, na primjer:

  • URL početne stranice: https://dex.k8s.example.com
  • URL za povratni poziv autorizacije: https://dex.k8s.example.com/callback

Budite oprezni sa vezama, važno je da ne izgubite kose crte.

Kao odgovor na popunjen obrazac, GitHub će generirati Client ID и Client secret, čuvajte ih na sigurnom mjestu, bit će nam korisni (npr svod za čuvanje tajni):

Client ID: 1ab2c3d4e5f6g7h8
Client secret: 98z76y54x32w1

Pripremite DNS zapise za poddomene login.k8s.example.com и dex.k8s.example.com, kao i SSL certifikati za ulaz.

Kreirajmo SSL certifikate:

cat <<EOF | kubectl create -f -
apiVersion: certmanager.k8s.io/v1alpha1
kind: Certificate
metadata:
  name: cert-auth-dex
  namespace: kube-system
spec:
  secretName: cert-auth-dex
  dnsNames:
    - dex.k8s.example.com
  acme:
    config:
    - http01:
        ingressClass: nginx
      domains:
      - dex.k8s.example.com
  issuerRef:
    name: le-clusterissuer
    kind: ClusterIssuer
---
apiVersion: certmanager.k8s.io/v1alpha1
kind: Certificate
metadata:
  name: cert-auth-login
  namespace: kube-system
spec:
  secretName: cert-auth-login
  dnsNames:
    - login.k8s.example.com
  acme:
    config:
    - http01:
        ingressClass: nginx
      domains:
      - login.k8s.example.com
  issuerRef:
    name: le-clusterissuer
    kind: ClusterIssuer
EOF
kubectl describe certificates cert-auth-dex -n kube-system
kubectl describe certificates cert-auth-login -n kube-system

ClusterIssuer s naslovom le-clusterissuer bi već trebao postojati, ali ako ne, kreirajte ga pomoću HELM-a:

helm install --namespace kube-system -n cert-manager stable/cert-manager
cat << EOF | kubectl create -f -
apiVersion: certmanager.k8s.io/v1alpha1
kind: ClusterIssuer
metadata:
  name: le-clusterissuer
  namespace: kube-system
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: [email protected]
    privateKeySecretRef:
      name: le-clusterissuer
    http01: {}
EOF

Konfiguracija KubeAPIServera

Da bi kubeAPIServer radio, morate konfigurirati OIDC i ažurirati klaster:

kops edit cluster
...
  kubeAPIServer:
    anonymousAuth: false
    authorizationMode: RBAC
    oidcClientID: dex-k8s-authenticator
    oidcGroupsClaim: groups
    oidcIssuerURL: https://dex.k8s.example.com/
    oidcUsernameClaim: email
kops update cluster --yes
kops rolling-update cluster --yes

Koristimo kops za postavljanje klastera, ali ovo funkcionira slično za drugi menadžeri klastera.

Dex konfiguracija i dex-k8s-autentikator

Da bi Dex radio, morate imati certifikat i ključ od Kubernetes mastera, hajde da ga uzmemo odatle:

sudo cat /srv/kubernetes/ca.{crt,key}
-----BEGIN CERTIFICATE-----
AAAAAAAAAAABBBBBBBBBBCCCCCC
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
DDDDDDDDDDDEEEEEEEEEEFFFFFF
-----END RSA PRIVATE KEY-----

Hajde da klonimo dex-k8s-authenticator spremište:

git clone [email protected]:mintel/dex-k8s-authenticator.git
cd dex-k8s-authenticator/

Koristeći datoteke vrijednosti, možemo fleksibilno konfigurirati varijable za naše HELM grafikoni.

Hajde da opišemo konfiguraciju za Dex:

cat << EOF > values-dex.yml
global:
  deployEnv: prod
tls:
  certificate: |-
    -----BEGIN CERTIFICATE-----
    AAAAAAAAAAABBBBBBBBBBCCCCCC
    -----END CERTIFICATE-----
  key: |-
    -----BEGIN RSA PRIVATE KEY-----
    DDDDDDDDDDDEEEEEEEEEEFFFFFF
    -----END RSA PRIVATE KEY-----
ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: nginx
    kubernetes.io/tls-acme: "true"
  path: /
  hosts:
    - dex.k8s.example.com
  tls:
    - secretName: cert-auth-dex
      hosts:
        - dex.k8s.example.com
serviceAccount:
  create: true
  name: dex-auth-sa
config: |
  issuer: https://dex.k8s.example.com/
  storage: # https://github.com/dexidp/dex/issues/798
    type: sqlite3
    config:
      file: /var/dex.db
  web:
    http: 0.0.0.0:5556
  frontend:
    theme: "coreos"
    issuer: "Example Co"
    issuerUrl: "https://example.com"
    logoUrl: https://example.com/images/logo-250x25.png
  expiry:
    signingKeys: "6h"
    idTokens: "24h"
  logger:
    level: debug
    format: json
  oauth2:
    responseTypes: ["code", "token", "id_token"]
    skipApprovalScreen: true
  connectors:
  - type: github
    id: github
    name: GitHub
    config:
      clientID: $GITHUB_CLIENT_ID
      clientSecret: $GITHUB_CLIENT_SECRET
      redirectURI: https://dex.k8s.example.com/callback
      orgs:
      - name: super-org
        teams:
        - team-red
  staticClients:
  - id: dex-k8s-authenticator
    name: dex-k8s-authenticator
    secret: generatedLongRandomPhrase
    redirectURIs:
      - https://login.k8s.example.com/callback/
envSecrets:
  GITHUB_CLIENT_ID: "1ab2c3d4e5f6g7h8"
  GITHUB_CLIENT_SECRET: "98z76y54x32w1"
EOF

I za dex-k8s-authenticator:

cat << EOF > values-auth.yml
global:
  deployEnv: prod
dexK8sAuthenticator:
  clusters:
  - name: k8s.example.com
    short_description: "k8s cluster"
    description: "Kubernetes cluster"
    issuer: https://dex.k8s.example.com/
    k8s_master_uri: https://api.k8s.example.com
    client_id: dex-k8s-authenticator
    client_secret: generatedLongRandomPhrase
    redirect_uri: https://login.k8s.example.com/callback/
    k8s_ca_pem: |
      -----BEGIN CERTIFICATE-----
      AAAAAAAAAAABBBBBBBBBBCCCCCC
      -----END CERTIFICATE-----
ingress:
  enabled: true
  annotations:
    kubernetes.io/ingress.class: nginx
    kubernetes.io/tls-acme: "true"
  path: /
  hosts:
    - login.k8s.example.com
  tls:
    - secretName: cert-auth-login
      hosts:
        - login.k8s.example.com
EOF

Instalirajte Dex i dex-k8s-authenticator:

helm install -n dex --namespace kube-system --values values-dex.yml charts/dex
helm install -n dex-auth --namespace kube-system --values values-auth.yml charts/dex-k8s-authenticator

Provjerimo funkcionalnost servisa (Dex bi trebao vratiti kod 400, a dex-k8s-authenticator bi trebao vratiti kod 200):

curl -sI https://dex.k8s.example.com/callback | head -1
HTTP/2 400
curl -sI https://login.k8s.example.com/ | head -1
HTTP/2 200

RBAC konfiguracija

Kreiramo ClusterRole za grupu, u našem slučaju s pristupom samo za čitanje:

cat << EOF | kubectl create -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-read-all
rules:
  -
    apiGroups:
      - ""
      - apps
      - autoscaling
      - batch
      - extensions
      - policy
      - rbac.authorization.k8s.io
      - storage.k8s.io
    resources:
      - componentstatuses
      - configmaps
      - cronjobs
      - daemonsets
      - deployments
      - events
      - endpoints
      - horizontalpodautoscalers
      - ingress
      - ingresses
      - jobs
      - limitranges
      - namespaces
      - nodes
      - pods
      - pods/log
      - pods/exec
      - persistentvolumes
      - persistentvolumeclaims
      - resourcequotas
      - replicasets
      - replicationcontrollers
      - serviceaccounts
      - services
      - statefulsets
      - storageclasses
      - clusterroles
      - roles
    verbs:
      - get
      - watch
      - list
  - nonResourceURLs: ["*"]
    verbs:
      - get
      - watch
      - list
  - apiGroups: [""]
    resources: ["pods/exec"]
    verbs: ["create"]
EOF

Kreirajmo konfiguraciju za ClusterRoleBinding:

cat <<EOF | kubectl create -f -
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
  name: dex-cluster-auth
  namespace: kube-system
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-read-all
subjects:
  kind: Group
  name: "super-org:team-red"
EOF

Sada smo spremni za testiranje.

Testovi

Idite na stranicu za prijavu (https://login.k8s.example.com) i prijavite se koristeći svoj GitHub račun:

Kubernetes autentifikacija sa GitHub OAuth i Dex
Stranica za prijavu

Kubernetes autentifikacija sa GitHub OAuth i Dex
Stranica za prijavu je preusmjerena na GitHub

Kubernetes autentifikacija sa GitHub OAuth i Dex
 Slijedite generirana uputstva za pristup

Nakon kopiranja sa web stranice, možemo koristiti kubectl za upravljanje našim resursima klastera:

kubectl get po
NAME                READY   STATUS    RESTARTS   AGE
mypod               1/1     Running   0          3d

kubectl delete po mypod
Error from server (Forbidden): pods "mypod" is forbidden: User "[email protected]" cannot delete pods in the namespace "default"

I funkcionira, svi korisnici GitHub-a u našoj organizaciji mogu vidjeti resurse i prijaviti se na podove, ali nemaju prava da ih mijenjaju.

izvor: www.habr.com

Dodajte komentar