From 0b51766c24c566a235df780f3d275b6ca64f30f1 Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Thu, 15 Oct 2026 11:52:53 +0100 Subject: [PATCH 1/9] Add API-mode Dag processor deployment support API-mode processors need health probes that work without database credentials. Each processor session must also remain exclusive while pods are replaced, and isolated deployments need explicit credential and network boundaries around the trusted API server. --- .../howto/docker-compose/docker-compose.yaml | 9 +- .../dag-processor-api/helm-values.yaml | 74 ++++++++++++ .../dag-processor-api/network-policy.yaml | 51 +++++++++ .../security/jwt_token_authentication.rst | 22 ++++ chart/templates/_helpers.yaml | 5 + .../dag-processor-deployment.yaml | 21 +++- .../airflow_core/test_dag_processor.py | 107 ++++++++++++++++++ chart/values.schema.json | 4 +- chart/values.yaml | 7 +- .../test_dag_processor_api_deployment.py | 99 ++++++++++++++++ 10 files changed, 393 insertions(+), 6 deletions(-) create mode 100644 airflow-core/docs/security/dag-processor-api/helm-values.yaml create mode 100644 airflow-core/docs/security/dag-processor-api/network-policy.yaml create mode 100644 docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py diff --git a/airflow-core/docs/howto/docker-compose/docker-compose.yaml b/airflow-core/docs/howto/docker-compose/docker-compose.yaml index d245afed6bd1..be749b92e0ee 100644 --- a/airflow-core/docs/howto/docker-compose/docker-compose.yaml +++ b/airflow-core/docs/howto/docker-compose/docker-compose.yaml @@ -155,7 +155,14 @@ services: <<: *airflow-common command: dag-processor healthcheck: - test: ["CMD-SHELL", 'airflow jobs check --job-type DagProcessorJob --hostname "$${HOSTNAME}"'] + test: + - CMD-SHELL + - >- + if [ -n "$${AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE:-}" ]; then + airflow dag-processor --check-health; + else + airflow jobs check --job-type DagProcessorJob --hostname "$${HOSTNAME}"; + fi interval: 30s timeout: 10s retries: 5 diff --git a/airflow-core/docs/security/dag-processor-api/helm-values.yaml b/airflow-core/docs/security/dag-processor-api/helm-values.yaml new file mode 100644 index 000000000000..a4ecfcf877de --- /dev/null +++ b/airflow-core/docs/security/dag-processor-api/helm-values.yaml @@ -0,0 +1,74 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +--- +# Install as a separate processor-only release, using an image with API mode. +airflowVersion: "3.5.0" +defaultAirflowTag: "3.5.0" +executor: LocalExecutor +scheduler: + enabled: false +apiServer: + enabled: false +triggerer: + enabled: false +createUserJob: + enabled: false +migrateDatabaseJob: + enabled: false +postgresql: + enabled: false +redis: + enabled: false +statsd: + enabled: false +rbac: + create: false +enableBuiltInSecretEnvVars: + AIRFLOW__CORE__FERNET_KEY: false + AIRFLOW__DATABASE__SQL_ALCHEMY_CONN: false + AIRFLOW_CONN_AIRFLOW_DB: false + AIRFLOW__API__SECRET_KEY: false + AIRFLOW__API_AUTH__JWT_SECRET: false + AIRFLOW__CELERY__RESULT_BACKEND: false + AIRFLOW__CELERY__BROKER_URL: false +config: + core: + execution_api_server_url: http://airflow-api-server.airflow.svc.cluster.local:8080/execution/ + dag_processor: + execution_api_token_file: /run/dag-processor/processor.jwt +dagProcessor: + replicas: 1 + waitForMigrations: + enabled: false + serviceAccount: + automountServiceAccountToken: false + env: + - name: CONNECTION_CHECK_MAX_COUNT + value: "0" + extraVolumes: + - name: processor-token + secret: + secretName: dag-processor-session + defaultMode: 0440 + extraVolumeMounts: + - name: processor-token + mountPath: /run/dag-processor + readOnly: true +dags: + persistence: + enabled: true + existingClaim: processor-dags diff --git a/airflow-core/docs/security/dag-processor-api/network-policy.yaml b/airflow-core/docs/security/dag-processor-api/network-policy.yaml new file mode 100644 index 000000000000..ae021ce64da2 --- /dev/null +++ b/airflow-core/docs/security/dag-processor-api/network-policy.yaml @@ -0,0 +1,51 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +--- +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: dag-processor-api-only +spec: + podSelector: + matchLabels: + component: dag-processor + policyTypes: [Ingress, Egress] + ingress: [] + egress: + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: airflow + podSelector: + matchLabels: + component: api-server + release: airflow + ports: + - protocol: TCP + port: 8080 + - to: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: kube-system + podSelector: + matchLabels: + k8s-app: kube-dns + ports: + - protocol: UDP + port: 53 + - protocol: TCP + port: 53 diff --git a/airflow-core/docs/security/jwt_token_authentication.rst b/airflow-core/docs/security/jwt_token_authentication.rst index 988b557baff3..63a2e40b55ba 100644 --- a/airflow-core/docs/security/jwt_token_authentication.rst +++ b/airflow-core/docs/security/jwt_token_authentication.rst @@ -734,6 +734,14 @@ one second, and waiting for parsing processes can take another second without a ``health_check_threshold`` above five times that timeout plus three seconds, with additional scheduling margin. +For Helm, set the token-file option under ``config.dag_processor`` to select the local +probe. The chart then replaces processor pods with the ``Recreate`` strategy, because pods +that share a session token cannot run their Jobs side by side, and rejects more than one +replica for the same reason. Disable the processor's migration-wait init container, provision the catalog +separately, and remove server credentials from the pod. The Compose example selects the +local probe when ``AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE`` is set. Neither the +main chart release nor the quick-start Compose file removes shared credentials or adds +database-denying network policies automatically; the isolated examples below do. Set ``CONNECTION_CHECK_MAX_COUNT=0`` in the processor container too: the standard image entrypoint otherwise checks the database before starting the command. Do not set ``_AIRFLOW_DB_MIGRATE`` or ``_AIRFLOW_WWW_USER_CREATE`` in that container. @@ -752,6 +760,20 @@ being moved. If that processor must continue serving other bundles, restrict it ``--bundle-name`` to those other bundles. This prevents conflicting inventory reconciliation and keeps Dag code for the moved bundles out of the database-credentialed processor. +For Kubernetes, use the :download:`processor-only Helm values ` +in a **separate release and namespace**. These values disable other components and built-in +server credential injection. Do not apply them to the release running the scheduler/API server. +Create the ``dag-processor-session`` Secret containing ``processor.jwt`` and the +``processor-dags`` PVC in that namespace, then configure the API service address and image. +The processor service account has no mounted API token; a trusted provisioner updates the Secret. + +Apply the :download:`egress policy ` in the processor +namespace before starting its pods. It permits only DNS and the trusted API server. Adjust +its namespace/pod selectors and ports to match the deployment. NetworkPolicy enforcement +requires a supporting cluster network plugin; other policies selecting these pods must not +grant broader egress. This example uses local Dag files. Remote bundles need additional, +explicit egress to their source service. + For Compose, use the :download:`standalone processor definition ` as its own project, rather than merging it with the quick-start file. It has no shared ``env_file``, server configuration mount, or dependency on a database/migration service. diff --git a/chart/templates/_helpers.yaml b/chart/templates/_helpers.yaml index 7e6c1fb549e0..870275fabbb5 100644 --- a/chart/templates/_helpers.yaml +++ b/chart/templates/_helpers.yaml @@ -904,8 +904,13 @@ server_tls_key_file = /etc/pgbouncer/server.key - sh - -c - | + {{- if (get (.Values.config.dag_processor | default dict) "execution_api_token_file") }} + CONNECTION_CHECK_MAX_COUNT=0 AIRFLOW__LOGGING__LOGGING_LEVEL=ERROR exec /entrypoint \ + airflow dag-processor --check-health + {{- else }} CONNECTION_CHECK_MAX_COUNT=0 AIRFLOW__LOGGING__LOGGING_LEVEL=ERROR exec /entrypoint \ airflow jobs check --local --job-type DagProcessorJob + {{- end }} {{- end }} {{- define "registry_docker_config" }} diff --git a/chart/templates/dag-processor/dag-processor-deployment.yaml b/chart/templates/dag-processor/dag-processor-deployment.yaml index a74c0a4ca9a3..09b1b11027dc 100644 --- a/chart/templates/dag-processor/dag-processor-deployment.yaml +++ b/chart/templates/dag-processor/dag-processor-deployment.yaml @@ -21,6 +21,9 @@ ## Airflow Dag Processor Deployment ################################# {{- if .Values.dagProcessor.enabled }} +{{- if and (get (.Values.config.dag_processor | default dict) "execution_api_token_file") (gt (int .Values.dagProcessor.replicas) 1) }} +{{- fail "`dagProcessor.replicas` must not exceed 1 when `config.dag_processor.execution_api_token_file` is set, because the pods would share one session token. Deploy a separate release, with its own token, for each additional processor." }} +{{- end }} {{- $nodeSelector := or .Values.dagProcessor.nodeSelector .Values.nodeSelector }} {{- $affinity := or .Values.dagProcessor.affinity .Values.affinity }} {{- $tolerations := or .Values.dagProcessor.tolerations .Values.tolerations }} @@ -58,7 +61,11 @@ spec: tier: airflow component: dag-processor release: {{ .Release.Name }} - {{- if .Values.dagProcessor.strategy }} + {{- if (get (.Values.config.dag_processor | default dict) "execution_api_token_file") }} + {{- /* Pods share one session token, and a new pod can register its Job only after the old one stops. */}} + strategy: + type: Recreate + {{- else if .Values.dagProcessor.strategy }} strategy: {{- toYaml .Values.dagProcessor.strategy | nindent 4 }} {{- end }} template: @@ -191,6 +198,18 @@ spec: {{- include "standard_airflow_environment" . | indent 10 }} {{- include "metadata_db_environment" . | indent 10 }} {{- include "container_extra_envs" (list . .Values.dagProcessor.env) | indent 10 }} + {{- if (get (.Values.config.dag_processor | default dict) "execution_api_token_file") }} + readinessProbe: + timeoutSeconds: {{ .Values.dagProcessor.livenessProbe.timeoutSeconds }} + periodSeconds: {{ .Values.dagProcessor.livenessProbe.periodSeconds }} + exec: + command: + - sh + - -c + - >- + CONNECTION_CHECK_MAX_COUNT=0 AIRFLOW__LOGGING__LOGGING_LEVEL=ERROR exec /entrypoint + airflow dag-processor --check-ready + {{- end }} livenessProbe: initialDelaySeconds: {{ .Values.dagProcessor.livenessProbe.initialDelaySeconds }} timeoutSeconds: {{ .Values.dagProcessor.livenessProbe.timeoutSeconds }} diff --git a/chart/tests/helm_tests/airflow_core/test_dag_processor.py b/chart/tests/helm_tests/airflow_core/test_dag_processor.py index ec6dcaab4751..7fdff7fb35a7 100644 --- a/chart/tests/helm_tests/airflow_core/test_dag_processor.py +++ b/chart/tests/helm_tests/airflow_core/test_dag_processor.py @@ -16,8 +16,13 @@ # under the License. from __future__ import annotations +from configparser import ConfigParser +from pathlib import Path +from subprocess import CalledProcessError + import jmespath import pytest +import yaml from chart_utils.helm_template_generator import render_chart from chart_utils.log_groomer import LogGroomerTestBase @@ -434,6 +439,108 @@ def test_livenessprobe_command(self): in jmespath.search("spec.template.spec.containers[0].livenessProbe.exec.command", docs[0])[-1] ) + def test_api_mode_uses_local_liveness_probe(self): + docs = render_chart( + values={"config": {"dag_processor": {"execution_api_token_file": "/run/processor.jwt"}}}, + show_only=["templates/dag-processor/dag-processor-deployment.yaml"], + ) + command = jmespath.search("spec.template.spec.containers[0].livenessProbe.exec.command", docs[0])[-1] + assert "airflow dag-processor --check-health" in command + readiness = docs[0]["spec"]["template"]["spec"]["containers"][0]["readinessProbe"]["exec"]["command"] + assert "airflow dag-processor --check-ready" in readiness[-1] + assert "airflow jobs check" not in command + + def test_api_mode_replaces_pods_with_recreate(self): + docs = render_chart( + values={ + "config": {"dag_processor": {"execution_api_token_file": "/run/processor.jwt"}}, + "dagProcessor": { + "strategy": {"rollingUpdate": {"maxSurge": "100%", "maxUnavailable": "50%"}} + }, + }, + show_only=["templates/dag-processor/dag-processor-deployment.yaml"], + ) + + assert jmespath.search("spec.strategy", docs[0]) == {"type": "Recreate"} + + @pytest.mark.parametrize(("replicas", "rejected"), [(0, False), (1, False), (2, True)]) + def test_api_mode_rejects_replicas_sharing_a_session_token(self, replicas, rejected): + values = { + "config": {"dag_processor": {"execution_api_token_file": "/run/processor.jwt"}}, + "dagProcessor": {"replicas": replicas}, + } + show_only = ["templates/dag-processor/dag-processor-deployment.yaml"] + if rejected: + with pytest.raises(CalledProcessError, match="must not exceed 1"): + render_chart(values=values, show_only=show_only) + else: + docs = render_chart(values=values, show_only=show_only) + assert jmespath.search("spec.replicas", docs[0]) == replicas + + def test_isolated_api_deployment_example(self): + examples = Path(__file__).resolve().parents[4] / "airflow-core/docs/security/dag-processor-api" + values = yaml.safe_load((examples / "helm-values.yaml").read_text()) + docs = render_chart(values=values, namespace="dag-processors") + workloads = [doc for doc in docs if doc["kind"] in {"Deployment", "StatefulSet", "Job", "CronJob"}] + assert len(workloads) == 1 + deployment = workloads[0] + assert deployment["metadata"]["labels"]["component"] == "dag-processor" + assert deployment["spec"]["strategy"] == {"type": "Recreate"} + pod = deployment["spec"]["template"]["spec"] + assert not pod.get("initContainers") + for container in pod["containers"]: + assert not container.get("envFrom") + assert all("valueFrom" not in env for env in container.get("env", [])) + processor = next(container for container in pod["containers"] if container["name"] == "dag-processor") + assert {env["name"]: env["value"] for env in processor["env"]} == { + "AIRFLOW_HOME": "/opt/airflow", + "CONNECTION_CHECK_MAX_COUNT": "0", + } + assert "--check-health" in processor["livenessProbe"]["exec"]["command"][-1] + assert "--check-ready" in processor["readinessProbe"]["exec"]["command"][-1] + assert {v["secret"]["secretName"] for v in pod["volumes"] if "secret" in v} == { + "dag-processor-session" + } + token_mount = next(m for m in processor["volumeMounts"] if m["name"] == "processor-token") + assert token_mount["readOnly"] + assert "subPath" not in token_mount + account = next( + doc + for doc in docs + if doc["kind"] == "ServiceAccount" and doc["metadata"]["name"] == pod["serviceAccountName"] + ) + assert account["automountServiceAccountToken"] is False + configmap = next( + doc for doc in docs if doc["kind"] == "ConfigMap" and "airflow.cfg" in doc.get("data", {}) + ) + config = ConfigParser(interpolation=None) + config.read_string(configmap["data"]["airflow.cfg"]) + for section, key in ( + ("database", "sql_alchemy_conn"), + ("core", "fernet_key"), + ("api_auth", "jwt_secret"), + ("api_auth", "jwt_private_key_path"), + ): + assert not config.has_option(section, key) + assert config["dag_processor"]["execution_api_token_file"] == "/run/dag-processor/processor.jwt" + policy = yaml.safe_load((examples / "network-policy.yaml").read_text())["spec"] + labels = deployment["spec"]["template"]["metadata"]["labels"] + assert policy["podSelector"]["matchLabels"].items() <= labels.items() + assert set(policy["policyTypes"]) == {"Ingress", "Egress"} + assert not policy["ingress"] + assert len(policy["egress"]) == 2 + assert policy["egress"][0] == { + "to": [ + { + "namespaceSelector": {"matchLabels": {"kubernetes.io/metadata.name": "airflow"}}, + "podSelector": {"matchLabels": {"component": "api-server", "release": "airflow"}}, + } + ], + "ports": [{"protocol": "TCP", "port": 8080}], + } + assert policy["egress"][1]["to"][0]["podSelector"]["matchLabels"] == {"k8s-app": "kube-dns"} + assert {port["port"] for port in policy["egress"][1]["ports"]} == {53} + @pytest.mark.parametrize( ("log_values", "expected_volume"), [ diff --git a/chart/values.schema.json b/chart/values.schema.json index 4cbe8ec2f1d5..4d5d923a6a85 100644 --- a/chart/values.schema.json +++ b/chart/values.schema.json @@ -4520,7 +4520,7 @@ } }, "replicas": { - "description": "Number of dag processors to run.", + "description": "Number of dag processors to run. At most 1 when ``config.dag_processor.execution_api_token_file`` is set, since the pods would share one session token.", "type": "integer", "default": 1 }, @@ -4560,7 +4560,7 @@ ] }, "strategy": { - "description": "Specifies the strategy used to replace old Pods by new ones when deployed as a Deployment.", + "description": "Specifies the strategy used to replace old Pods by new ones when deployed as a Deployment. Ignored when ``config.dag_processor.execution_api_token_file`` is set; those pods share one session token and are replaced with the Recreate strategy.", "type": [ "null", "object" diff --git a/chart/values.yaml b/chart/values.yaml index 47f362369e5e..253c37866df9 100644 --- a/chart/values.yaml +++ b/chart/values.yaml @@ -2164,7 +2164,8 @@ dagProcessor: # classpath: "airflow.dag_processing.bundles.local.LocalDagBundle" # kwargs: {} - # Number of Airflow dag processors in the Deployment + # Number of Airflow dag processors in the Deployment. At most 1 when + # config.dag_processor.execution_api_token_file is set, since the pods would share one session token. replicas: 1 # Max number of old ReplicaSets to retain @@ -2176,7 +2177,9 @@ dagProcessor: # Args to use when running Airflow dag processor (templated). args: ["bash", "-c", "exec airflow dag-processor"] - # Update Strategy for dag processors + # Update Strategy for dag processors. Ignored when + # config.dag_processor.execution_api_token_file is set: those pods share one session + # token, so they are always replaced with the Recreate strategy. strategy: rollingUpdate: maxSurge: "100%" diff --git a/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py b/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py new file mode 100644 index 000000000000..b2e067da35c7 --- /dev/null +++ b/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py @@ -0,0 +1,99 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import subprocess + +import pytest +import yaml +from python_on_whales import DockerClient + +from docker_tests.constants import AIRFLOW_ROOT_PATH + + +@pytest.mark.parametrize( + ("token_file", "expected_args"), + [ + (None, ["jobs", "check", "--job-type", "DagProcessorJob", "--hostname", "test-processor"]), + ("/run/processor.jwt", ["dag-processor", "--check-health"]), + ], +) +def test_quick_start_processor_healthcheck_mode(tmp_path, token_file, expected_args): + example = AIRFLOW_ROOT_PATH / "airflow-core/docs/howto/docker-compose/docker-compose.yaml" + healthcheck = yaml.safe_load(example.read_text())["services"]["airflow-dag-processor"]["healthcheck"][ + "test" + ] + assert healthcheck[0] == "CMD-SHELL" + airflow = tmp_path / "airflow" + airflow.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n") + airflow.chmod(0o700) + env = {"PATH": str(tmp_path), "HOSTNAME": "test-processor"} + if token_file is not None: + env["AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE"] = token_file + # Compose unescapes doubled dollar signs before passing CMD-SHELL to the container. + result = subprocess.run( + ["/bin/sh", "-c", healthcheck[1].replace("$$", "$")], + env=env, + check=True, + capture_output=True, + text=True, + ) + assert result.stdout.splitlines() == expected_args + + +@pytest.mark.parametrize("uid", [50000, 54321]) +def test_isolated_processor_compose_example(tmp_path, monkeypatch, uid): + monkeypatch.setenv("AIRFLOW_IMAGE_NAME", "processor-api:test") + monkeypatch.setenv("DAG_PROCESSOR_API_NETWORK", "test-api-only") + monkeypatch.setenv("AIRFLOW_UID", str(uid)) + credentials = { + "AIRFLOW__DATABASE__SQL_ALCHEMY_CONN": "postgresql://must-not-reach-the-processor", + "AIRFLOW__CORE__FERNET_KEY": "must-not-reach-the-processor", + "AIRFLOW__API_AUTH__JWT_SECRET": "must-not-reach-the-processor", + "AIRFLOW__API_AUTH__JWT_PRIVATE_KEY_PATH": "/server/private.key", + } + for name, value in credentials.items(): + monkeypatch.setenv(name, value) + (tmp_path / ".env").write_text("\n".join(f"{name}={value}" for name, value in credentials.items())) + example = AIRFLOW_ROOT_PATH / "airflow-core/docs/security/dag-processor-api/docker-compose.yaml" + rendered = DockerClient(compose_files=[example], compose_project_directory=tmp_path).compose.config( + return_json=True + ) + assert set(rendered["services"]) == {"dag-processor"} + processor = rendered["services"]["dag-processor"] + assert processor["command"] == ["dag-processor"] + assert processor["user"] == f"{uid}:0" + assert processor["environment"]["USER"] == "airflow" + assert not processor.get("depends_on") + assert not processor.get("env_file") + assert not credentials.keys() & processor["environment"].keys() + assert processor["environment"]["CONNECTION_CHECK_MAX_COUNT"] == "0" + assert ( + processor["environment"]["AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE"] + == "/run/dag-processor/processor.jwt" + ) + assert processor["environment"]["AIRFLOW_CONFIG"] == "/tmp/airflow.cfg" + assert processor["healthcheck"]["test"] == ["CMD", "airflow", "dag-processor", "--check-health"] + assert set(processor["networks"]) == {"processor-api"} + assert rendered["networks"]["processor-api"]["name"] == "test-api-only" + assert rendered["networks"]["processor-api"]["external"] + mounts = {mount["target"]: mount for mount in processor["volumes"]} + assert set(mounts) == {"/run/dag-processor", "/opt/airflow/dags", "/opt/airflow/logs"} + assert mounts["/run/dag-processor"]["read_only"] + assert mounts["/opt/airflow/dags"]["read_only"] + assert processor["read_only"] + assert processor["cap_drop"] == ["ALL"] From 84223c5d80d91d40a245cc142bb0f16314cda5af Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Tue, 20 Oct 2026 17:16:47 +0100 Subject: [PATCH 2/9] Rotate Dag processor session tokens in Kubernetes Secrets Dag processors using the Execution API need renewable credentials without access to signing keys. Kubernetes deployments also need to retain their session when the token publisher restarts or an API response is lost. --- .../dag-processor-api/helm-values.yaml | 3 +- .../kubernetes-token-provisioner.yaml | 139 +++++++ .../security/jwt_token_authentication.rst | 110 +++++- airflow-core/src/airflow/cli/cli_config.py | 18 +- .../commands/dag_processor_token_command.py | 79 +++- .../dag_processor_token_kubernetes.py | 145 +++++++ .../test_dag_processor_token_command.py | 171 +++++++++ .../test_dag_processor_token_kubernetes.py | 359 ++++++++++++++++++ .../airflow_core/test_dag_processor.py | 97 +++++ 9 files changed, 1097 insertions(+), 24 deletions(-) create mode 100644 airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml create mode 100644 airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py create mode 100644 airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py diff --git a/airflow-core/docs/security/dag-processor-api/helm-values.yaml b/airflow-core/docs/security/dag-processor-api/helm-values.yaml index a4ecfcf877de..1013e3ef5d55 100644 --- a/airflow-core/docs/security/dag-processor-api/helm-values.yaml +++ b/airflow-core/docs/security/dag-processor-api/helm-values.yaml @@ -15,7 +15,8 @@ # specific language governing permissions and limitations # under the License. --- -# Install as a separate processor-only release, using an image with API mode. +# Install as a separate processor-only release in airflow-dag-processor. +# Apply kubernetes-token-provisioner.yaml first, using an image with API mode. airflowVersion: "3.5.0" defaultAirflowTag: "3.5.0" executor: LocalExecutor diff --git a/airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml b/airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml new file mode 100644 index 000000000000..3f664a9757a5 --- /dev/null +++ b/airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml @@ -0,0 +1,139 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +--- +apiVersion: v1 +kind: Namespace +metadata: + name: airflow-dag-processor +--- +# Omit data/stringData so applying this manifest again preserves the current session. +apiVersion: v1 +kind: Secret +metadata: + name: dag-processor-session + namespace: airflow-dag-processor +type: Opaque +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: dag-processor-token-provisioner + namespace: airflow +automountServiceAccountToken: true +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: dag-processor-token-provisioner + namespace: airflow-dag-processor +rules: + - apiGroups: [""] + resources: [secrets] + resourceNames: [dag-processor-session] + verbs: [get, patch] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: dag-processor-token-provisioner + namespace: airflow-dag-processor +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: dag-processor-token-provisioner +subjects: + - kind: ServiceAccount + name: dag-processor-token-provisioner + namespace: airflow +--- +apiVersion: apps/v1 +kind: Deployment +metadata: + name: dag-processor-token-provisioner + namespace: airflow +spec: + replicas: 1 + strategy: + type: Recreate + selector: + matchLabels: + component: dag-processor-token-provisioner + template: + metadata: + labels: + component: dag-processor-token-provisioner + spec: + serviceAccountName: dag-processor-token-provisioner + automountServiceAccountToken: true + securityContext: + runAsNonRoot: true + runAsUser: 50000 + runAsGroup: 0 + fsGroup: 0 + seccompProfile: + type: RuntimeDefault + containers: + - name: token-provisioner + # Use an image containing the Kubernetes token provisioner command. + image: apache/airflow:3.5.0 + args: + - airflow + - dag-processor-token + - --kubernetes-secret + - dag-processor-session + - --kubernetes-namespace + - airflow-dag-processor + - --bundle-name + - dags-folder + - --valid-for + - "600" + - --rotate + env: + - name: AIRFLOW_HOME + value: /tmp/airflow + - name: AIRFLOW_CONFIG + value: /dev/null + - name: AIRFLOW__CORE__LOAD_EXAMPLES + value: "False" + - name: AIRFLOW__DAG_PROCESSOR__DAG_BUNDLE_CONFIG_LIST + value: >- + [{"name":"dags-folder", + "classpath":"airflow.dag_processing.bundles.local.LocalDagBundle","kwargs":{}}] + - name: AIRFLOW__API_AUTH__JWT_SECRET + valueFrom: + secretKeyRef: + # Match the trusted API server's jwtSecretName (default: -jwt-secret). + name: airflow-jwt-secret + key: jwt-secret + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: [ALL] + resources: + requests: + cpu: 100m + memory: 256Mi + limits: + cpu: 500m + memory: 512Mi + volumeMounts: + - name: tmp + mountPath: /tmp + volumes: + - name: tmp + emptyDir: {} diff --git a/airflow-core/docs/security/jwt_token_authentication.rst b/airflow-core/docs/security/jwt_token_authentication.rst index 63a2e40b55ba..0b41755a9651 100644 --- a/airflow-core/docs/security/jwt_token_authentication.rst +++ b/airflow-core/docs/security/jwt_token_authentication.rst @@ -749,11 +749,18 @@ entrypoint otherwise checks the database before starting the command. Do not set Isolated deployment examples ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -The following examples run only the processor, alongside an existing trusted deployment. +The following examples isolate the processor from an existing trusted deployment. Use an image containing processor API support; this feature targets Airflow 3.5. -Synchronize the bundle catalog and run token provisioning in the trusted deployment as -described above. Keep the token provisioner running, and mount its directory rather than -a single file so atomic token replacement remains visible. +Synchronize the bundle catalog in the trusted deployment before starting the processor, +and again whenever the bundle configuration changes:: + + airflow dag-processor --sync-bundles-only + +This step needs database access. Token provisioning itself needs only the API's signing +configuration and the configured bundle names; it does not access the metadata database. + +Kubernetes token provisioner +"""""""""""""""""""""""""""" Before starting the isolated processor, stop the trusted deployment's processor for the bundles being moved. If that processor must continue serving other bundles, restrict it with @@ -763,9 +770,35 @@ and keeps Dag code for the moved bundles out of the database-credentialed proces For Kubernetes, use the :download:`processor-only Helm values ` in a **separate release and namespace**. These values disable other components and built-in server credential injection. Do not apply them to the release running the scheduler/API server. -Create the ``dag-processor-session`` Secret containing ``processor.jwt`` and the -``processor-dags`` PVC in that namespace, then configure the API service address and image. -The processor service account has no mounted API token; a trusted provisioner updates the Secret. + +The :download:`token provisioner manifest ` +automatically maintains the processor's ``dag-processor-session`` Secret. It runs +``airflow dag-processor-token --kubernetes-secret dag-processor-session +--kubernetes-namespace airflow-dag-processor --bundle-name dags-folder --valid-for 600 --rotate`` +in the trusted ``airflow`` namespace. Its service account can only get and patch that +named Secret in the ``airflow-dag-processor`` namespace. The processor has neither the +signing key nor a mounted Kubernetes API credential. + +Customize both files before applying them: + +* Set both images to an image containing this feature. The manifest assumes the trusted + release and namespace are named ``airflow``; update namespace references, the API + service address, and NetworkPolicy selectors together if yours differ. +* Point the provisioner's ``AIRFLOW__API_AUTH__JWT_SECRET`` at the API server's signing + Secret. For the Helm chart's default configuration this is ``-jwt-secret``, + key ``jwt-secret``; ``jwtSecretName`` overrides the Secret name. For asymmetric signing, + replace this environment variable with the matching private-key mount and + ``AIRFLOW__API_AUTH__JWT_PRIVATE_KEY_PATH``. +* Copy any non-default signing algorithm, key ID, issuer, and execution API audience + settings from the API server. Do not copy database credentials or the entire server + configuration into the provisioner. Restart the provisioner when its signing + configuration changes, including a signing Secret supplied through environment variables. +* Match ``--bundle-name`` and ``AIRFLOW__DAG_PROCESSOR__DAG_BUNDLE_CONFIG_LIST`` to the + catalog and processor configuration. Repeat ``--bundle-name`` for additional bundles. + Provisioning reads their names without loading bundle classes or fetching Dag files. +* Create the ``processor-dags`` PVC in ``airflow-dag-processor`` and populate it with + the local Dag files. The provisioner needs no volume for its session state: it reads + the current token from the Secret on startup and preserves that session across restarts. Apply the :download:`egress policy ` in the processor namespace before starting its pods. It permits only DNS and the trusted API server. Adjust @@ -774,6 +807,65 @@ requires a supporting cluster network plugin; other policies selecting these pod grant broader egress. This example uses local Dag files. Remote bundles need additional, explicit egress to their source service. +For a fresh deployment, keep the empty ``Secret`` document in the provisioner manifest. +The Secret must exist before the command runs: the provisioner has no permission to create +or delete Secrets. + +To adopt an existing processor Secret while preserving its session: + +* Stop the previous token publisher and prevent it from restarting. +* Keep the existing Secret and its ``processor.jwt`` value. Match the provisioner's + Secret name, namespace, and bundle names to that token's current grant. +* Remove the entire ``kind: Secret`` document from your copy of + ``kubernetes-token-provisioner.yaml`` before applying it, and keep it excluded from + subsequent applies. Do not delete the live Secret. If an earlier ``kubectl apply`` + managed its token data, applying an empty Secret document can remove that data through + the last-applied configuration and cause the provisioner to create a new session. + +After preparing the files for a fresh deployment or adoption, start the provisioner +and then the processor:: + + kubectl apply -f kubernetes-token-provisioner.yaml + kubectl -n airflow rollout status deployment/dag-processor-token-provisioner + kubectl -n airflow-dag-processor wait --for=jsonpath='{.data.processor\.jwt}' secret/dag-processor-session --timeout=120s + kubectl -n airflow-dag-processor apply -f network-policy.yaml + helm upgrade --install dag-processor apache-airflow/airflow \ + --namespace airflow-dag-processor --values helm-values.yaml + +For Secrets created by this example, the manifest deliberately omits ``data`` and +``stringData`` from the first apply, so later applies leave the provisioner's token intact. +When adopting an existing Secret, the provisioner reads its current token and reuses the +session for the same bundle grant. Restrict other writers to this Secret; deleting and +recreating it or changing the authorized bundle set creates a new session. Restart the +processor when changing sessions. Each concurrently running +processor needs a separate provisioner and Secret. Both example Deployments use one replica and +``Recreate``; do not scale a deployment whose replicas share a session token. + +The provisioner writes a token immediately and rotates it every 300 seconds, with each +token valid for 600 seconds. It updates the Secret directly; no external ``kubectl`` loop, +sidecar publisher, or persistent token directory is needed. Kubernetes eventually projects +the updated Secret into the processor's mounted directory, which the processor reloads +without restarting. Keep the directory mount in the values file: a ``subPath`` mount +does not receive `Secret updates `_. +Choose a token lifetime that leaves time for your cluster's projection delay and transient outages. + +The rollout check confirms that the provisioner process started; the Secret-key wait +checks only that a token has been published at least once. Neither check proves that +an existing token is still valid or that rotation continues successfully. + +Allow the trusted provisioner to reach the Kubernetes API over TLS if the trusted +namespace restricts egress. It uses its mounted service-account token and cluster CA, +and reloads that credential on each request. In rotation mode, Kubernetes read and update +failures are retried with backoff, including during initial issuance. Initial signing or +configuration errors exit the command and Kubernetes restarts it. Later rotation failures +also retry; the previous token remains usable until it expires. An outage lasting beyond expiry +prevents the processor from renewing its API credentials. Monitor provisioner failures +and processor readiness, and restore Kubernetes API access or signing configuration +before the token expires. Monitor the token's expiry without logging its value. + +Compose token provisioner +""""""""""""""""""""""""" + For Compose, use the :download:`standalone processor definition ` as its own project, rather than merging it with the quick-start file. It has no shared ``env_file``, server configuration mount, or dependency on a database/migration service. @@ -781,7 +873,9 @@ It serves ``dags-folder`` from its own ``./dags`` directory. Disable the quick-s ``airflow-dag-processor`` service unless it is restricted to other bundles: processors that reconcile different file sets for the same bundle mark each other's missing Dags stale. Create its ``tokens``, ``dags``, and ``logs`` directories with permissions for the configured -container user; provision ``tokens/processor.jwt``. Set ``AIRFLOW_IMAGE_NAME`` to the image +container user; run the file-based token provisioner described above continuously to +maintain ``tokens/processor.jwt``. Mount the directory rather than a single file so +atomic token replacement remains visible. Set ``AIRFLOW_IMAGE_NAME`` to the image with API support. Create an internal network and attach only the API server and processor:: docker network create --internal dag-processor-api diff --git a/airflow-core/src/airflow/cli/cli_config.py b/airflow-core/src/airflow/cli/cli_config.py index c3acd30746a3..78bdebd2d645 100644 --- a/airflow-core/src/airflow/cli/cli_config.py +++ b/airflow-core/src/airflow/cli/cli_config.py @@ -836,7 +836,14 @@ def string_lower_type(val): ARG_DAG_PROCESSOR_TOKEN_FILE = Arg( ("--token-file",), help="File to write the token to; it is replaced in one step and readable only by the current user", - required=True, +) +ARG_DAG_PROCESSOR_TOKEN_KUBERNETES_SECRET = Arg( + ("--kubernetes-secret",), + help="Existing Kubernetes Secret to update at key processor.jwt, instead of writing --token-file", +) +ARG_DAG_PROCESSOR_TOKEN_KUBERNETES_NAMESPACE = Arg( + ("--kubernetes-namespace",), + help="Namespace of --kubernetes-secret; uses the pod's service account and cluster CA", ) ARG_DAG_PROCESSOR_TOKEN_VALID_FOR = Arg( ("--valid-for",), @@ -2375,16 +2382,19 @@ class GroupCommand(NamedTuple): ), ActionCommand( name="dag-processor-token", - help="Write a Dag processor session token to a file", + help="Write a Dag processor session token to a file or Kubernetes Secret", description=( "Issue a session token that lets a Dag processor reach the Execution API for the given " "bundles, without the processor holding the signing key. Run it where the signing key is " - "available, and give the processor read access to the token file; its mode and group are kept when " - "rotation replaces it." + "available. Choose --token-file or --kubernetes-secret with --kubernetes-namespace. " + "File rotation preserves mode and group. Kubernetes rotation updates processor.jwt in an existing " + "Secret using the pod's service account; mount that Secret as a directory on the processor." ), func=lazy_load_command("airflow.cli.commands.dag_processor_token_command.dag_processor_token"), args=( ARG_DAG_PROCESSOR_TOKEN_FILE, + ARG_DAG_PROCESSOR_TOKEN_KUBERNETES_SECRET, + ARG_DAG_PROCESSOR_TOKEN_KUBERNETES_NAMESPACE, ARG_BUNDLE_NAME, ARG_DAG_PROCESSOR_TOKEN_VALID_FOR, ARG_DAG_PROCESSOR_TOKEN_ROTATE, diff --git a/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py b/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py index fbaaf5f6cb05..c1fdb077c90e 100644 --- a/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py +++ b/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py @@ -24,7 +24,9 @@ import stat import tempfile import time +from functools import partial from pathlib import Path +from typing import TYPE_CHECKING from uuid import UUID import jwt @@ -32,10 +34,17 @@ from airflow.api_fastapi.execution_api.app import create_jwt_generator from airflow.api_fastapi.execution_api.dag_processor_tokens import generate_dag_processor_session_token +from airflow.cli.commands.dag_processor_token_kubernetes import ( + KubernetesSecretTokenError, + KubernetesSecretTokenStore, +) from airflow.configuration import conf from airflow.dag_processing.bundles.manager import get_configured_bundle_names from airflow.utils.providers_configuration_loader import providers_configuration_loaded +if TYPE_CHECKING: + from collections.abc import Callable + log = logging.getLogger(__name__) @@ -63,9 +72,18 @@ def write_token_file(path: Path, token: str) -> None: def get_session_id(token_file: Path, bundle_names: set[str]) -> UUID: """Reuse the session of the token already in the file, so a restart keeps the processors' Jobs.""" - with contextlib.suppress(OSError, KeyError, TypeError, ValueError, jwt.PyJWTError): - # Unverified: the file is this command's own output. - claims = jwt.decode(token_file.read_text(), options={"verify_signature": False}) + with contextlib.suppress(OSError, ValueError): + return get_session_id_from_token(token_file.read_text(), bundle_names) + return uuid6.uuid7() + + +def get_session_id_from_token(token: str | None, bundle_names: set[str]) -> UUID: + """Reuse the session in a previous provisioner's output for the same bundle grant.""" + if not token: + return uuid6.uuid7() + with contextlib.suppress(KeyError, TypeError, ValueError, jwt.PyJWTError): + # Unverified: only trusted provisioners can write this file or Secret. + claims = jwt.decode(token, options={"verify_signature": False}) if claims["scope"] == "dag_processor_session" and set(claims["dag_bundles"]) == bundle_names: return UUID(claims["sub"]) return uuid6.uuid7() @@ -75,7 +93,11 @@ def get_session_id(token_file: Path, bundle_names: set[str]) -> UUID: # component that only holds the signing key cannot reach. @providers_configuration_loaded def dag_processor_token(args) -> None: - """Write a Dag processor session token to a file, and with ``--rotate`` keep replacing it.""" + """Publish a Dag processor session token, and with ``--rotate`` keep replacing it.""" + if bool(args.token_file) == bool(args.kubernetes_secret): + raise SystemExit("Choose exactly one of --token-file or --kubernetes-secret") + if bool(args.kubernetes_secret) != bool(args.kubernetes_namespace): + raise SystemExit("--kubernetes-secret and --kubernetes-namespace must be supplied together") # Names only: provisioning runs where the signing key is, which may not have the bundle classes installed. configured = get_configured_bundle_names() bundle_names = set(args.bundle_name or configured) @@ -83,27 +105,62 @@ def dag_processor_token(args) -> None: raise SystemExit(f"Bundles not found: {', '.join(sorted(unknown))}") valid_for = args.valid_for or conf.getint("execution_api", "jwt_expiration_time") + if args.kubernetes_secret: + with KubernetesSecretTokenStore(args.kubernetes_secret, args.kubernetes_namespace) as store: + _run_token_rotation( + bundle_names, + valid_for, + get_session=lambda: get_session_id_from_token(store.read_token(), bundle_names), + publish_token=store.write_token, + rotate=args.rotate, + retry_initial_publication=True, + ) + return + token_file = Path(args.token_file) session_id = get_session_id(token_file, bundle_names) - log.info("Issuing Dag processor session %s for bundles %s", session_id, ", ".join(sorted(bundle_names))) + _run_token_rotation( + bundle_names, + valid_for, + get_session=lambda: session_id, + publish_token=partial(write_token_file, token_file), + rotate=args.rotate, + ) + + +def _run_token_rotation( + bundle_names: set[str], + valid_for: int, + *, + get_session: Callable[[], UUID], + publish_token: Callable[[str], None], + rotate: bool, + retry_initial_publication: bool = False, +) -> None: issued = False failures = 0 while True: try: + session_id = get_session() token = generate_dag_processor_session_token( create_jwt_generator(), session_id=session_id, bundle_names=bundle_names, valid_for=valid_for ) - write_token_file(token_file, token) - except Exception: - # Without a token to keep, or without rotation, the operator must see the failure. - if not (args.rotate and issued): + publish_token(token) + except Exception as exc: + # A failed first Kubernetes PATCH may already have committed; re-read its session on retry. + if not rotate or not ( + issued or (retry_initial_publication and isinstance(exc, KubernetesSecretTokenError)) + ): raise failures += 1 - log.exception("Could not rotate the session token; the previous one stays valid until it expires") + log.exception("Could not publish the session token; any previous token keeps its original expiry") time.sleep(min(2 ** min(failures, 10), valid_for / 4)) continue issued = True failures = 0 - if not args.rotate: + log.info( + "Published Dag processor session %s for bundles %s", session_id, ", ".join(sorted(bundle_names)) + ) + if not rotate: return time.sleep(valid_for / 2) diff --git a/airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py b/airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py new file mode 100644 index 000000000000..e14cc74ab78b --- /dev/null +++ b/airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py @@ -0,0 +1,145 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Publish Dag processor session tokens to an existing Kubernetes Secret.""" + +from __future__ import annotations + +import base64 +import os +import re +import ssl +from pathlib import Path +from typing import TYPE_CHECKING + +import httpx2 + +if TYPE_CHECKING: + from types import TracebackType + +_SERVICE_ACCOUNT_DIRECTORY = Path("/var/run/secrets/kubernetes.io/serviceaccount") +_TOKEN_KEY = "processor.jwt" +_DNS_LABEL = r"[a-z0-9](?:[-a-z0-9]*[a-z0-9])?" + + +class KubernetesSecretTokenError(RuntimeError): + """A Secret could not be read or updated without exposing its contents.""" + + +class KubernetesSecretTokenStore: + """Read and conditionally update one pre-created Secret using in-cluster credentials.""" + + def __init__(self, secret_name: str, namespace: str): + if len(namespace) > 63 or re.fullmatch(_DNS_LABEL, namespace) is None: + raise ValueError("Kubernetes namespace must be a DNS label of at most 63 characters") + if len(secret_name) > 253 or re.fullmatch(rf"{_DNS_LABEL}(?:\.{_DNS_LABEL})*", secret_name) is None: + raise ValueError("Kubernetes Secret name must be a DNS subdomain of at most 253 characters") + self._path = f"/api/v1/namespaces/{namespace}/secrets/{secret_name}" + self._resource_version: str | None = None + host = os.environ.get("KUBERNETES_SERVICE_HOST") + port = os.environ.get("KUBERNETES_SERVICE_PORT_HTTPS") or os.environ.get("KUBERNETES_SERVICE_PORT") + if not host or not port: + raise ValueError( + "Kubernetes API access requires KUBERNETES_SERVICE_HOST and " + "KUBERNETES_SERVICE_PORT_HTTPS or KUBERNETES_SERVICE_PORT" + ) + try: + port_number = int(port) + if not 1 <= port_number <= 65535: + raise ValueError + except ValueError: + raise ValueError("Kubernetes service port must be an integer between 1 and 65535") from None + self._client = httpx2.Client( + base_url=httpx2.URL(scheme="https", host=host, port=port_number), + verify=ssl.create_default_context(cafile=str(_SERVICE_ACCOUNT_DIRECTORY / "ca.crt")), + timeout=10, + follow_redirects=False, + trust_env=False, + ) + + def __enter__(self) -> KubernetesSecretTokenStore: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self._client.close() + + def _request(self, method: str, *, body: dict | None = None) -> httpx2.Response: + # Kubelet rotates this credential independently of the session token we publish. + try: + bearer = (_SERVICE_ACCOUNT_DIRECTORY / "token").read_text().strip() + except OSError: + raise KubernetesSecretTokenError("Could not read the Kubernetes service account token") from None + if not bearer: + raise KubernetesSecretTokenError("The Kubernetes service account token is empty") + headers = {"Authorization": f"Bearer {bearer}"} + if body is not None: + headers["Content-Type"] = "application/merge-patch+json" + try: + response = self._client.request(method, self._path, headers=headers, json=body) + except httpx2.HTTPError as error: + raise KubernetesSecretTokenError( + f"Kubernetes Secret {method} request failed ({type(error).__name__})" + ) from None + if not response.is_success: + raise KubernetesSecretTokenError( + f"Kubernetes Secret {method} returned HTTP {response.status_code}", + ) + return response + + def read_token(self) -> str | None: + """Read the current token and retain the version required for the next write.""" + self._resource_version = None + response = self._request("GET") + try: + secret = response.json() + resource_version = secret["metadata"]["resourceVersion"] + if not isinstance(resource_version, str) or not resource_version: + raise ValueError + data = secret.get("data") + if data is None: + data = {} + if not isinstance(data, dict): + raise ValueError + encoded = data.get(_TOKEN_KEY, "") + if not isinstance(encoded, str): + raise ValueError + token = base64.b64decode(encoded, validate=True).decode().strip() or None + except (ValueError, TypeError, KeyError, AttributeError): + raise KubernetesSecretTokenError("Kubernetes Secret has invalid token data or metadata") from None + self._resource_version = resource_version + return token + + def write_token(self, token: str) -> None: + """Update only the token, rejecting writes based on a stale Secret version.""" + resource_version = self._resource_version + self._resource_version = None + if resource_version is None: + raise KubernetesSecretTokenError("Read the Kubernetes Secret successfully before writing a token") + if not token.strip(): + raise ValueError("The Dag processor session token must not be empty") + # Consume the version even on an uncertain response: the next attempt must read the persisted session. + self._request( + "PATCH", + body={ + "metadata": {"resourceVersion": resource_version}, + "data": {_TOKEN_KEY: base64.b64encode(token.encode()).decode("ascii")}, + }, + ) diff --git a/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py index b29e94603379..ebace24ffb7c 100644 --- a/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py +++ b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py @@ -27,6 +27,7 @@ from airflow.cli import cli_parser from airflow.cli.commands import dag_processor_token_command +from airflow.cli.commands.dag_processor_token_kubernetes import KubernetesSecretTokenError from airflow.dag_processing.bundles.manager import _load_bundle_config_snapshot from tests_common.test_utils.config import conf_vars @@ -167,6 +168,176 @@ def test_first_write_failure_is_not_retried(self, _, mock_sleep, tmp_path): mock_sleep.assert_not_called() + @pytest.mark.parametrize( + ("args", "error"), + [ + ([], "Choose exactly one"), + (["--token-file", "token", "--kubernetes-secret", "processor"], "Choose exactly one"), + (["--kubernetes-secret", "processor"], "must be supplied together"), + (["--token-file", "token", "--kubernetes-namespace", "processors"], "must be supplied together"), + ], + ) + @mock.patch.object(dag_processor_token_command, "KubernetesSecretTokenStore", autospec=True) + def test_rejects_invalid_output_options(self, store, args, error): + with pytest.raises(SystemExit, match=error): + self._run(*args) + store.assert_not_called() + + +class TestKubernetesTokenCommand: + @pytest.fixture + def secret_store(self): + with mock.patch.object( + dag_processor_token_command, "KubernetesSecretTokenStore", autospec=True + ) as factory: + store = factory.return_value + store.__enter__.return_value = store + published = [] + store.read_token.side_effect = lambda: published[-1] if published else None + store.write_token.side_effect = published.append + yield store, published + + factory.assert_called_with("processor-session", "processors") + store.__exit__.assert_called() + + def _run(self, *args: str) -> None: + dag_processor_token_command.dag_processor_token( + cli_parser.get_parser().parse_args( + [ + "dag-processor-token", + "--kubernetes-secret", + "processor-session", + "--kubernetes-namespace", + "processors", + *args, + ] + ) + ) + + def test_bootstraps_without_a_local_token_file(self, secret_store): + store, published = secret_store + + self._run("-B", "bundle_a") + + claims = _decode(published[0]) + assert claims["scope"] == "dag_processor_session" + assert claims["dag_bundles"] == ["bundle_a"] + assert claims["exp"] - claims["iat"] == 600 + store.read_token.assert_called_once_with() + + @pytest.mark.parametrize("bundle", ["bundle_a", "bundle_b"]) + @pytest.mark.parametrize("elapsed", [0, 601], ids=["unexpired", "expired"]) + def test_restart_recovers_the_session_unless_grants_change( + self, secret_store, bundle, elapsed, time_machine + ): + _, published = secret_store + time_machine.move_to("2026-10-20T12:00:00Z", tick=False) + self._run("-B", "bundle_a") + time_machine.shift(elapsed) + + self._run("-B", bundle) + + first, second = map(_decode, published) + assert (first["sub"] == second["sub"]) == (bundle == "bundle_a") + assert first["jti"] != second["jti"] + assert second["dag_bundles"] == [bundle] + assert second["exp"] - first["exp"] == elapsed + + @mock.patch.object( + dag_processor_token_command.time, "sleep", autospec=True, side_effect=[None, _StopRotation] + ) + def test_rotation_reloads_the_secret_and_preserves_the_session(self, mock_sleep, secret_store): + store, published = secret_store + with pytest.raises(_StopRotation): + self._run("--valid-for", "120", "--rotate") + + first, second = map(_decode, published) + assert first["sub"] == second["sub"] + assert first["jti"] != second["jti"] + assert store.read_token.call_count == 2 + assert mock_sleep.call_args_list == [mock.call(60), mock.call(60)] + + @mock.patch.object( + dag_processor_token_command.time, "sleep", autospec=True, side_effect=[None, _StopRotation] + ) + def test_first_patch_conflict_recovers_the_winning_session(self, mock_sleep, secret_store): + store, published = secret_store + self._run() + winner = published[0] + store.read_token.side_effect = [None, winner] + store.write_token.reset_mock() + store.write_token.side_effect = [KubernetesSecretTokenError("Conflict"), None] + + with pytest.raises(_StopRotation): + self._run("--valid-for", "120", "--rotate") + + rejected, retried = (_decode(call.args[0]) for call in store.write_token.call_args_list) + assert rejected["sub"] != _decode(winner)["sub"] + assert retried["sub"] == _decode(winner)["sub"] + assert mock_sleep.call_args_list == [mock.call(2), mock.call(60)] + + @mock.patch.object( + dag_processor_token_command.time, "sleep", autospec=True, side_effect=[None, _StopRotation] + ) + def test_lost_first_patch_response_recovers_the_published_session(self, mock_sleep, secret_store): + store, published = secret_store + + def publish(token): + published.append(token) + if len(published) == 1: + raise KubernetesSecretTokenError("Response timed out") + + store.write_token.side_effect = publish + with pytest.raises(_StopRotation): + self._run("--valid-for", "120", "--rotate") + + first, second = map(_decode, published) + assert first["sub"] == second["sub"] + assert first["jti"] != second["jti"] + assert mock_sleep.call_args_list == [mock.call(2), mock.call(60)] + + @mock.patch.object( + dag_processor_token_command.time, "sleep", autospec=True, side_effect=[None, _StopRotation] + ) + def test_first_read_failure_is_retried_without_publishing(self, mock_sleep, secret_store): + store, published = secret_store + store.read_token.side_effect = [KubernetesSecretTokenError("API unavailable"), None] + + with pytest.raises(_StopRotation): + self._run("--valid-for", "120", "--rotate") + + assert len(published) == 1 + assert mock_sleep.call_args_list == [mock.call(2), mock.call(60)] + + @mock.patch.object(dag_processor_token_command.time, "sleep", autospec=True) + @pytest.mark.parametrize("operation", ["read_token", "write_token"]) + def test_one_shot_failure_is_reported(self, mock_sleep, secret_store, operation): + store, published = secret_store + getattr(store, operation).side_effect = KubernetesSecretTokenError("Forbidden") + + with pytest.raises(KubernetesSecretTokenError, match="Forbidden"): + self._run() + + assert not published + mock_sleep.assert_not_called() + + @mock.patch.object(dag_processor_token_command.time, "sleep", autospec=True) + @mock.patch.object( + dag_processor_token_command, + "create_jwt_generator", + autospec=True, + side_effect=ValueError("Invalid signing configuration"), + ) + def test_first_signing_failure_exits_without_publishing(self, _, mock_sleep, secret_store): + store, published = secret_store + + with pytest.raises(ValueError, match="Invalid signing configuration"): + self._run("--rotate") + + assert not published + store.write_token.assert_not_called() + mock_sleep.assert_not_called() + class TestWriteTokenFile: def test_creates_the_file_readable_only_by_its_owner(self, tmp_path): diff --git a/airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py new file mode 100644 index 000000000000..9e5a5d92ebd8 --- /dev/null +++ b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py @@ -0,0 +1,359 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from __future__ import annotations + +import base64 +import json +import ssl +import traceback +from functools import partial +from unittest import mock + +import httpx2 +import pytest + +from airflow.cli.commands import dag_processor_token_kubernetes +from airflow.cli.commands.dag_processor_token_kubernetes import ( + KubernetesSecretTokenError, + KubernetesSecretTokenStore, +) + + +def make_secret_response(token: str = "old-session", version: str = "10") -> httpx2.Response: + return httpx2.Response( + 200, + json={ + "metadata": {"resourceVersion": version}, + "data": { + "processor.jwt": base64.b64encode(token.encode()).decode(), + "other-key": base64.b64encode(b"preserved").decode(), + }, + }, + ) + + +@pytest.fixture +def service_account_directory(tmp_path, monkeypatch): + (tmp_path / "token").write_text("service-account-1\n") + monkeypatch.setattr(dag_processor_token_kubernetes, "_SERVICE_ACCOUNT_DIRECTORY", tmp_path) + return tmp_path + + +@pytest.fixture +def make_store(service_account_directory, monkeypatch): + monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.96.0.1") + monkeypatch.setenv("KUBERNETES_SERVICE_PORT", "443") + monkeypatch.delenv("KUBERNETES_SERVICE_PORT_HTTPS", raising=False) + client_class = httpx2.Client + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + create_context = mock.create_autospec(ssl.create_default_context, return_value=context) + monkeypatch.setattr(dag_processor_token_kubernetes.ssl, "create_default_context", create_context) + clients = [] + + def create(*responses): + requests = [] + pending = iter(responses) + + def handle(request): + requests.append(request) + result = next(pending) + if isinstance(result, Exception): + raise result + return result + + def create_client(**kwargs): + return client_class(transport=httpx2.MockTransport(handle), **kwargs) + + factory = mock.create_autospec(client_class, side_effect=create_client) + monkeypatch.setattr(dag_processor_token_kubernetes.httpx2, "Client", factory) + store = KubernetesSecretTokenStore("processor-session", "dag-processors") + clients.append(store) + return store, requests, factory, create_context + + yield create + for store in clients: + store.__exit__(None, None, None) + + +def test_reads_and_conditionally_updates_only_the_token(make_store): + store, requests, _, _ = make_store(make_secret_response(), httpx2.Response(200, json={})) + + with store: + assert store.read_token() == "old-session" + store.write_token("new-session") + + assert [request.method for request in requests] == ["GET", "PATCH"] + assert str(requests[0].url) == ( + "https://10.96.0.1/api/v1/namespaces/dag-processors/secrets/processor-session" + ) + assert requests[1].headers["content-type"] == "application/merge-patch+json" + assert json.loads(requests[1].content) == { + "metadata": {"resourceVersion": "10"}, + "data": {"processor.jwt": base64.b64encode(b"new-session").decode()}, + } + assert store._client.is_closed + + +def test_uses_cluster_ca_and_bounded_direct_requests(make_store, service_account_directory): + store, _, factory, create_context = make_store() + + create_context.assert_called_once_with(cafile=str(service_account_directory / "ca.crt")) + factory.assert_called_once_with( + base_url=httpx2.URL("https://10.96.0.1"), + verify=create_context.return_value, + timeout=10, + follow_redirects=False, + trust_env=False, + ) + with pytest.raises(RuntimeError, match="stop"), store: + raise RuntimeError("stop") + assert store._client.is_closed + + +@pytest.mark.parametrize( + ("host", "https_port", "service_port", "endpoint"), + [ + ("10.96.0.2", None, "443", "https://10.96.0.2"), + ("10.96.0.2", "6443", "443", "https://10.96.0.2:6443"), + ("api.internal", "8443", None, "https://api.internal:8443"), + ("api.internal", "", "8443", "https://api.internal:8443"), + ("fd00::1", None, "6443", "https://[fd00::1]:6443"), + ("fd00::1", "443", "6443", "https://[fd00::1]"), + ], +) +def test_uses_advertised_kubernetes_endpoint( + make_store, monkeypatch, host, https_port, service_port, endpoint +): + for name, value in ( + ("KUBERNETES_SERVICE_HOST", host), + ("KUBERNETES_SERVICE_PORT_HTTPS", https_port), + ("KUBERNETES_SERVICE_PORT", service_port), + ): + if value is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, value) + store, requests, _, _ = make_store(make_secret_response(), httpx2.Response(200)) + + store.read_token() + store.write_token("new-session") + + assert [str(request.url) for request in requests] == [ + f"{endpoint}/api/v1/namespaces/dag-processors/secrets/processor-session" + ] * 2 + + +@pytest.mark.parametrize( + ("host", "port"), + [(None, "443"), ("", "443"), ("10.96.0.1", None), ("10.96.0.1", "")], +) +def test_requires_in_cluster_endpoint_configuration(make_store, monkeypatch, host, port): + for name, value in (("KUBERNETES_SERVICE_HOST", host), ("KUBERNETES_SERVICE_PORT", port)): + if value is None: + monkeypatch.delenv(name, raising=False) + else: + monkeypatch.setenv(name, value) + + with pytest.raises(ValueError, match="Kubernetes API access requires KUBERNETES_SERVICE_HOST"): + make_store() + + +@pytest.mark.parametrize("port", ["not-a-port", "0", "-1", "65536"]) +def test_rejects_invalid_kubernetes_service_port(make_store, monkeypatch, port): + monkeypatch.setenv("KUBERNETES_SERVICE_PORT", port) + + with pytest.raises(ValueError, match="Kubernetes service port must be an integer between 1 and 65535"): + make_store() + + +@pytest.mark.parametrize("data", [None, {}, {"processor.jwt": ""}, {"processor.jwt": "IAo="}]) +def test_accepts_an_uninitialized_secret(make_store, data): + body = {"metadata": {"resourceVersion": "1"}} + if data is not None: + body["data"] = data + store, requests, _, _ = make_store(httpx2.Response(200, json=body), httpx2.Response(200)) + + assert store.read_token() is None + store.write_token("first-session") + + assert json.loads(requests[1].content)["metadata"] == {"resourceVersion": "1"} + + +def test_reloads_service_account_token_for_each_request(make_store, service_account_directory): + store, requests, _, _ = make_store(make_secret_response(), httpx2.Response(200)) + + store.read_token() + (service_account_directory / "token").write_text("service-account-2\n") + store.write_token("new-session") + + assert [request.headers["authorization"] for request in requests] == [ + "Bearer service-account-1", + "Bearer service-account-2", + ] + + +@pytest.mark.parametrize("missing", [False, True]) +def test_rejects_empty_or_unreadable_service_account_token(make_store, service_account_directory, missing): + store, requests, _, _ = make_store() + token_file = service_account_directory / "token" + if missing: + token_file.unlink() + else: + token_file.write_text(" \n") + + with pytest.raises(KubernetesSecretTokenError, match="service account token"): + store.read_token() + + assert not requests + + +@pytest.mark.parametrize("method", ["GET", "PATCH"]) +@pytest.mark.parametrize("status", [302, 403, 404, 409, 422, 503]) +def test_reports_http_failures_without_secret_contents(make_store, method, status): + failure = httpx2.Response( + status, + json={"message": "sensitive-token"}, + headers={"Location": "https://another-service.invalid/"}, + ) + responses = [failure] if method == "GET" else [make_secret_response(), failure] + store, requests, _, _ = make_store(*responses) + if method == "PATCH": + store.read_token() + operation = store.read_token if method == "GET" else partial(store.write_token, "new-session") + + with pytest.raises(KubernetesSecretTokenError, match=f"{method} returned HTTP {status}") as raised: + operation() + + assert "sensitive-token" not in str(raised.value) + assert len(requests) == len(responses) + + +@pytest.mark.parametrize("method", ["GET", "PATCH"]) +@pytest.mark.parametrize("error_type", [httpx2.ConnectError, httpx2.ReadTimeout, httpx2.PoolTimeout]) +def test_reports_transport_failures_without_secret_contents(make_store, method, error_type): + failure = error_type("sensitive-token") + responses = [failure] if method == "GET" else [make_secret_response(), failure] + store, _, _, _ = make_store(*responses) + if method == "PATCH": + store.read_token() + operation = store.read_token if method == "GET" else partial(store.write_token, "new-session") + + with pytest.raises( + KubernetesSecretTokenError, match=rf"{method} request failed \({error_type.__name__}\)" + ) as raised: + operation() + + assert "sensitive-token" not in "".join(traceback.format_exception(raised.value)) + + +@pytest.mark.parametrize( + "body", + [ + None, + [], + {}, + {"metadata": None}, + {"metadata": {"resourceVersion": ""}}, + {"metadata": {"resourceVersion": 10}}, + {"metadata": {"resourceVersion": "10"}, "data": []}, + {"metadata": {"resourceVersion": "10"}, "data": {"processor.jwt": None}}, + {"metadata": {"resourceVersion": "10"}, "data": {"processor.jwt": "invalid!"}}, + {"metadata": {"resourceVersion": "10"}, "data": {"processor.jwt": "/w=="}}, + ], +) +def test_rejects_malformed_secret_without_allowing_a_write(make_store, body): + store, requests, _, _ = make_store(httpx2.Response(200, json=body)) + + with pytest.raises(KubernetesSecretTokenError, match="invalid token data or metadata"): + store.read_token() + with pytest.raises(KubernetesSecretTokenError, match="Read the Kubernetes Secret successfully"): + store.write_token("new-session") + + assert len(requests) == 1 + + +def test_failed_read_invalidates_the_previous_version(make_store): + store, requests, _, _ = make_store(make_secret_response(), httpx2.Response(503)) + store.read_token() + + with pytest.raises(KubernetesSecretTokenError, match="HTTP 503"): + store.read_token() + with pytest.raises(KubernetesSecretTokenError, match="Read the Kubernetes Secret successfully"): + store.write_token("new-session") + + assert [request.method for request in requests] == ["GET", "GET"] + + +@pytest.mark.parametrize( + "write_result", + [ + httpx2.Response(200), + httpx2.Response(409), + httpx2.ReadTimeout("The response was lost after persistence"), + ], +) +def test_each_write_requires_a_new_read_even_after_an_uncertain_response(make_store, write_result): + store, requests, _, _ = make_store( + make_secret_response(), + write_result, + make_secret_response("persisted-session", "11"), + httpx2.Response(200), + ) + store.read_token() + if isinstance(write_result, Exception) or write_result.status_code == 409: + with pytest.raises(KubernetesSecretTokenError): + store.write_token("first-attempt") + else: + store.write_token("first-attempt") + with pytest.raises(KubernetesSecretTokenError, match="Read the Kubernetes Secret successfully"): + store.write_token("must-not-overwrite") + + assert store.read_token() == "persisted-session" + store.write_token("second-attempt") + + assert [request.method for request in requests] == ["GET", "PATCH", "GET", "PATCH"] + assert json.loads(requests[3].content)["metadata"] == {"resourceVersion": "11"} + + +def test_rejects_empty_session_token(make_store): + store, requests, _, _ = make_store(make_secret_response()) + store.read_token() + + with pytest.raises(ValueError, match="must not be empty"): + store.write_token(" \n") + + assert len(requests) == 1 + + +@pytest.mark.parametrize( + ("secret_name", "namespace"), + [ + ("", "processors"), + ("../other-secret", "processors"), + ("secret/another", "processors"), + ("secret..name", "processors"), + ("Secret", "processors"), + ("s" * 254, "processors"), + ("secret", ""), + ("secret", "another/namespace"), + ("secret", "processor.example"), + ("secret", "n" * 64), + ], +) +def test_rejects_invalid_secret_or_namespace_names(secret_name, namespace): + with pytest.raises(ValueError, match="Kubernetes"): + KubernetesSecretTokenStore(secret_name, namespace) diff --git a/chart/tests/helm_tests/airflow_core/test_dag_processor.py b/chart/tests/helm_tests/airflow_core/test_dag_processor.py index 7fdff7fb35a7..38257473dc0e 100644 --- a/chart/tests/helm_tests/airflow_core/test_dag_processor.py +++ b/chart/tests/helm_tests/airflow_core/test_dag_processor.py @@ -16,6 +16,7 @@ # under the License. from __future__ import annotations +import json from configparser import ConfigParser from pathlib import Path from subprocess import CalledProcessError @@ -541,6 +542,102 @@ def test_isolated_api_deployment_example(self): assert policy["egress"][1]["to"][0]["podSelector"]["matchLabels"] == {"k8s-app": "kube-dns"} assert {port["port"] for port in policy["egress"][1]["ports"]} == {53} + def test_kubernetes_token_provisioner_example(self): + examples = Path(__file__).resolve().parents[4] / "airflow-core/docs/security/dag-processor-api" + docs = list(yaml.safe_load_all((examples / "kubernetes-token-provisioner.yaml").read_text())) + resources = {doc["kind"]: doc for doc in docs} + assert len(resources) == len(docs) == 6 + secret = resources["Secret"] + target_namespace = secret["metadata"]["namespace"] + secret_name = secret["metadata"]["name"] + assert resources["Namespace"]["metadata"]["name"] == target_namespace + assert "data" not in secret + assert "stringData" not in secret + assert not secret.get("immutable") + + role = resources["Role"] + assert role["metadata"]["namespace"] == target_namespace + assert role["rules"] == [ + { + "apiGroups": [""], + "resources": ["secrets"], + "resourceNames": [secret_name], + "verbs": ["get", "patch"], + } + ] + account = resources["ServiceAccount"] + trusted_namespace = account["metadata"]["namespace"] + assert trusted_namespace != target_namespace + assert account["automountServiceAccountToken"] is True + binding = resources["RoleBinding"] + assert binding["metadata"]["namespace"] == target_namespace + assert binding["roleRef"] == { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "Role", + "name": role["metadata"]["name"], + } + assert binding["subjects"] == [ + { + "kind": "ServiceAccount", + "name": account["metadata"]["name"], + "namespace": trusted_namespace, + } + ] + + deployment = resources["Deployment"] + assert deployment["metadata"]["namespace"] == trusted_namespace + assert deployment["spec"]["replicas"] == 1 + assert deployment["spec"]["strategy"] == {"type": "Recreate"} + pod = deployment["spec"]["template"]["spec"] + assert pod["serviceAccountName"] == account["metadata"]["name"] + assert pod["automountServiceAccountToken"] is True + assert pod["securityContext"]["runAsNonRoot"] is True + assert pod["securityContext"]["runAsUser"] != 0 + assert pod["volumes"] == [{"name": "tmp", "emptyDir": {}}] + assert not pod.get("initContainers") + assert len(pod["containers"]) == 1 + provisioner = pod["containers"][0] + assert provisioner["args"] == [ + "airflow", + "dag-processor-token", + "--kubernetes-secret", + secret_name, + "--kubernetes-namespace", + target_namespace, + "--bundle-name", + "dags-folder", + "--valid-for", + "600", + "--rotate", + ] + assert provisioner["securityContext"] == { + "allowPrivilegeEscalation": False, + "readOnlyRootFilesystem": True, + "capabilities": {"drop": ["ALL"]}, + } + assert provisioner["resources"]["requests"] + assert provisioner["resources"]["limits"] + assert provisioner["volumeMounts"] == [{"name": "tmp", "mountPath": "/tmp"}] + assert not provisioner.get("envFrom") + env = {entry["name"]: entry for entry in provisioner["env"]} + signing_secret = env.pop("AIRFLOW__API_AUTH__JWT_SECRET")["valueFrom"]["secretKeyRef"] + assert signing_secret == {"name": "airflow-jwt-secret", "key": "jwt-secret"} + bundles = json.loads(env.pop("AIRFLOW__DAG_PROCESSOR__DAG_BUNDLE_CONFIG_LIST")["value"]) + assert {bundle["name"] for bundle in bundles} == {"dags-folder"} + assert {name: entry["value"] for name, entry in env.items()} == { + "AIRFLOW_HOME": "/tmp/airflow", + "AIRFLOW_CONFIG": "/dev/null", + "AIRFLOW__CORE__LOAD_EXAMPLES": "False", + } + + values = yaml.safe_load((examples / "helm-values.yaml").read_text()) + token_volume = next( + volume for volume in values["dagProcessor"]["extraVolumes"] if volume["name"] == "processor-token" + ) + assert token_volume["secret"]["secretName"] == secret_name + assert token_volume["secret"]["secretName"] != signing_secret["name"] + assert provisioner["image"] == f"apache/airflow:{values['defaultAirflowTag']}" + @pytest.mark.parametrize( ("log_values", "expected_volume"), [ From bcb2a0d20e29ed7e1c6b1bfcf2386ff55f3fde3e Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Thu, 22 Oct 2026 13:50:00 +0100 Subject: [PATCH 3/9] Clarify isolated Dag processor credential and migration guidance Catalog synchronization and token provisioning have different credential requirements. Bundle migrations must also avoid having trusted and isolated processors reconcile different inventories for the same bundle. --- .../docs/security/jwt_token_authentication.rst | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/airflow-core/docs/security/jwt_token_authentication.rst b/airflow-core/docs/security/jwt_token_authentication.rst index 0b41755a9651..6312e834dfb7 100644 --- a/airflow-core/docs/security/jwt_token_authentication.rst +++ b/airflow-core/docs/security/jwt_token_authentication.rst @@ -756,17 +756,18 @@ and again whenever the bundle configuration changes:: airflow dag-processor --sync-bundles-only -This step needs database access. Token provisioning itself needs only the API's signing -configuration and the configured bundle names; it does not access the metadata database. - -Kubernetes token provisioner -"""""""""""""""""""""""""""" +This step needs database access and the deployment's Fernet key when signing bundle URLs. +Token provisioning itself needs only the API's JWT signing configuration and the configured +bundle names; it does not access the metadata database. Before starting the isolated processor, stop the trusted deployment's processor for the bundles being moved. If that processor must continue serving other bundles, restrict it with ``--bundle-name`` to those other bundles. This prevents conflicting inventory reconciliation and keeps Dag code for the moved bundles out of the database-credentialed processor. +Kubernetes token provisioner +"""""""""""""""""""""""""""" + For Kubernetes, use the :download:`processor-only Helm values ` in a **separate release and namespace**. These values disable other components and built-in server credential injection. Do not apply them to the release running the scheduler/API server. From 0f3de8f5dfaefff5cd4f6a684daeda692e4c545f Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Fri, 23 Oct 2026 14:54:21 +0100 Subject: [PATCH 4/9] Clarify the Dag processor rollout status check Deployment checks should name the command being described so operators can match the guidance to the example and distinguish process startup from continued token validity. --- airflow-core/docs/security/jwt_token_authentication.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/airflow-core/docs/security/jwt_token_authentication.rst b/airflow-core/docs/security/jwt_token_authentication.rst index 6312e834dfb7..5309f86d7eaf 100644 --- a/airflow-core/docs/security/jwt_token_authentication.rst +++ b/airflow-core/docs/security/jwt_token_authentication.rst @@ -850,9 +850,9 @@ without restarting. Keep the directory mount in the values file: a ``subPath`` m does not receive `Secret updates `_. Choose a token lifetime that leaves time for your cluster's projection delay and transient outages. -The rollout check confirms that the provisioner process started; the Secret-key wait -checks only that a token has been published at least once. Neither check proves that -an existing token is still valid or that rotation continues successfully. +The ``kubectl rollout status`` check confirms that the provisioner process started; +the Secret-key wait checks only that a token has been published at least once. Neither +check proves that an existing token is still valid or that rotation continues successfully. Allow the trusted provisioner to reach the Kubernetes API over TLS if the trusted namespace restricts egress. It uses its mounted service-account token and cluster CA, From 8ad25ad63c17f96edb1a11c6da504bc18b67426e Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Wed, 28 Oct 2026 20:18:13 +0100 Subject: [PATCH 5/9] Use the trusted bundle catalog command in deployment guidance --- airflow-core/docs/security/jwt_token_authentication.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/airflow-core/docs/security/jwt_token_authentication.rst b/airflow-core/docs/security/jwt_token_authentication.rst index 5309f86d7eaf..79e26cbd4c0a 100644 --- a/airflow-core/docs/security/jwt_token_authentication.rst +++ b/airflow-core/docs/security/jwt_token_authentication.rst @@ -754,7 +754,7 @@ Use an image containing processor API support; this feature targets Airflow 3.5. Synchronize the bundle catalog in the trusted deployment before starting the processor, and again whenever the bundle configuration changes:: - airflow dag-processor --sync-bundles-only + airflow dag-processor-sync-bundles This step needs database access and the deployment's Fernet key when signing bundle URLs. Token provisioning itself needs only the API's JWT signing configuration and the configured From c14aa415867208a69a4d6c94fcb13bc17fe89bde Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Thu, 29 Oct 2026 14:52:49 +0100 Subject: [PATCH 6/9] Handle invalid input in the Dag processor token provisioner A token whose subject is not a string, written to the Secret by anything other than the provisioner, made the session lookup raise AttributeError. Kubernetes rotation then re-read that token on every iteration and never replaced it, so the processor's token eventually expired, and file mode crashed at startup the same way. The provisioner now treats such a token as having no session and starts a new one. A bad Secret name, namespace or API port, or a missing cluster CA, ended the command with a traceback, and the CA error did not say which file it tried to load. These now exit with a message that names the problem, including the CA path. The name-validation test could not fail: without the in-cluster environment variables, the store raised a different ValueError that the test's match also accepted. It now sets those variables and matches the DNS-label and DNS-subdomain messages. --- .../commands/dag_processor_token_command.py | 12 +++++- .../dag_processor_token_kubernetes.py | 7 +++- .../test_dag_processor_token_command.py | 22 +++++++++++ .../test_dag_processor_token_kubernetes.py | 38 ++++++++++++------- 4 files changed, 63 insertions(+), 16 deletions(-) diff --git a/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py b/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py index c1fdb077c90e..b8764cb9cd6a 100644 --- a/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py +++ b/airflow-core/src/airflow/cli/commands/dag_processor_token_command.py @@ -84,7 +84,11 @@ def get_session_id_from_token(token: str | None, bundle_names: set[str]) -> UUID with contextlib.suppress(KeyError, TypeError, ValueError, jwt.PyJWTError): # Unverified: only trusted provisioners can write this file or Secret. claims = jwt.decode(token, options={"verify_signature": False}) - if claims["scope"] == "dag_processor_session" and set(claims["dag_bundles"]) == bundle_names: + if ( + claims["scope"] == "dag_processor_session" + and set(claims["dag_bundles"]) == bundle_names + and isinstance(claims["sub"], str) + ): return UUID(claims["sub"]) return uuid6.uuid7() @@ -106,7 +110,11 @@ def dag_processor_token(args) -> None: valid_for = args.valid_for or conf.getint("execution_api", "jwt_expiration_time") if args.kubernetes_secret: - with KubernetesSecretTokenStore(args.kubernetes_secret, args.kubernetes_namespace) as store: + try: + store = KubernetesSecretTokenStore(args.kubernetes_secret, args.kubernetes_namespace) + except ValueError as error: + raise SystemExit(str(error)) from None + with store: _run_token_rotation( bundle_names, valid_for, diff --git a/airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py b/airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py index e14cc74ab78b..2cbe06c241a8 100644 --- a/airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py +++ b/airflow-core/src/airflow/cli/commands/dag_processor_token_kubernetes.py @@ -62,9 +62,14 @@ def __init__(self, secret_name: str, namespace: str): raise ValueError except ValueError: raise ValueError("Kubernetes service port must be an integer between 1 and 65535") from None + ca_file = _SERVICE_ACCOUNT_DIRECTORY / "ca.crt" + try: + verify = ssl.create_default_context(cafile=str(ca_file)) + except OSError as error: + raise ValueError(f"Could not load the Kubernetes cluster CA from {ca_file}: {error}") from None self._client = httpx2.Client( base_url=httpx2.URL(scheme="https", host=host, port=port_number), - verify=ssl.create_default_context(cafile=str(_SERVICE_ACCOUNT_DIRECTORY / "ca.crt")), + verify=verify, timeout=10, follow_redirects=False, trust_env=False, diff --git a/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py index ebace24ffb7c..9cd62a57b2b6 100644 --- a/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py +++ b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_command.py @@ -183,6 +183,10 @@ def test_rejects_invalid_output_options(self, store, args, error): self._run(*args) store.assert_not_called() + def test_reports_invalid_kubernetes_settings_as_an_exit_message(self): + with pytest.raises(SystemExit, match="namespace must be a DNS label"): + self._run("--kubernetes-secret", "processor", "--kubernetes-namespace", "Processors") + class TestKubernetesTokenCommand: @pytest.fixture @@ -257,6 +261,24 @@ def test_rotation_reloads_the_secret_and_preserves_the_session(self, mock_sleep, assert store.read_token.call_count == 2 assert mock_sleep.call_args_list == [mock.call(60), mock.call(60)] + @mock.patch.object( + dag_processor_token_command.time, "sleep", autospec=True, side_effect=[None, _StopRotation] + ) + def test_rotation_replaces_a_secret_holding_a_non_string_session(self, mock_sleep, secret_store): + store, published = secret_store + foreign = jwt.encode( + {"scope": "dag_processor_session", "dag_bundles": ["bundle_a", "bundle_b"], "sub": 123}, + "another-writer-secret-of-32-bytes", + algorithm="HS256", + ) + store.read_token.side_effect = [None, foreign] + with pytest.raises(_StopRotation): + self._run("--valid-for", "120", "--rotate") + + first, second = map(_decode, published) + assert second["sub"] != first["sub"] + assert mock_sleep.call_args_list == [mock.call(60), mock.call(60)] + @mock.patch.object( dag_processor_token_command.time, "sleep", autospec=True, side_effect=[None, _StopRotation] ) diff --git a/airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py index 9e5a5d92ebd8..cb972b9c8cda 100644 --- a/airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py +++ b/airflow-core/tests/unit/cli/commands/test_dag_processor_token_kubernetes.py @@ -124,6 +124,16 @@ def test_uses_cluster_ca_and_bounded_direct_requests(make_store, service_account assert store._client.is_closed +def test_reports_the_path_of_a_missing_cluster_ca(service_account_directory, monkeypatch): + monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.96.0.1") + monkeypatch.setenv("KUBERNETES_SERVICE_PORT", "443") + + with pytest.raises(ValueError, match="Could not load the Kubernetes cluster CA from") as error: + KubernetesSecretTokenStore("processor-session", "dag-processors") + + assert str(service_account_directory / "ca.crt") in str(error.value) + + @pytest.mark.parametrize( ("host", "https_port", "service_port", "endpoint"), [ @@ -340,20 +350,22 @@ def test_rejects_empty_session_token(make_store): @pytest.mark.parametrize( - ("secret_name", "namespace"), + ("secret_name", "namespace", "message"), [ - ("", "processors"), - ("../other-secret", "processors"), - ("secret/another", "processors"), - ("secret..name", "processors"), - ("Secret", "processors"), - ("s" * 254, "processors"), - ("secret", ""), - ("secret", "another/namespace"), - ("secret", "processor.example"), - ("secret", "n" * 64), + ("", "processors", "Secret name must be a DNS subdomain"), + ("../other-secret", "processors", "Secret name must be a DNS subdomain"), + ("secret/another", "processors", "Secret name must be a DNS subdomain"), + ("secret..name", "processors", "Secret name must be a DNS subdomain"), + ("Secret", "processors", "Secret name must be a DNS subdomain"), + ("s" * 254, "processors", "Secret name must be a DNS subdomain"), + ("secret", "", "namespace must be a DNS label"), + ("secret", "another/namespace", "namespace must be a DNS label"), + ("secret", "processor.example", "namespace must be a DNS label"), + ("secret", "n" * 64, "namespace must be a DNS label"), ], ) -def test_rejects_invalid_secret_or_namespace_names(secret_name, namespace): - with pytest.raises(ValueError, match="Kubernetes"): +def test_rejects_invalid_secret_or_namespace_names(monkeypatch, secret_name, namespace, message): + monkeypatch.setenv("KUBERNETES_SERVICE_HOST", "10.96.0.1") + monkeypatch.setenv("KUBERNETES_SERVICE_PORT", "443") + with pytest.raises(ValueError, match=message): KubernetesSecretTokenStore(secret_name, namespace) From 74c58a48bea843d4ba07a31280f0a305aef3e345 Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Thu, 29 Oct 2026 14:52:49 +0100 Subject: [PATCH 7/9] Fix the isolated Dag processor deployment examples and chart checks The token provisioner example signed with the key in the chart's generated -jwt-secret. Every helm upgrade of the trusted release writes a new key there and rolls the API server onto it, but the provisioner keeps the old key in its environment until it restarts, so the API server rejected every token it issued after an upgrade. The example now reads a pre-created Secret that the trusted release also uses as jwtSecretName. The processor-only Helm values set LocalExecutor just to pass the chart's validation, which also made the processor parse Dags with a different [core] executor from the trusted deployment. Tasks naming another executor then failed to import. The example now sets the processor's executor to match, and the guide says it must. The chart chooses probes, update strategy and the replica limit only from config.dag_processor.execution_api_token_file. Setting the token file through AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE instead kept a liveness probe that fails without database credentials, so the chart now rejects that variable. The chart tests now also cover rendering without a token file, including a null config.dag_processor. The guide overstated how close to token expiry a Kubernetes API outage can end without stopping the processor, because it left out the retry backoff and the Secret projection delay. Its install command also lacked a chart version, and a few smaller statements were wrong. No CI job ran the Compose deployment example tests, so the quick-start Compose job now runs them. --- .../workflows/additional-prod-image-tests.yml | 4 ++ .../dag-processor-api/helm-values.yaml | 4 ++ .../kubernetes-token-provisioner.yaml | 6 +- .../security/jwt_token_authentication.rst | 53 +++++++++++++---- .../dag-processor-deployment.yaml | 5 ++ .../airflow_core/test_dag_processor.py | 57 ++++++++++++++++++- .../testing/docker_compose_tests.rst | 7 +++ 7 files changed, 121 insertions(+), 15 deletions(-) diff --git a/.github/workflows/additional-prod-image-tests.yml b/.github/workflows/additional-prod-image-tests.yml index 505d56d2649a..841a572cdd8d 100644 --- a/.github/workflows/additional-prod-image-tests.yml +++ b/.github/workflows/additional-prod-image-tests.yml @@ -253,6 +253,10 @@ jobs: use-uv: ${{ inputs.use-uv }} make-mnt-writeable-and-cleanup: true id: breeze + - name: "Test Dag processor API deployment examples" + run: > + cd ./docker-tests && + uv run pytest tests/docker_tests/test_dag_processor_api_deployment.py --color=yes - name: "Test docker-compose quick start" run: breeze testing docker-compose-tests diff --git a/airflow-core/docs/security/dag-processor-api/helm-values.yaml b/airflow-core/docs/security/dag-processor-api/helm-values.yaml index 1013e3ef5d55..1b06b3ebc54e 100644 --- a/airflow-core/docs/security/dag-processor-api/helm-values.yaml +++ b/airflow-core/docs/security/dag-processor-api/helm-values.yaml @@ -19,6 +19,7 @@ # Apply kubernetes-token-provisioner.yaml first, using an image with API mode. airflowVersion: "3.5.0" defaultAirflowTag: "3.5.0" +# Only satisfies the chart's executor validation; the processor's executor is set in dagProcessor.env. executor: LocalExecutor scheduler: enabled: false @@ -60,6 +61,9 @@ dagProcessor: env: - name: CONNECTION_CHECK_MAX_COUNT value: "0" + # Match the trusted deployment's [core] executor: parsing fails for tasks naming any other executor. + - name: AIRFLOW__CORE__EXECUTOR + value: CeleryExecutor extraVolumes: - name: processor-token secret: diff --git a/airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml b/airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml index 3f664a9757a5..b264f11fddcf 100644 --- a/airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml +++ b/airflow-core/docs/security/dag-processor-api/kubernetes-token-provisioner.yaml @@ -116,8 +116,10 @@ spec: - name: AIRFLOW__API_AUTH__JWT_SECRET valueFrom: secretKeyRef: - # Match the trusted API server's jwtSecretName (default: -jwt-secret). - name: airflow-jwt-secret + # A pre-created Secret that the trusted release uses as its jwtSecretName. Do not use + # the chart-generated -jwt-secret: every helm upgrade replaces its key, and + # this variable keeps the old key until the provisioner restarts. + name: airflow-jwt-signing-key key: jwt-secret securityContext: allowPrivilegeEscalation: false diff --git a/airflow-core/docs/security/jwt_token_authentication.rst b/airflow-core/docs/security/jwt_token_authentication.rst index 79e26cbd4c0a..b0814c67fc1c 100644 --- a/airflow-core/docs/security/jwt_token_authentication.rst +++ b/airflow-core/docs/security/jwt_token_authentication.rst @@ -737,7 +737,11 @@ scheduling margin. For Helm, set the token-file option under ``config.dag_processor`` to select the local probe. The chart then replaces processor pods with the ``Recreate`` strategy, because pods that share a session token cannot run their Jobs side by side, and rejects more than one -replica for the same reason. Disable the processor's migration-wait init container, provision the catalog +replica for the same reason. It does not select those settings for the +``AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE`` environment variable, and rejects that +variable in ``env`` and ``dagProcessor.env``. Do not set it through ``secret``, ``extraEnv``, +or ``extraEnvFrom`` either; the chart does not check those. +Disable the processor's migration-wait init container, provision the catalog separately, and remove server credentials from the pod. The Compose example selects the local probe when ``AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE`` is set. Neither the main chart release nor the quick-start Compose file removes shared credentials or adds @@ -760,6 +764,10 @@ This step needs database access and the deployment's Fernet key when signing bun Token provisioning itself needs only the API's JWT signing configuration and the configured bundle names; it does not access the metadata database. +Configure the processor's ``[core] executor``, and ``[core] multi_team`` with its team +executors, to match the trusted deployment. Parsing records an import error for any Dag with +a task whose ``executor`` is not configured on the processor. + Before starting the isolated processor, stop the trusted deployment's processor for the bundles being moved. If that processor must continue serving other bundles, restrict it with ``--bundle-name`` to those other bundles. This prevents conflicting inventory reconciliation @@ -785,15 +793,27 @@ Customize both files before applying them: * Set both images to an image containing this feature. The manifest assumes the trusted release and namespace are named ``airflow``; update namespace references, the API service address, and NetworkPolicy selectors together if yours differ. -* Point the provisioner's ``AIRFLOW__API_AUTH__JWT_SECRET`` at the API server's signing - Secret. For the Helm chart's default configuration this is ``-jwt-secret``, - key ``jwt-secret``; ``jwtSecretName`` overrides the Secret name. For asymmetric signing, - replace this environment variable with the matching private-key mount and +* Pin the trusted release's signing key, and point the provisioner's + ``AIRFLOW__API_AUTH__JWT_SECRET`` at the same Secret. Create a Secret with the key + ``jwt-secret``, and set the trusted release's ``jwtSecretName`` to its name, as the + :doc:`chart production guide ` recommends. The manifest + expects it as ``airflow-jwt-signing-key``. Do not use the chart-generated + ``-jwt-secret`` unless ``jwtSecret`` holds a fixed value: otherwise every + ``helm upgrade`` of the trusted release generates a new key. The API server switches to + the new key, but the provisioner keeps signing with the old one until it restarts, so the + API rejects the processor's requests. For asymmetric signing, replace this + environment variable with the matching private-key mount and ``AIRFLOW__API_AUTH__JWT_PRIVATE_KEY_PATH``. * Copy any non-default signing algorithm, key ID, issuer, and execution API audience settings from the API server. Do not copy database credentials or the entire server configuration into the provisioner. Restart the provisioner when its signing - configuration changes, including a signing Secret supplied through environment variables. + configuration changes, including a signing Secret supplied through environment variables + (``kubectl -n airflow rollout restart deployment/dag-processor-token-provisioner``). +* Set ``AIRFLOW__CORE__EXECUTOR`` in the values file's ``dagProcessor.env`` to the trusted + deployment's ``[core] executor``; the example assumes the chart's default + ``CeleryExecutor``. The values file's top-level ``executor`` only satisfies the chart's + validation for a release without a broker, and the chart rejects a ``config.core.executor`` + that differs from it. * Match ``--bundle-name`` and ``AIRFLOW__DAG_PROCESSOR__DAG_BUNDLE_CONFIG_LIST`` to the catalog and processor configuration. Repeat ``--bundle-name`` for additional bundles. Provisioning reads their names without loading bundle classes or fetching Dag files. @@ -824,13 +844,16 @@ To adopt an existing processor Secret while preserving its session: the last-applied configuration and cause the provisioner to create a new session. After preparing the files for a fresh deployment or adoption, start the provisioner -and then the processor:: +and then the processor. Replace ```` with a chart release that supports +``config.dag_processor.execution_api_token_file``. Earlier releases keep the database-backed +liveness probe, which fails without database credentials, and rolling updates, in which the +new pod cannot register while the old pod holds the session:: kubectl apply -f kubernetes-token-provisioner.yaml kubectl -n airflow rollout status deployment/dag-processor-token-provisioner kubectl -n airflow-dag-processor wait --for=jsonpath='{.data.processor\.jwt}' secret/dag-processor-session --timeout=120s kubectl -n airflow-dag-processor apply -f network-policy.yaml - helm upgrade --install dag-processor apache-airflow/airflow \ + helm upgrade --install dag-processor apache-airflow/airflow --version \ --namespace airflow-dag-processor --values helm-values.yaml For Secrets created by this example, the manifest deliberately omits ``data`` and @@ -859,10 +882,16 @@ namespace restricts egress. It uses its mounted service-account token and cluste and reloads that credential on each request. In rotation mode, Kubernetes read and update failures are retried with backoff, including during initial issuance. Initial signing or configuration errors exit the command and Kubernetes restarts it. Later rotation failures -also retry; the previous token remains usable until it expires. An outage lasting beyond expiry -prevents the processor from renewing its API credentials. Monitor provisioner failures -and processor readiness, and restore Kubernetes API access or signing configuration -before the token expires. Monitor the token's expiry without logging its value. +also retry; the previous token remains usable until it expires. The delay between retries +doubles from 2 seconds up to the smaller of 1024 seconds and a quarter of the token +lifetime: 150 seconds with ``--valid-for 600``. The processor keeps its API credentials +only if a retry succeeds and Kubernetes projects the new token before the previous one +expires. Restore Kubernetes API access or signing configuration at least that maximum +delay plus your cluster's projection delay before the token expires. Otherwise the +processor stops when the API rejects its +expired credentials, and recovers only after Kubernetes restarts it with a newly projected +token. Monitor provisioner failures and processor readiness, and monitor the token's expiry +without logging its value. Compose token provisioner """"""""""""""""""""""""" diff --git a/chart/templates/dag-processor/dag-processor-deployment.yaml b/chart/templates/dag-processor/dag-processor-deployment.yaml index 09b1b11027dc..98dbc5c6fe39 100644 --- a/chart/templates/dag-processor/dag-processor-deployment.yaml +++ b/chart/templates/dag-processor/dag-processor-deployment.yaml @@ -24,6 +24,11 @@ {{- if and (get (.Values.config.dag_processor | default dict) "execution_api_token_file") (gt (int .Values.dagProcessor.replicas) 1) }} {{- fail "`dagProcessor.replicas` must not exceed 1 when `config.dag_processor.execution_api_token_file` is set, because the pods would share one session token. Deploy a separate release, with its own token, for each additional processor." }} {{- end }} +{{- range concat (.Values.env | default list) (.Values.dagProcessor.env | default list) }} +{{- if eq .name "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE" }} +{{- fail "Set the Dag processor token file with `config.dag_processor.execution_api_token_file`, not the `AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE` environment variable: the chart selects probes, update strategy and replica limits that work without database credentials only from the config value." }} +{{- end }} +{{- end }} {{- $nodeSelector := or .Values.dagProcessor.nodeSelector .Values.nodeSelector }} {{- $affinity := or .Values.dagProcessor.affinity .Values.affinity }} {{- $tolerations := or .Values.dagProcessor.tolerations .Values.tolerations }} diff --git a/chart/tests/helm_tests/airflow_core/test_dag_processor.py b/chart/tests/helm_tests/airflow_core/test_dag_processor.py index 38257473dc0e..01f89c45209d 100644 --- a/chart/tests/helm_tests/airflow_core/test_dag_processor.py +++ b/chart/tests/helm_tests/airflow_core/test_dag_processor.py @@ -478,6 +478,37 @@ def test_api_mode_rejects_replicas_sharing_a_session_token(self, replicas, rejec docs = render_chart(values=values, show_only=show_only) assert jmespath.search("spec.replicas", docs[0]) == replicas + @pytest.mark.parametrize( + "values", + [ + {"env": [{"name": "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE", "value": "/run/t"}]}, + { + "dagProcessor": { + "env": [{"name": "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE", "value": "/run/t"}] + } + }, + ], + ids=["env", "dagProcessor.env"], + ) + def test_rejects_the_token_file_environment_variable(self, values): + with pytest.raises(CalledProcessError, match="config.dag_processor.execution_api_token_file"): + render_chart(values=values, show_only=["templates/dag-processor/dag-processor-deployment.yaml"]) + + @pytest.mark.parametrize("config", [{}, {"dag_processor": None}]) + def test_database_mode_keeps_database_probe_and_replicas(self, config): + docs = render_chart( + values={"config": config, "dagProcessor": {"replicas": 2}}, + show_only=["templates/dag-processor/dag-processor-deployment.yaml"], + ) + + assert jmespath.search("spec.replicas", docs[0]) == 2 + container = jmespath.search("spec.template.spec.containers[0]", docs[0]) + assert "readinessProbe" not in container + assert ( + "airflow jobs check --local --job-type DagProcessorJob" + in container["livenessProbe"]["exec"]["command"][-1] + ) + def test_isolated_api_deployment_example(self): examples = Path(__file__).resolve().parents[4] / "airflow-core/docs/security/dag-processor-api" values = yaml.safe_load((examples / "helm-values.yaml").read_text()) @@ -493,9 +524,13 @@ def test_isolated_api_deployment_example(self): assert not container.get("envFrom") assert all("valueFrom" not in env for env in container.get("env", [])) processor = next(container for container in pod["containers"] if container["name"] == "dag-processor") + trusted_executor = yaml.safe_load((Path(__file__).resolve().parents[3] / "values.yaml").read_text())[ + "executor" + ] assert {env["name"]: env["value"] for env in processor["env"]} == { "AIRFLOW_HOME": "/opt/airflow", "CONNECTION_CHECK_MAX_COUNT": "0", + "AIRFLOW__CORE__EXECUTOR": trusted_executor, } assert "--check-health" in processor["livenessProbe"]["exec"]["command"][-1] assert "--check-ready" in processor["readinessProbe"]["exec"]["command"][-1] @@ -621,7 +656,7 @@ def test_kubernetes_token_provisioner_example(self): assert not provisioner.get("envFrom") env = {entry["name"]: entry for entry in provisioner["env"]} signing_secret = env.pop("AIRFLOW__API_AUTH__JWT_SECRET")["valueFrom"]["secretKeyRef"] - assert signing_secret == {"name": "airflow-jwt-secret", "key": "jwt-secret"} + assert signing_secret == {"name": "airflow-jwt-signing-key", "key": "jwt-secret"} bundles = json.loads(env.pop("AIRFLOW__DAG_PROCESSOR__DAG_BUNDLE_CONFIG_LIST")["value"]) assert {bundle["name"] for bundle in bundles} == {"dags-folder"} assert {name: entry["value"] for name, entry in env.items()} == { @@ -638,6 +673,26 @@ def test_kubernetes_token_provisioner_example(self): assert token_volume["secret"]["secretName"] != signing_secret["name"] assert provisioner["image"] == f"apache/airflow:{values['defaultAirflowTag']}" + def test_kubernetes_token_provisioner_example_uses_a_pinned_signing_key(self): + examples = Path(__file__).resolve().parents[4] / "airflow-core/docs/security/dag-processor-api" + docs = yaml.safe_load_all((examples / "kubernetes-token-provisioner.yaml").read_text()) + deployment = next(doc for doc in docs if doc["kind"] == "Deployment") + env = deployment["spec"]["template"]["spec"]["containers"][0]["env"] + signing_secret = next(entry for entry in env if entry["name"] == "AIRFLOW__API_AUTH__JWT_SECRET") + policy = yaml.safe_load((examples / "network-policy.yaml").read_text())["spec"] + trusted_release = policy["egress"][0]["to"][0]["podSelector"]["matchLabels"]["release"] + + generated = render_chart(name=trusted_release, show_only=["templates/secrets/jwt-secret.yaml"]) + generated_names = {doc["metadata"]["name"] for doc in generated} + assert generated_names == {f"{trusted_release}-jwt-secret"} + assert signing_secret["valueFrom"]["secretKeyRef"]["name"] not in generated_names + pinned = render_chart( + name=trusted_release, + values={"jwtSecretName": signing_secret["valueFrom"]["secretKeyRef"]["name"]}, + show_only=["templates/api-server/api-server-deployment.yaml"], + ) + assert signing_secret in jmespath.search("spec.template.spec.containers[0].env", pinned[0]) + @pytest.mark.parametrize( ("log_values", "expected_volume"), [ diff --git a/contributing-docs/testing/docker_compose_tests.rst b/contributing-docs/testing/docker_compose_tests.rst index a225264323d7..2b3aa0e132e2 100644 --- a/contributing-docs/testing/docker_compose_tests.rst +++ b/contributing-docs/testing/docker_compose_tests.rst @@ -64,6 +64,13 @@ You can also add ``-s`` option to the command pass it to underlying pytest comma to see the output of the test as it happens (it can be also set via ``WAIT_FOR_CONTAINERS_TIMEOUT`` environment variable) +The same CI job also checks the Dag processor API deployment examples. That test needs only +``docker compose config``, not a running deployment or the PROD image: + +.. code-block:: bash + + cd docker-tests && uv run pytest tests/docker_tests/test_dag_processor_api_deployment.py + The test can be also run manually with ``pytest docker_tests/test_docker_compose_quick_start.py`` command, provided that you have a local Airflow venv with ``dev`` extra set and the ``DOCKER_IMAGE`` environment variable is set to the image you want to test. The variable defaults From 7613c27290f346a55581a95a98a987be13857912 Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Tue, 10 Nov 2026 17:08:51 +0100 Subject: [PATCH 8/9] Select the chart's Dag processor API mode from use_execution_api The Dag processor now enters API mode only when [dag_processor] use_execution_api is enabled; execution_api_token_file is just the credential source. The chart still chose the local probes, the Recreate strategy and the one-replica limit from the token file, so a release that set only the token file ran a database-mode processor with API-mode probes. "airflow dag-processor --check-health" then exits because local health probes need API mode, and Kubernetes restarts the pod in a loop. A processor with API mode enabled and no token file fails at startup, so the chart refuses to render that combination instead of deploying a pod that cannot start. Setting AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API in env or dagProcessor.env would bypass the chart's API-mode settings the same way the token-file variable did, so the chart rejects it too. The quick-start Compose healthcheck tested the token file in the same way, so it now follows use_execution_api as well. --- .../howto/docker-compose/docker-compose.yaml | 9 ++- .../dag-processor-api/helm-values.yaml | 1 + .../security/jwt_token_authentication.rst | 20 +++--- chart/templates/_helpers.yaml | 11 ++- .../dag-processor-deployment.yaml | 18 +++-- .../airflow_core/test_dag_processor.py | 70 ++++++++++++++----- chart/values.schema.json | 4 +- chart/values.yaml | 4 +- .../test_dag_processor_api_deployment.py | 26 +++++-- 9 files changed, 112 insertions(+), 51 deletions(-) diff --git a/airflow-core/docs/howto/docker-compose/docker-compose.yaml b/airflow-core/docs/howto/docker-compose/docker-compose.yaml index be749b92e0ee..06c2855df555 100644 --- a/airflow-core/docs/howto/docker-compose/docker-compose.yaml +++ b/airflow-core/docs/howto/docker-compose/docker-compose.yaml @@ -158,11 +158,10 @@ services: test: - CMD-SHELL - >- - if [ -n "$${AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE:-}" ]; then - airflow dag-processor --check-health; - else - airflow jobs check --job-type DagProcessorJob --hostname "$${HOSTNAME}"; - fi + case "$${AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API:-}" in + [Tt] | [Tt][Rr][Uu][Ee] | 1) airflow dag-processor --check-health;; + *) airflow jobs check --job-type DagProcessorJob --hostname "$${HOSTNAME}";; + esac interval: 30s timeout: 10s retries: 5 diff --git a/airflow-core/docs/security/dag-processor-api/helm-values.yaml b/airflow-core/docs/security/dag-processor-api/helm-values.yaml index 1b06b3ebc54e..4403399492ae 100644 --- a/airflow-core/docs/security/dag-processor-api/helm-values.yaml +++ b/airflow-core/docs/security/dag-processor-api/helm-values.yaml @@ -51,6 +51,7 @@ config: core: execution_api_server_url: http://airflow-api-server.airflow.svc.cluster.local:8080/execution/ dag_processor: + use_execution_api: "True" execution_api_token_file: /run/dag-processor/processor.jwt dagProcessor: replicas: 1 diff --git a/airflow-core/docs/security/jwt_token_authentication.rst b/airflow-core/docs/security/jwt_token_authentication.rst index b0814c67fc1c..4c1729e7406e 100644 --- a/airflow-core/docs/security/jwt_token_authentication.rst +++ b/airflow-core/docs/security/jwt_token_authentication.rst @@ -734,16 +734,18 @@ one second, and waiting for parsing processes can take another second without a ``health_check_threshold`` above five times that timeout plus three seconds, with additional scheduling margin. -For Helm, set the token-file option under ``config.dag_processor`` to select the local -probe. The chart then replaces processor pods with the ``Recreate`` strategy, because pods +For Helm, enable ``use_execution_api`` under ``config.dag_processor`` to select the local +probes, and set ``execution_api_token_file`` there too: the chart refuses to render API mode +without a token file, and a token file alone keeps the database-backed probe. In API mode the +chart replaces processor pods with the ``Recreate`` strategy, because pods that share a session token cannot run their Jobs side by side, and rejects more than one -replica for the same reason. It does not select those settings for the -``AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE`` environment variable, and rejects that -variable in ``env`` and ``dagProcessor.env``. Do not set it through ``secret``, ``extraEnv``, -or ``extraEnvFrom`` either; the chart does not check those. +replica for the same reason. It does not select those settings from the +``AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API`` or ``AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE`` +environment variables, and rejects them in ``env`` and ``dagProcessor.env``. Do not set them +through ``secret``, ``extraEnv``, or ``extraEnvFrom`` either; the chart does not check those. Disable the processor's migration-wait init container, provision the catalog -separately, and remove server credentials from the pod. The Compose example selects the -local probe when ``AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE`` is set. Neither the +separately, and remove server credentials from the pod. The quick-start Compose file selects the +local probe when ``AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API`` is true. Neither the main chart release nor the quick-start Compose file removes shared credentials or adds database-denying network policies automatically; the isolated examples below do. Set ``CONNECTION_CHECK_MAX_COUNT=0`` in the processor container too: the standard image @@ -845,7 +847,7 @@ To adopt an existing processor Secret while preserving its session: After preparing the files for a fresh deployment or adoption, start the provisioner and then the processor. Replace ```` with a chart release that supports -``config.dag_processor.execution_api_token_file``. Earlier releases keep the database-backed +``config.dag_processor.use_execution_api``. Earlier releases keep the database-backed liveness probe, which fails without database credentials, and rolling updates, in which the new pod cannot register while the old pod holds the session:: diff --git a/chart/templates/_helpers.yaml b/chart/templates/_helpers.yaml index 870275fabbb5..599baa25bf13 100644 --- a/chart/templates/_helpers.yaml +++ b/chart/templates/_helpers.yaml @@ -853,6 +853,15 @@ server_tls_key_file = /etc/pgbouncer/server.key {{- include "_serviceAccountName" (merge (dict "key" "dagProcessor" "nameSuffix" "dag-processor") .) -}} {{- end }} +{{/* +Render "true" when config.dag_processor.use_execution_api enables the Dag processor's API mode. +Accepts the values Airflow reads as true, so a string "False" keeps database mode. +*/}} +{{- define "dagProcessor.useExecutionApi" -}} + {{- $value := get (.Values.config.dag_processor | default dict) "use_execution_api" | toString -}} + {{- if has (tpl $value . | trim | lower) (list "t" "true" "1") }}true{{ end -}} +{{- end }} + {{/* Create the name of the pgbouncer service account to use */}} {{- define "pgbouncer.serviceAccountName" -}} {{- include "_serviceAccountName" (merge (dict "key" "pgbouncer") .) -}} @@ -904,7 +913,7 @@ server_tls_key_file = /etc/pgbouncer/server.key - sh - -c - | - {{- if (get (.Values.config.dag_processor | default dict) "execution_api_token_file") }} + {{- if include "dagProcessor.useExecutionApi" . }} CONNECTION_CHECK_MAX_COUNT=0 AIRFLOW__LOGGING__LOGGING_LEVEL=ERROR exec /entrypoint \ airflow dag-processor --check-health {{- else }} diff --git a/chart/templates/dag-processor/dag-processor-deployment.yaml b/chart/templates/dag-processor/dag-processor-deployment.yaml index 98dbc5c6fe39..8b330288ba2d 100644 --- a/chart/templates/dag-processor/dag-processor-deployment.yaml +++ b/chart/templates/dag-processor/dag-processor-deployment.yaml @@ -21,13 +21,17 @@ ## Airflow Dag Processor Deployment ################################# {{- if .Values.dagProcessor.enabled }} -{{- if and (get (.Values.config.dag_processor | default dict) "execution_api_token_file") (gt (int .Values.dagProcessor.replicas) 1) }} -{{- fail "`dagProcessor.replicas` must not exceed 1 when `config.dag_processor.execution_api_token_file` is set, because the pods would share one session token. Deploy a separate release, with its own token, for each additional processor." }} -{{- end }} {{- range concat (.Values.env | default list) (.Values.dagProcessor.env | default list) }} -{{- if eq .name "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE" }} -{{- fail "Set the Dag processor token file with `config.dag_processor.execution_api_token_file`, not the `AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE` environment variable: the chart selects probes, update strategy and replica limits that work without database credentials only from the config value." }} +{{- if has .name (list "AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API" "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE") }} +{{- fail (printf "Configure Dag processor API mode with `config.dag_processor.use_execution_api` and `config.dag_processor.execution_api_token_file`, not the `%s` environment variable: the chart selects probes, update strategy and replica limits that work without database credentials only from the config values." .name) }} +{{- end }} +{{- end }} +{{- $useExecutionApi := include "dagProcessor.useExecutionApi" . }} +{{- if and $useExecutionApi (not (get (.Values.config.dag_processor | default dict) "execution_api_token_file")) }} +{{- fail "`config.dag_processor.use_execution_api` requires `config.dag_processor.execution_api_token_file`: the Dag processor fails at startup without a session token to authenticate to the Execution API." }} {{- end }} +{{- if and $useExecutionApi (gt (int .Values.dagProcessor.replicas) 1) }} +{{- fail "`dagProcessor.replicas` must not exceed 1 when `config.dag_processor.use_execution_api` is enabled, because the pods would share one session token. Deploy a separate release, with its own token, for each additional processor." }} {{- end }} {{- $nodeSelector := or .Values.dagProcessor.nodeSelector .Values.nodeSelector }} {{- $affinity := or .Values.dagProcessor.affinity .Values.affinity }} @@ -66,7 +70,7 @@ spec: tier: airflow component: dag-processor release: {{ .Release.Name }} - {{- if (get (.Values.config.dag_processor | default dict) "execution_api_token_file") }} + {{- if $useExecutionApi }} {{- /* Pods share one session token, and a new pod can register its Job only after the old one stops. */}} strategy: type: Recreate @@ -203,7 +207,7 @@ spec: {{- include "standard_airflow_environment" . | indent 10 }} {{- include "metadata_db_environment" . | indent 10 }} {{- include "container_extra_envs" (list . .Values.dagProcessor.env) | indent 10 }} - {{- if (get (.Values.config.dag_processor | default dict) "execution_api_token_file") }} + {{- if $useExecutionApi }} readinessProbe: timeoutSeconds: {{ .Values.dagProcessor.livenessProbe.timeoutSeconds }} periodSeconds: {{ .Values.dagProcessor.livenessProbe.periodSeconds }} diff --git a/chart/tests/helm_tests/airflow_core/test_dag_processor.py b/chart/tests/helm_tests/airflow_core/test_dag_processor.py index 01f89c45209d..b0c451a9bee7 100644 --- a/chart/tests/helm_tests/airflow_core/test_dag_processor.py +++ b/chart/tests/helm_tests/airflow_core/test_dag_processor.py @@ -27,6 +27,8 @@ from chart_utils.helm_template_generator import render_chart from chart_utils.log_groomer import LogGroomerTestBase +API_MODE_CONFIG = {"use_execution_api": "True", "execution_api_token_file": "/run/processor.jwt"} + class TestDagProcessor: """Tests DAG processor.""" @@ -440,9 +442,17 @@ def test_livenessprobe_command(self): in jmespath.search("spec.template.spec.containers[0].livenessProbe.exec.command", docs[0])[-1] ) - def test_api_mode_uses_local_liveness_probe(self): + @pytest.mark.parametrize("use_execution_api", [True, "True", "true", "t", "1"]) + def test_api_mode_uses_local_liveness_probe(self, use_execution_api): docs = render_chart( - values={"config": {"dag_processor": {"execution_api_token_file": "/run/processor.jwt"}}}, + values={ + "config": { + "dag_processor": { + "use_execution_api": use_execution_api, + "execution_api_token_file": "/run/processor.jwt", + } + } + }, show_only=["templates/dag-processor/dag-processor-deployment.yaml"], ) command = jmespath.search("spec.template.spec.containers[0].livenessProbe.exec.command", docs[0])[-1] @@ -454,7 +464,7 @@ def test_api_mode_uses_local_liveness_probe(self): def test_api_mode_replaces_pods_with_recreate(self): docs = render_chart( values={ - "config": {"dag_processor": {"execution_api_token_file": "/run/processor.jwt"}}, + "config": {"dag_processor": API_MODE_CONFIG}, "dagProcessor": { "strategy": {"rollingUpdate": {"maxSurge": "100%", "maxUnavailable": "50%"}} }, @@ -467,7 +477,7 @@ def test_api_mode_replaces_pods_with_recreate(self): @pytest.mark.parametrize(("replicas", "rejected"), [(0, False), (1, False), (2, True)]) def test_api_mode_rejects_replicas_sharing_a_session_token(self, replicas, rejected): values = { - "config": {"dag_processor": {"execution_api_token_file": "/run/processor.jwt"}}, + "config": {"dag_processor": API_MODE_CONFIG}, "dagProcessor": {"replicas": replicas}, } show_only = ["templates/dag-processor/dag-processor-deployment.yaml"] @@ -479,29 +489,52 @@ def test_api_mode_rejects_replicas_sharing_a_session_token(self, replicas, rejec assert jmespath.search("spec.replicas", docs[0]) == replicas @pytest.mark.parametrize( - "values", - [ - {"env": [{"name": "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE", "value": "/run/t"}]}, - { - "dagProcessor": { - "env": [{"name": "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE", "value": "/run/t"}] - } - }, - ], - ids=["env", "dagProcessor.env"], + "dag_processor", + [{"use_execution_api": "True"}, {"use_execution_api": "True", "execution_api_token_file": ""}], + ids=["unset", "empty"], ) - def test_rejects_the_token_file_environment_variable(self, values): - with pytest.raises(CalledProcessError, match="config.dag_processor.execution_api_token_file"): + def test_api_mode_requires_a_token_file(self, dag_processor): + with pytest.raises( + CalledProcessError, + match="use_execution_api` requires `config.dag_processor.execution_api_token_file", + ): + render_chart( + values={"config": {"dag_processor": dag_processor}}, + show_only=["templates/dag-processor/dag-processor-deployment.yaml"], + ) + + @pytest.mark.parametrize( + "name", + ["AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API", "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE"], + ) + @pytest.mark.parametrize("location", ["env", "dagProcessor.env"]) + def test_rejects_api_mode_environment_variables(self, name, location): + env = [{"name": name, "value": "True"}] + values = {"env": env} if location == "env" else {"dagProcessor": {"env": env}} + with pytest.raises(CalledProcessError, match=f"not the `{name}` environment variable"): render_chart(values=values, show_only=["templates/dag-processor/dag-processor-deployment.yaml"]) - @pytest.mark.parametrize("config", [{}, {"dag_processor": None}]) - def test_database_mode_keeps_database_probe_and_replicas(self, config): + @pytest.mark.parametrize( + "config", + [ + {}, + {"dag_processor": None}, + {"dag_processor": {"execution_api_token_file": "/run/processor.jwt"}}, + {"dag_processor": {**API_MODE_CONFIG, "use_execution_api": "False"}}, + {"dag_processor": {**API_MODE_CONFIG, "use_execution_api": False}}, + ], + ids=["default", "no-section", "token-file-only", "disabled-string", "disabled-bool"], + ) + def test_database_mode_keeps_database_probe_strategy_and_replicas(self, config): docs = render_chart( values={"config": config, "dagProcessor": {"replicas": 2}}, show_only=["templates/dag-processor/dag-processor-deployment.yaml"], ) assert jmespath.search("spec.replicas", docs[0]) == 2 + assert jmespath.search("spec.strategy", docs[0]) == { + "rollingUpdate": {"maxSurge": "100%", "maxUnavailable": "50%"} + } container = jmespath.search("spec.template.spec.containers[0]", docs[0]) assert "readinessProbe" not in container assert ( @@ -558,6 +591,7 @@ def test_isolated_api_deployment_example(self): ("api_auth", "jwt_private_key_path"), ): assert not config.has_option(section, key) + assert config["dag_processor"]["use_execution_api"] == "True" assert config["dag_processor"]["execution_api_token_file"] == "/run/dag-processor/processor.jwt" policy = yaml.safe_load((examples / "network-policy.yaml").read_text())["spec"] labels = deployment["spec"]["template"]["metadata"]["labels"] diff --git a/chart/values.schema.json b/chart/values.schema.json index 4d5d923a6a85..3c97245f7927 100644 --- a/chart/values.schema.json +++ b/chart/values.schema.json @@ -4520,7 +4520,7 @@ } }, "replicas": { - "description": "Number of dag processors to run. At most 1 when ``config.dag_processor.execution_api_token_file`` is set, since the pods would share one session token.", + "description": "Number of dag processors to run. At most 1 when ``config.dag_processor.use_execution_api`` is enabled, since the pods would share one session token.", "type": "integer", "default": 1 }, @@ -4560,7 +4560,7 @@ ] }, "strategy": { - "description": "Specifies the strategy used to replace old Pods by new ones when deployed as a Deployment. Ignored when ``config.dag_processor.execution_api_token_file`` is set; those pods share one session token and are replaced with the Recreate strategy.", + "description": "Specifies the strategy used to replace old Pods by new ones when deployed as a Deployment. Ignored when ``config.dag_processor.use_execution_api`` is enabled; those pods share one session token and are replaced with the Recreate strategy.", "type": [ "null", "object" diff --git a/chart/values.yaml b/chart/values.yaml index 253c37866df9..0395c0e65f40 100644 --- a/chart/values.yaml +++ b/chart/values.yaml @@ -2165,7 +2165,7 @@ dagProcessor: # kwargs: {} # Number of Airflow dag processors in the Deployment. At most 1 when - # config.dag_processor.execution_api_token_file is set, since the pods would share one session token. + # config.dag_processor.use_execution_api is enabled, since the pods would share one session token. replicas: 1 # Max number of old ReplicaSets to retain @@ -2178,7 +2178,7 @@ dagProcessor: args: ["bash", "-c", "exec airflow dag-processor"] # Update Strategy for dag processors. Ignored when - # config.dag_processor.execution_api_token_file is set: those pods share one session + # config.dag_processor.use_execution_api is enabled: those pods share one session # token, so they are always replaced with the Recreate strategy. strategy: rollingUpdate: diff --git a/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py b/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py index b2e067da35c7..32b39d969e7d 100644 --- a/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py +++ b/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py @@ -24,15 +24,21 @@ from docker_tests.constants import AIRFLOW_ROOT_PATH +DATABASE_PROBE = ["jobs", "check", "--job-type", "DagProcessorJob", "--hostname", "test-processor"] +API_PROBE = ["dag-processor", "--check-health"] + @pytest.mark.parametrize( - ("token_file", "expected_args"), + ("use_execution_api", "expected_args"), [ - (None, ["jobs", "check", "--job-type", "DagProcessorJob", "--hostname", "test-processor"]), - ("/run/processor.jwt", ["dag-processor", "--check-health"]), + (None, DATABASE_PROBE), + ("False", DATABASE_PROBE), + ("True", API_PROBE), + ("t", API_PROBE), + ("1", API_PROBE), ], ) -def test_quick_start_processor_healthcheck_mode(tmp_path, token_file, expected_args): +def test_quick_start_processor_healthcheck_mode(tmp_path, use_execution_api, expected_args): example = AIRFLOW_ROOT_PATH / "airflow-core/docs/howto/docker-compose/docker-compose.yaml" healthcheck = yaml.safe_load(example.read_text())["services"]["airflow-dag-processor"]["healthcheck"][ "test" @@ -41,9 +47,14 @@ def test_quick_start_processor_healthcheck_mode(tmp_path, token_file, expected_a airflow = tmp_path / "airflow" airflow.write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n") airflow.chmod(0o700) - env = {"PATH": str(tmp_path), "HOSTNAME": "test-processor"} - if token_file is not None: - env["AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE"] = token_file + # A token file alone does not enable API mode. + env = { + "PATH": str(tmp_path), + "HOSTNAME": "test-processor", + "AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE": "/run/processor.jwt", + } + if use_execution_api is not None: + env["AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API"] = use_execution_api # Compose unescapes doubled dollar signs before passing CMD-SHELL to the container. result = subprocess.run( ["/bin/sh", "-c", healthcheck[1].replace("$$", "$")], @@ -82,6 +93,7 @@ def test_isolated_processor_compose_example(tmp_path, monkeypatch, uid): assert not processor.get("env_file") assert not credentials.keys() & processor["environment"].keys() assert processor["environment"]["CONNECTION_CHECK_MAX_COUNT"] == "0" + assert processor["environment"]["AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API"] == "True" assert ( processor["environment"]["AIRFLOW__DAG_PROCESSOR__EXECUTION_API_TOKEN_FILE"] == "/run/dag-processor/processor.jwt" From c3f057faf72ae172e44bc0dab78345f7e660bd89 Mon Sep 17 00:00:00 2001 From: Ephraim Anierobi Date: Wed, 11 Nov 2026 08:11:09 +0100 Subject: [PATCH 9/9] Keep Dag processor deployment probes consistent with API mode Airflow accepts whitespace and inline comments in boolean configuration. Deployment selectors must recognize the same values so processors receive matching probes, rollout behavior and session-token safeguards. --- .../howto/docker-compose/docker-compose.yaml | 7 +++- chart/templates/_helpers.yaml | 2 +- .../airflow_core/test_dag_processor.py | 33 ++++++++++++------- .../test_dag_processor_api_deployment.py | 5 +++ 4 files changed, 33 insertions(+), 14 deletions(-) diff --git a/airflow-core/docs/howto/docker-compose/docker-compose.yaml b/airflow-core/docs/howto/docker-compose/docker-compose.yaml index 06c2855df555..960b5078de98 100644 --- a/airflow-core/docs/howto/docker-compose/docker-compose.yaml +++ b/airflow-core/docs/howto/docker-compose/docker-compose.yaml @@ -155,10 +155,15 @@ services: <<: *airflow-common command: dag-processor healthcheck: + # Airflow accepts inline # comments and whitespace in boolean config values. test: - CMD-SHELL - >- - case "$${AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API:-}" in + use_execution_api="$${AIRFLOW__DAG_PROCESSOR__USE_EXECUTION_API:-}"; + use_execution_api="$${use_execution_api%%#*}"; + use_execution_api="$${use_execution_api#"$${use_execution_api%%[![:space:]]*}"}"; + use_execution_api="$${use_execution_api%"$${use_execution_api##*[![:space:]]}"}"; + case "$${use_execution_api}" in [Tt] | [Tt][Rr][Uu][Ee] | 1) airflow dag-processor --check-health;; *) airflow jobs check --job-type DagProcessorJob --hostname "$${HOSTNAME}";; esac diff --git a/chart/templates/_helpers.yaml b/chart/templates/_helpers.yaml index 599baa25bf13..9d19a54f246d 100644 --- a/chart/templates/_helpers.yaml +++ b/chart/templates/_helpers.yaml @@ -859,7 +859,7 @@ Accepts the values Airflow reads as true, so a string "False" keeps database mod */}} {{- define "dagProcessor.useExecutionApi" -}} {{- $value := get (.Values.config.dag_processor | default dict) "use_execution_api" | toString -}} - {{- if has (tpl $value . | trim | lower) (list "t" "true" "1") }}true{{ end -}} + {{- if has (tpl $value . | splitList "#" | first | trim | lower) (list "t" "true" "1") }}true{{ end -}} {{- end }} {{/* Create the name of the pgbouncer service account to use */}} diff --git a/chart/tests/helm_tests/airflow_core/test_dag_processor.py b/chart/tests/helm_tests/airflow_core/test_dag_processor.py index b0c451a9bee7..e8b282e44b1f 100644 --- a/chart/tests/helm_tests/airflow_core/test_dag_processor.py +++ b/chart/tests/helm_tests/airflow_core/test_dag_processor.py @@ -28,6 +28,12 @@ from chart_utils.log_groomer import LogGroomerTestBase API_MODE_CONFIG = {"use_execution_api": "True", "execution_api_token_file": "/run/processor.jwt"} +API_MODE_COMMENT_VALUES = [ + "True # enabled", + " \tTrUe \t# enabled", + "1# enabled", + '{{ "TrUe # enabled" }}', +] class TestDagProcessor: @@ -442,7 +448,7 @@ def test_livenessprobe_command(self): in jmespath.search("spec.template.spec.containers[0].livenessProbe.exec.command", docs[0])[-1] ) - @pytest.mark.parametrize("use_execution_api", [True, "True", "true", "t", "1"]) + @pytest.mark.parametrize("use_execution_api", [True, "True", "true", "t", "1", *API_MODE_COMMENT_VALUES]) def test_api_mode_uses_local_liveness_probe(self, use_execution_api): docs = render_chart( values={ @@ -461,10 +467,11 @@ def test_api_mode_uses_local_liveness_probe(self, use_execution_api): assert "airflow dag-processor --check-ready" in readiness[-1] assert "airflow jobs check" not in command - def test_api_mode_replaces_pods_with_recreate(self): + @pytest.mark.parametrize("use_execution_api", ["True", *API_MODE_COMMENT_VALUES]) + def test_api_mode_replaces_pods_with_recreate(self, use_execution_api): docs = render_chart( values={ - "config": {"dag_processor": API_MODE_CONFIG}, + "config": {"dag_processor": {**API_MODE_CONFIG, "use_execution_api": use_execution_api}}, "dagProcessor": { "strategy": {"rollingUpdate": {"maxSurge": "100%", "maxUnavailable": "50%"}} }, @@ -475,9 +482,10 @@ def test_api_mode_replaces_pods_with_recreate(self): assert jmespath.search("spec.strategy", docs[0]) == {"type": "Recreate"} @pytest.mark.parametrize(("replicas", "rejected"), [(0, False), (1, False), (2, True)]) - def test_api_mode_rejects_replicas_sharing_a_session_token(self, replicas, rejected): + @pytest.mark.parametrize("use_execution_api", ["True", *API_MODE_COMMENT_VALUES]) + def test_api_mode_rejects_replicas_sharing_a_session_token(self, replicas, rejected, use_execution_api): values = { - "config": {"dag_processor": API_MODE_CONFIG}, + "config": {"dag_processor": {**API_MODE_CONFIG, "use_execution_api": use_execution_api}}, "dagProcessor": {"replicas": replicas}, } show_only = ["templates/dag-processor/dag-processor-deployment.yaml"] @@ -487,13 +495,14 @@ def test_api_mode_rejects_replicas_sharing_a_session_token(self, replicas, rejec else: docs = render_chart(values=values, show_only=show_only) assert jmespath.search("spec.replicas", docs[0]) == replicas - - @pytest.mark.parametrize( - "dag_processor", - [{"use_execution_api": "True"}, {"use_execution_api": "True", "execution_api_token_file": ""}], - ids=["unset", "empty"], - ) - def test_api_mode_requires_a_token_file(self, dag_processor): + assert jmespath.search("spec.strategy", docs[0]) == {"type": "Recreate"} + + @pytest.mark.parametrize("token_file", [None, ""], ids=["unset", "empty"]) + @pytest.mark.parametrize("use_execution_api", ["True", *API_MODE_COMMENT_VALUES]) + def test_api_mode_requires_a_token_file(self, token_file, use_execution_api): + dag_processor = {"use_execution_api": use_execution_api} + if token_file is not None: + dag_processor["execution_api_token_file"] = token_file with pytest.raises( CalledProcessError, match="use_execution_api` requires `config.dag_processor.execution_api_token_file", diff --git a/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py b/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py index 32b39d969e7d..8c1fe93b9ddd 100644 --- a/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py +++ b/docker-tests/tests/docker_tests/test_dag_processor_api_deployment.py @@ -36,6 +36,11 @@ ("True", API_PROBE), ("t", API_PROBE), ("1", API_PROBE), + (" True ", API_PROBE), + ("\tTrUe\r\n", API_PROBE), + ("True # enabled", API_PROBE), + (" \tTrUe \t# enabled", API_PROBE), + ("1# enabled", API_PROBE), ], ) def test_quick_start_processor_healthcheck_mode(tmp_path, use_execution_api, expected_args):