From 50a2c277be084fefcc7a53c9309716771c003ea8 Mon Sep 17 00:00:00 2001 From: Oleksandr K Date: Wed, 28 Feb 2024 17:34:05 +0100 Subject: [PATCH] feat: support keystone-auth (#297) * feat: support keystone-auth * render template * fix unittest * fix flake and isort issue * fix manifest path * fix jinja env initi * fix calico path * fix flake8 error * Configuration on K8S master for authentication and/or authorization * fix lint errors * workaround for jsonpath for slices * add missing webhook file content * mount cloud ca in keystone-webhook for tls support and add /v3 in identity url * fix indentation * support http endpoints * write k8s-keystone-auth helm chart and use helm template * revert manifest changes * fix template output * set namespace for helm template rendered manifests * set ca cert optionally * set hostnetwork in keystone-auth chart * fix helm template rendering * fix volume mount * fix lint errors * remove static manifests * add webhook file * resolve comments * fix typo --------- Co-authored-by: okozachenko1203 --- .gitignore | 1 + .../charts/k8s-keystone-auth/.helmignore | 23 ++++ .../charts/k8s-keystone-auth/Chart.yaml | 8 ++ .../k8s-keystone-auth/templates/NOTES.txt | 1 + .../k8s-keystone-auth/templates/_helpers.tpl | 62 +++++++++ .../templates/clusterrole.yaml | 21 +++ .../templates/clusterrolebinding.yaml | 19 +++ .../templates/configmap-policy.yaml | 8 ++ .../templates/configmap-sync.yaml | 9 ++ .../templates/daemonset.yaml | 100 ++++++++++++++ .../templates/secret-ca.yaml | 10 ++ .../k8s-keystone-auth/templates/service.yaml | 15 ++ .../templates/serviceaccount.yaml | 11 ++ .../charts/k8s-keystone-auth/values.yaml | 94 +++++++++++++ magnum_cluster_api/helm.py | 48 ++++++- .../manifests/keystone-auth/webhook.yaml | 17 +++ magnum_cluster_api/resources.py | 130 ++++++++++++++++-- magnum_cluster_api/utils.py | 24 ++++ 18 files changed, 590 insertions(+), 11 deletions(-) create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/.helmignore create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/Chart.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/NOTES.txt create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/_helpers.tpl create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrole.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrolebinding.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-policy.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-sync.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/daemonset.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/secret-ca.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/service.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/templates/serviceaccount.yaml create mode 100644 magnum_cluster_api/charts/k8s-keystone-auth/values.yaml create mode 100644 magnum_cluster_api/manifests/keystone-auth/webhook.yaml diff --git a/.gitignore b/.gitignore index e55d9f98..55dd7f8f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ __pycache__ dist magnum_cluster_api/charts/* !magnum_cluster_api/charts/.gitkeep +!magnum_cluster_api/charts/k8s-keystone-auth site diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/.helmignore b/magnum_cluster_api/charts/k8s-keystone-auth/.helmignore new file mode 100644 index 00000000..0e8a0eb3 --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/.helmignore @@ -0,0 +1,23 @@ +# Patterns to ignore when building packages. +# This supports shell glob matching, relative path matching, and +# negation (prefixed with !). Only one pattern per line. +.DS_Store +# Common VCS dirs +.git/ +.gitignore +.bzr/ +.bzrignore +.hg/ +.hgignore +.svn/ +# Common backup files +*.swp +*.bak +*.tmp +*.orig +*~ +# Various IDEs +.project +.idea/ +*.tmproj +.vscode/ diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/Chart.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/Chart.yaml new file mode 100644 index 00000000..804ebaae --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/Chart.yaml @@ -0,0 +1,8 @@ +apiVersion: v2 +name: k8s-keystone-auth +description: A Helm chart for k8s-keystone-auth +type: application +version: 0.1.0 +appVersion: v1.29.0 +sources: +- https://github.com/kubernetes/cloud-provider-openstack/ diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/NOTES.txt b/magnum_cluster_api/charts/k8s-keystone-auth/templates/NOTES.txt new file mode 100644 index 00000000..596ff66d --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/NOTES.txt @@ -0,0 +1 @@ +Here is a reference https://github.com/kubernetes/cloud-provider-openstack/blob/master/docs/keystone-auth/using-keystone-webhook-authenticator-and-authorizer.md diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/_helpers.tpl b/magnum_cluster_api/charts/k8s-keystone-auth/templates/_helpers.tpl new file mode 100644 index 00000000..84b3a179 --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/_helpers.tpl @@ -0,0 +1,62 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "k8s-keystone-auth.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). +If release name contains chart name it will be used as a full name. +*/}} +{{- define "k8s-keystone-auth.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Create chart name and version as used by the chart label. +*/}} +{{- define "k8s-keystone-auth.chart" -}} +{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Common labels +*/}} +{{- define "k8s-keystone-auth.labels" -}} +helm.sh/chart: {{ include "k8s-keystone-auth.chart" . }} +{{ include "k8s-keystone-auth.selectorLabels" . }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Selector labels +*/}} +{{- define "k8s-keystone-auth.selectorLabels" -}} +app.kubernetes.io/name: {{ include "k8s-keystone-auth.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- end }} + +{{/* +Create the name of the service account to use +*/}} +{{- define "k8s-keystone-auth.serviceAccountName" -}} +{{- if .Values.serviceAccount.create }} +{{- default (include "k8s-keystone-auth.fullname" .) .Values.serviceAccount.name }} +{{- else }} +{{- default "default" .Values.serviceAccount.name }} +{{- end }} +{{- end }} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrole.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrole.yaml new file mode 100644 index 00000000..dbfc64e0 --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrole.yaml @@ -0,0 +1,21 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + name: system:{{ include "k8s-keystone-auth.fullname" . }} + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +rules: + - apiGroups: + - "" + resources: + - configmaps + - services + - pods + verbs: + - get + - list + - watch diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrolebinding.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrolebinding.yaml new file mode 100644 index 00000000..66baddf2 --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/clusterrolebinding.yaml @@ -0,0 +1,19 @@ +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRoleBinding +metadata: + name: system:{{ include "k8s-keystone-auth.fullname" . }} + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + rbac.authorization.kubernetes.io/autoupdate: "true" + {{- toYaml . | nindent 4 }} + {{- end }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: ClusterRole + name: system:{{ include "k8s-keystone-auth.fullname" . }} +subjects: +- kind: ServiceAccount + name: {{ include "k8s-keystone-auth.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-policy.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-policy.yaml new file mode 100644 index 00000000..4cfbab3c --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-policy.yaml @@ -0,0 +1,8 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "k8s-keystone-auth.fullname" . }}-policy + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} +data: + policies: {{ toJson .Values.conf.policy | quote }} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-sync.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-sync.yaml new file mode 100644 index 00000000..dd125b2e --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/configmap-sync.yaml @@ -0,0 +1,9 @@ +apiVersion: v1 +kind: ConfigMap +metadata: + name: {{ include "k8s-keystone-auth.fullname" . }}-sync + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} +data: + syncConfig: | +{{ .Values.conf.sync_config | indent 4 }} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/daemonset.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/daemonset.yaml new file mode 100644 index 00000000..824a6fdf --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/daemonset.yaml @@ -0,0 +1,100 @@ +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: {{ include "k8s-keystone-auth.fullname" . }} + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} +spec: + selector: + matchLabels: + {{- include "k8s-keystone-auth.selectorLabels" . | nindent 6 }} + template: + metadata: + {{- with .Values.podAnnotations }} + annotations: + {{- toYaml . | nindent 8 }} + {{- end }} + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 8 }} + {{- with .Values.podLabels }} + {{- toYaml . | nindent 8 }} + {{- end }} + spec: + {{- with .Values.imagePullSecrets }} + imagePullSecrets: + {{- toYaml . | nindent 8 }} + {{- end }} + serviceAccountName: {{ include "k8s-keystone-auth.serviceAccountName" . }} + securityContext: + {{- toYaml .Values.podSecurityContext | nindent 8 }} + containers: + - name: {{ .Chart.Name }} + securityContext: + {{- toYaml .Values.securityContext | nindent 12 }} + image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}" + imagePullPolicy: {{ .Values.image.pullPolicy }} + args: + - ./bin/k8s-keystone-auth + - --tls-cert-file + - /etc/kubernetes/pki/apiserver.crt + - --tls-private-key-file + - /etc/kubernetes/pki/apiserver.key + - --policy-configmap-name + - {{ include "k8s-keystone-auth.fullname" . }}-policy + - --keystone-url + - {{ .Values.conf.auth_url }} + - --sync-configmap-name + - {{ include "k8s-keystone-auth.fullname" . }}-sync + {{- if not (empty .Values.conf.ca_cert) }} + - --keystone-ca-file + - /etc/kubernetes/cloud_ca.crt + {{- end }} + - --listen + - 127.0.0.1:8443 + ports: + - name: https + containerPort: {{ .Values.service.port }} + hostPort: {{ .Values.service.hostPort }} + protocol: TCP + resources: + {{- toYaml .Values.resources | nindent 12 }} + volumeMounts: + {{- if not (empty .Values.conf.ca_cert) }} + - mountPath: /etc/kubernetes/cloud_ca.crt + subPath: cloud_ca.crt + name: cloud-cert + readOnly: true + {{- end }} + - mountPath: /etc/kubernetes/pki + name: k8s-certs + readOnly: true + {{- with .Values.volumeMounts }} + {{- toYaml . | nindent 12 }} + {{- end }} + hostNetwork: true + volumes: + {{- if not (empty .Values.conf.ca_cert) }} + - name: cloud-cert + secret: + secretName: {{ include "k8s-keystone-auth.fullname" . }}-ca + defaultMode: 0444 + {{- end }} + - hostPath: + path: /etc/kubernetes/pki + type: DirectoryOrCreate + name: k8s-certs + {{- with .Values.volumes }} + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.affinity }} + affinity: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/secret-ca.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/secret-ca.yaml new file mode 100644 index 00000000..3dc25df6 --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/secret-ca.yaml @@ -0,0 +1,10 @@ +{{- if not (empty .Values.conf.ca_cert) }} +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "k8s-keystone-auth.fullname" . }}-ca + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} +stringData: + cloud_ca.crt: {{ .Values.conf.ca_cert }} +{{- end -}} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/service.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/service.yaml new file mode 100644 index 00000000..cd7797bd --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/service.yaml @@ -0,0 +1,15 @@ +apiVersion: v1 +kind: Service +metadata: + name: {{ include "k8s-keystone-auth.fullname" . }} + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} +spec: + type: {{ .Values.service.type }} + ports: + - port: {{ .Values.service.port }} + targetPort: {{ .Values.service.port }} + protocol: TCP + name: https + selector: + {{- include "k8s-keystone-auth.selectorLabels" . | nindent 4 }} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/templates/serviceaccount.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/templates/serviceaccount.yaml new file mode 100644 index 00000000..12b24eb3 --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/templates/serviceaccount.yaml @@ -0,0 +1,11 @@ +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "k8s-keystone-auth.serviceAccountName" . }} + labels: + {{- include "k8s-keystone-auth.labels" . | nindent 4 }} + {{- with .Values.serviceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +automountServiceAccountToken: {{ .Values.serviceAccount.automount }} diff --git a/magnum_cluster_api/charts/k8s-keystone-auth/values.yaml b/magnum_cluster_api/charts/k8s-keystone-auth/values.yaml new file mode 100644 index 00000000..d52d2b0e --- /dev/null +++ b/magnum_cluster_api/charts/k8s-keystone-auth/values.yaml @@ -0,0 +1,94 @@ +# Default values for k8s-keystone-auth. +# This is a YAML-formatted file. +# Declare variables to be passed into your templates. + +replicaCount: 1 + +image: + repository: registry.k8s.io/provider-os/k8s-keystone-auth + pullPolicy: IfNotPresent + # Overrides the image tag whose default is the chart appVersion. + tag: "" + +imagePullSecrets: [] +nameOverride: "" +fullnameOverride: "" + +conf: + auth_url: http://keystone:5000/v3 + # Specify the ca certificate body if needed. + ca_cert: ~ + sync_config: | + role-mappings: + - keystone-role: member + groups: [] + policy: "" + + +serviceAccount: + # Automatically mount a ServiceAccount's API credentials? + automount: true + # Annotations to add to the service account + annotations: {} + # The name of the service account to use. + # If not set and create is true, a name is generated using the fullname template + name: "" + +podAnnotations: {} +podLabels: {} + +podSecurityContext: {} + # fsGroup: 2000 + +securityContext: {} + # capabilities: + # drop: + # - ALL + # readOnlyRootFilesystem: true + # runAsNonRoot: true + # runAsUser: 1000 + +service: + type: ClusterIP + port: 8443 + hostPort: 8443 + +resources: {} + # We usually recommend not to specify default resources and to leave this as a conscious + # choice for the user. This also increases chances charts run on environments with little + # resources, such as Minikube. If you do want to specify resources, uncomment the following + # lines, adjust them as necessary, and remove the curly braces after 'resources:'. + # limits: + # cpu: 100m + # memory: 128Mi + # requests: + # cpu: 100m + # memory: 128Mi + +# Additional volumes on the output Deployment definition. +volumes: [] +# - name: foo +# secret: +# secretName: mysecret +# optional: false + +# Additional volumeMounts on the output Deployment definition. +volumeMounts: [] +# - name: foo +# mountPath: "/etc/foo" +# readOnly: true + +nodeSelector: + node-role.kubernetes.io/master: "" + +tolerations: + # Make sure the pod can be scheduled on master kubelet. + - effect: NoSchedule + operator: Exists + # Mark the pod as a critical add-on for rescheduling. + - key: CriticalAddonsOnly + operator: Exists + - effect: NoExecute + operator: Exists + +affinity: {} diff --git a/magnum_cluster_api/helm.py b/magnum_cluster_api/helm.py index aca014ff..5c0f3163 100644 --- a/magnum_cluster_api/helm.py +++ b/magnum_cluster_api/helm.py @@ -12,11 +12,13 @@ # License for the specific language governing permissions and limitations # under the License. +import itertools + import yaml from oslo_concurrency import processutils from oslo_log import log as logging -from magnum_cluster_api import exceptions +from magnum_cluster_api import exceptions, image_utils LOG = logging.getLogger(__name__) @@ -105,3 +107,47 @@ def __call__(self): raise exceptions.HelmReleaseNotFound(self.release_name) else: raise + + +class TemplateReleaseCommand(ReleaseCommand): + COMMAND = ["template"] + + def __init__(self, namespace, release_name, chart_ref, values={}): + super().__init__(namespace, release_name) + self.chart_ref = chart_ref + self.values = values + + def __call__(self, repository=None, replacements=[]): + try: + docs = [] + data, _ = super().__call__( + self.chart_ref, + "--values", + "-", + process_input=yaml.dump(self.values), + ) + + # NOTE(oleks): ClusterResourceSet fails to be applied without namespace set in resources. + # On the other hand, helm template doesn't output namespace. We set it manually + # until https://github.com/helm/helm/issues/10737 is fixed. + for doc in yaml.safe_load_all(data): + if doc["kind"] in ("DaemonSet", "Deployment", "StatefulSet"): + for container in itertools.chain( + doc["spec"]["template"]["spec"].get("initContainers", []), + doc["spec"]["template"]["spec"]["containers"], + ): + for src, dst in replacements: + container["image"] = container["image"].replace(src, dst) + if repository: + container["image"] = image_utils.get_image( + container["image"], repository + ) + + if doc["kind"] not in ("ClusterRole", "ClusterRoleBinding"): + doc["metadata"]["namespace"] = self.namespace + docs.append(doc) + return yaml.safe_dump_all(docs, default_flow_style=False) + + except processutils.ProcessExecutionError: + LOG.info("Helm template %s failed", self.release_name) + raise diff --git a/magnum_cluster_api/manifests/keystone-auth/webhook.yaml b/magnum_cluster_api/manifests/keystone-auth/webhook.yaml new file mode 100644 index 00000000..86a11bbb --- /dev/null +++ b/magnum_cluster_api/manifests/keystone-auth/webhook.yaml @@ -0,0 +1,17 @@ +--- +apiVersion: v1 +kind: Config +preferences: {} +clusters: + - cluster: + insecure-skip-tls-verify: true + server: https://127.0.0.1:8443/webhook + name: webhook +users: + - name: webhook +contexts: + - context: + cluster: webhook + user: webhook + name: webhook +current-context: webhook diff --git a/magnum_cluster_api/resources.py b/magnum_cluster_api/resources.py index d9be68ac..07a8643b 100644 --- a/magnum_cluster_api/resources.py +++ b/magnum_cluster_api/resources.py @@ -331,6 +331,37 @@ def get_object(self) -> pykube.ConfigMap: }, } + if utils.get_cluster_label_as_bool(self.cluster, "keystone_auth_enabled", True): + auth_url = osc.url_for( + service_type="identity", + interface=CONF.capi_client.endpoint_type.replace("URL", ""), + ) + data = { + **data, + **{ + "keystone-auth.yaml": helm.TemplateReleaseCommand( + namespace="kube-system", + release_name="k8s-keystone-auth", + chart_ref=os.path.join( + pkg_resources.resource_filename( + "magnum_cluster_api", "charts" + ), + "k8s-keystone-auth/", + ), + values={ + "conf": { + "auth_url": auth_url + + ("" if auth_url.endswith("/v3") else "/v3"), + "ca_file": utils.get_cloud_ca_cert(), + "policy": utils.get_keystone_auth_default_policy( + self.cluster + ), + }, + }, + )(repository=repository) + }, + } + return pykube.ConfigMap( self.api, { @@ -540,9 +571,13 @@ def get_object(self) -> pykube.Secret: class KubeadmControlPlaneTemplate(Base): def get_object(self) -> objects.KubeadmControlPlaneTemplate: manifests_path = pkg_resources.resource_filename( - "magnum_cluster_api.manifests", "audit" + "magnum_cluster_api", "manifests" ) - audit_policy = open(os.path.join(manifests_path, "policy.yaml")).read() + audit_policy = open(os.path.join(manifests_path, "audit/policy.yaml")).read() + keystone_auth_webhook = open( + os.path.join(manifests_path, "keystone-auth/webhook.yaml") + ).read() + return objects.KubeadmControlPlaneTemplate( self.api, { @@ -562,7 +597,15 @@ def get_object(self) -> objects.KubeadmControlPlaneTemplate: "cloud-provider": "external", "profiling": "false", }, - "extraVolumes": [], + "extraVolumes": [ + # Note(oleks): Add this as default as a workaround of the json patch limitation # noqa: E501 + # https://cluster-api.sigs.k8s.io/tasks/experimental-features/cluster-class/write-clusterclass#json-patches-tips--tricks + { + "name": "webhooks", + "hostPath": "/etc/kubernetes/webhooks", + "mountPath": "/etc/kubernetes/webhooks", + } + ], }, "controllerManager": { "extraArgs": { @@ -583,6 +626,15 @@ def get_object(self) -> objects.KubeadmControlPlaneTemplate: "content": base64.encode_as_text(audit_policy), "encoding": "base64", }, + { + "path": "/etc/kubernetes/webhooks/webhookconfig.yaml", + "owner": "root:root", + "permissions": "0644", + "content": base64.encode_as_text( + keystone_auth_webhook + ), + "encoding": "base64", + }, ], "initConfiguration": { "nodeRegistration": { @@ -1086,6 +1138,16 @@ def get_object(self) -> objects.ClusterClass: }, }, }, + { + "name": "enableKeystoneAuth", + "required": True, + "schema": { + "openAPIV3Schema": { + "type": "boolean", + "default": False, + }, + }, + }, ], "patches": [ { @@ -1134,16 +1196,26 @@ def get_object(self) -> objects.ClusterClass: }, { "op": "add", - "path": "/spec/template/spec/kubeadmConfigSpec/clusterConfiguration/apiServer/extraVolumes", # noqa: E501 + "path": "/spec/template/spec/kubeadmConfigSpec/clusterConfiguration/apiServer/extraVolumes/-", # noqa: E501 + "valueFrom": { + "template": textwrap.dedent( + """\ + name: audit-policy + hostPath: /etc/kubernetes/audit-policy + mountPath: /etc/kubernetes/audit-policy + """ + ), + }, + }, + { + "op": "add", + "path": "/spec/template/spec/kubeadmConfigSpec/clusterConfiguration/apiServer/extraVolumes/-", # noqa: E501 "valueFrom": { "template": textwrap.dedent( """\ - - name: audit-policy - hostPath: /etc/kubernetes/audit-policy - mountPath: /etc/kubernetes/audit-policy - - name: audit-logs - hostPath: /var/log/kubernetes/audit - mountPath: /var/log/audit + name: audit-logs + hostPath: /var/log/kubernetes/audit + mountPath: /var/log/audit """ ), }, @@ -1681,6 +1753,38 @@ def get_object(self) -> objects.ClusterClass: }, ], }, + { + "name": "keystoneAuth", + "enabledIf": "{{ if .enableKeystoneAuth }}true{{end}}", + "definitions": [ + { + "selector": { + "apiVersion": objects.KubeadmControlPlaneTemplate.version, + "kind": objects.KubeadmControlPlaneTemplate.kind, + "matchResources": { + "controlPlane": True, + }, + }, + "jsonPatches": [ + { + "op": "add", + "path": "/spec/template/spec/kubeadmConfigSpec/clusterConfiguration/apiServer/extraArgs/authentication-token-webhook-config-file", # noqa: E501 + "value": "/etc/kubernetes/webhooks/webhookconfig.yaml", + }, + { + "op": "add", + "path": "/spec/template/spec/kubeadmConfigSpec/clusterConfiguration/apiServer/extraArgs/authorization-webhook-config-file", # noqa: E501 + "value": "/etc/kubernetes/webhooks/webhookconfig.yaml", + }, + { + "op": "add", + "path": "/spec/template/spec/kubeadmConfigSpec/clusterConfiguration/apiServer/extraArgs/authorization-mode", # noqa: E501 + "value": "Node,RBAC,Webhook", + }, + ], + } + ], + }, { "name": "controlPlaneConfig", "definitions": [ @@ -2248,6 +2352,12 @@ def get_object(self) -> objects.Cluster: ) or "", }, + { + "name": "enableKeystoneAuth", + "value": utils.get_cluster_label_as_bool( + self.cluster, "keystone_auth_enabled", True + ), + }, ], }, }, diff --git a/magnum_cluster_api/utils.py b/magnum_cluster_api/utils.py index 4f6ab2d1..fc62e30f 100644 --- a/magnum_cluster_api/utils.py +++ b/magnum_cluster_api/utils.py @@ -12,6 +12,7 @@ # License for the specific language governing permissions and limitations # under the License. +import json import re import string import textwrap @@ -395,3 +396,26 @@ def convert_to_rfc1123(input: str) -> str: :rtype: str """ return re.sub(r"[^a-zA-Z0-9]+", "-", input).lower() + + +def get_keystone_auth_default_policy(cluster: magnum_objects.Cluster): + default_policy = [ + { + "resource": { + "verbs": ["list"], + "resources": ["pods", "services", "deployments", "pvc"], + "version": "*", + "namespace": "default", + }, + "match": [ + {"type": "role", "values": ["member"]}, + {"type": "project", "values": [cluster.project_id]}, + ], + } + ] + + try: + with open(CONF.kubernetes.keystone_auth_default_policy) as f: + return json.loads(f.read()) + except Exception: + return default_policy