Fíordheimhniú Kubernetes le GitHub OAuth agus Dex

Cuirim teagaisc i láthair d’aird chun rochtain a ghiniúint ar bhraisle Kubernetes ag baint úsáide as Dex, dex-k8s-authenticator agus GitHub.

Fíordheimhniú Kubernetes le GitHub OAuth agus Dex
Meme áitiúil ó Kubernetes Rúisis-chomhrá i Telegram

Réamhrá

Bainimid úsáid as Kubernetes chun timpeallachtaí dinimiciúla a chruthú don fhoireann forbartha agus don QA. Mar sin ba mhaith linn rochtain a thabhairt dóibh ar an mbraisle don deais agus don kubectl araon. Murab ionann agus an OpenShift céanna, níl fíordheimhniú dúchais ag vanilla Kubernetes, mar sin úsáidimid uirlisí tríú páirtí le haghaidh seo.

Sa chumraíocht seo úsáidimid:

  • dex-k8s-fhíordheimhnitheoir  - feidhmchlár gréasáin chun kubectl config a ghiniúint
  • Dex - Soláthraí OpenID Connect
  • GitHub - go simplí toisc go n-úsáideann muid GitHub inár gcuideachta

Rinneamar iarracht Google OIDC a úsáid, ach ar an drochuair rinneamar theip chun tús a chur leo le grúpaí, agus mar sin d'oirfeadh an comhtháthú le GitHub go breá dúinn. Gan léarscáiliú grúpa, ní bheidh sé indéanta beartais RBAC grúpabhunaithe a chruthú.

Mar sin, conas a oibríonn ár bpróiseas údaraithe Kubernetes i léiriú amhairc:

Fíordheimhniú Kubernetes le GitHub OAuth agus Dex
Próiseas údaraithe

Beagán níos mó sonraí agus pointe ar phointe:

  1. Logálann an t-úsáideoir isteach i dex-k8s-authenticator (login.k8s.example.com)
  2. atreoraíonn dex-k8s-authenticator an t-iarratas chuig Dex (dex.k8s.example.com)
  3. Déanann Dex atreorú chuig leathanach logáil isteach GitHub
  4. Gineann GitHub an fhaisnéis údaraithe riachtanach agus cuireann sé ar ais chuig Dex í
  5. Cuireann Dex an fhaisnéis faighte ar aghaidh chuig dex-k8s-authenticator
  6. Faigheann an t-úsáideoir comhartha OIDC ó GitHub
  7. cuireann dex-k8s-authenticator comhartha chuig kubeconfig
  8. Gabhann kubectl comhartha chuig KubeAPIServer
  9. Tugann KubeAPIServer bunaithe ar an chomhartha a ritheadh ​​rochtain ar kubectl ar ais
  10. Rochtain úsáideora ó kubectl

Gníomhaíochtaí Ullmhúcháin

Ar ndóigh, tá braisle Kubernetes suiteáilte againn cheana féin (k8s.example.com), chomh maith le HELM réamhshuiteáilte. Tá eagraíocht againn freisin ar GitHub (super-org).
Mura bhfuil HELM agat, suiteáil é an-simplí.

Ar dtús ní mór dúinn GitHub a bhunú.

Téigh go dtí an leathanach socruithe eagraíochta, (https://github.com/organizations/super-org/settings/applications) agus cruthaigh feidhmchlár nua (Aip OAuth Údaraithe):
Fíordheimhniú Kubernetes le GitHub OAuth agus Dex
Cruthaigh aip nua ar GitHub

Líon isteach na réimsí leis na URLanna riachtanacha, mar shampla:

  • URL an leathanaigh baile: https://dex.k8s.example.com
  • URL aisghlao údaraithe: https://dex.k8s.example.com/callback

Bí cúramach le naisc, tá sé tábhachtach gan slais a chailleadh.

Mar fhreagra ar an bhfoirm chomhlánaithe, ginfidh GitHub Client ID и Client secret, iad a shábháil in áit shábháilte, beidh siad úsáideach dúinn (mar shampla, úsáidimid Bóthair chun rúin a choimeád):

Client ID: 1ab2c3d4e5f6g7h8
Client secret: 98z76y54x32w1

Ullmhaigh taifid DNS le haghaidh fofhearainn login.k8s.example.com и dex.k8s.example.com, chomh maith le deimhnithe SSL le haghaidh ionghabhálacha.

Cruthaimis teastais SSL:

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

Eisitheoir Braisle le teideal le-clusterissuer Ba chóir go mbeadh sé ann cheana féin, mura bhfuil, cruthaigh é ag baint úsáide as HELM:

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

Cumraíocht KubeAPISserver

Le go n-oibreoidh kubeAPIServer, ní mór duit OIDC a chumrú agus an braisle a uasghrádú:

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

Úsáidimid cóbanna chun braislí a leathnú, ach oibríonn sé ar an mbealach céanna le haghaidh bainisteoirí braisle eile.

Cumraíocht Dex agus dex-k8s-authenticator

Chun Dex a bheith ag obair, ní mór duit teastas agus eochair a bheith agat ó mháistir Kubernetes, tarraingeoimid amach as sin é:

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

Clón an stór dex-k8s-authenticator:

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

Le cabhair ó chomhaid luachanna, is féidir linn athróga a shocrú go solúbtha dár gcuid Cairteacha HELM.

Déanaimis cur síos ar an chumraíocht do 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

Agus le haghaidh 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

Suiteáil Dex agus 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

Déanaimis inseirbhísiúlacht na seirbhísí a sheiceáil (ba cheart do Dex cód 400 a thabhairt ar ais, agus ba cheart do dex-k8s-authenticator cód 200 a sheoladh ar ais):

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

cumraíocht RBAC

Cruthaigh Ról Braisle don ghrúpa, inár gcás le rochtain inléite amháin:

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

Cruthaímid cumraíocht le haghaidh 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

Anois táimid réidh le haghaidh tástála.

Tástálacha

Téigh go dtí an leathanach logáil isteachhttps://login.k8s.example.com) agus logáil isteach le cuntas GitHub:

Fíordheimhniú Kubernetes le GitHub OAuth agus Dex
Leathanach údaraithe

Fíordheimhniú Kubernetes le GitHub OAuth agus Dex
Leathanach údaraithe arna atreorú chuig GitHub

Fíordheimhniú Kubernetes le GitHub OAuth agus Dex
 Lean na treoracha ginte chun rochtain a fháil

Tar éis cóip-ghreamú ón leathanach gréasáin, is féidir linn kubectl a úsáid chun ár n-acmhainní braisle a bhainistiú:

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"

Agus oibríonn sé, is féidir le gach úsáideoir GitHub inár n-eagraíocht acmhainní a fheiceáil agus logáil isteach i pods, ach níl cead acu iad a athrú.

Foinse: will.com

Add a comment