From 15e28371ebb3b08957abceb84300c329c3966823 Mon Sep 17 00:00:00 2001 From: Hao Liu <44379968+TheRealHaoLiu@users.noreply.github.com> Date: Tue, 3 Sep 2024 09:51:17 -0400 Subject: [PATCH] Prevent automountServiceAccountToken (#6638) * Prevent job pod from mounting serviceaccount token * Add serializer validation for cg pod_spec_override Prevent automountServiceAccountToken to be set to true and provide an error message when automountServiceAccountToken is being set to true --- awx/api/serializers.py | 29 +++++++++++++++++++++++++++++ awx/main/scheduler/kubernetes.py | 3 +++ 2 files changed, 32 insertions(+) diff --git a/awx/api/serializers.py b/awx/api/serializers.py index b42783eb2a..3cae9a1c51 100644 --- a/awx/api/serializers.py +++ b/awx/api/serializers.py @@ -6,6 +6,7 @@ import copy import json import logging import re +import yaml from collections import Counter, OrderedDict from datetime import timedelta from uuid import uuid4 @@ -6057,6 +6058,34 @@ class InstanceGroupSerializer(BaseSerializer): raise serializers.ValidationError(_('Only Kubernetes credentials can be associated with an Instance Group')) return value + def validate_pod_spec_override(self, value): + if not value: + return value + + # value should be empty for non-container groups + if self.instance and not self.instance.is_container_group: + raise serializers.ValidationError(_('pod_spec_override is only valid for container groups')) + + pod_spec_override_json = {} + # defect if the value is yaml or json if yaml convert to json + try: + # convert yaml to json + pod_spec_override_json = yaml.safe_load(value) + except yaml.YAMLError: + try: + pod_spec_override_json = json.loads(value) + except json.JSONDecodeError: + raise serializers.ValidationError(_('pod_spec_override must be valid yaml or json')) + + # validate the + spec = pod_spec_override_json.get('spec', {}) + automount_service_account_token = spec.get('automountServiceAccountToken', False) + + if automount_service_account_token: + raise serializers.ValidationError(_('automountServiceAccountToken is not allowed for security reasons')) + + return value + def validate(self, attrs): attrs = super(InstanceGroupSerializer, self).validate(attrs) diff --git a/awx/main/scheduler/kubernetes.py b/awx/main/scheduler/kubernetes.py index 8566ca4864..b0869835e7 100644 --- a/awx/main/scheduler/kubernetes.py +++ b/awx/main/scheduler/kubernetes.py @@ -174,6 +174,9 @@ class PodManager(object): ) pod_spec['spec']['containers'][0]['name'] = self.pod_name + # Prevent mounting of service account token in job pods in order to prevent job pods from accessing the k8s API via in cluster service account auth + pod_spec['spec']['automountServiceAccountToken'] = False + return pod_spec