You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "mwojtyczka (via GitHub)" <gi...@apache.org> on 2026/02/04 17:44:58 UTC
[PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
mwojtyczka opened a new pull request, #61458:
URL: https://github.com/apache/airflow/pull/61458
<!--
Thank you for contributing!
Please provide above a brief description of the changes made in this pull request.
Write a good git commit message following this guide: http://chris.beams.io/posts/git-commit/
Please make sure that your code changes are covered with tests.
And in case of new features or big changes remember to adjust the documentation.
Feel free to ping (in general) for the review if you do not see reaction for a few days
(72 Hours is the minimum reaction time you can expect from volunteers) - we sometimes miss notifications.
In case of an existing issue, reference it using one of the following:
* closes: #ISSUE
* related: #ISSUE
-->
Extended Databricks Provider hook with OIDC token federation for Airflow deployed on Kubernetes. The hook automatically fetch JWT tokens from Kubernetes Service Account via projected volume path or TokenRequest API and exchange them for Databricks OAuth tokens. This will be the recommended method when Airflow runs in Kubernetes. This method requires no secrets to be stored in the connection and eliminates the need for token management (no rotation, expiration handling, or credential storage).
* related: #54291
---
##### Was generative AI tooling used to co-author this PR?
<!--
If generative AI tooling has been used in the process of authoring this PR, please
change below checkbox to `[X]` followed by the name of the tool, uncomment the "Generated-by".
-->
- [X] Yes, Cursor for writing unit tests and partially for updating documentation
<!--
Generated-by: [Tool Name] following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions)
-->
---
* Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information. Note: commit author/co-author name and email in commits become permanently public when merged.
* For fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
* When adding dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
* For significant user-facing changes create newsfragment: `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770530754
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
For consistency I'm following the existing pattern in this hook here. The retriable errors are:
* ClientConnectorError or TimeoutError (network issues)
* HTTP status >= 500 (server errors)
* HTTP 429 (rate limiting)
* HTTP 400 with error code "COULD_NOT_ACQUIRE_LOCK"
Everything else is not retried, goes straight to the except block
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on PR #61458:
URL: https://github.com/apache/airflow/pull/61458#issuecomment-3907774346
@potiuk thanks for looking into this. Fixed the doc now.
There was one mypy error in mssql to hive provider - not related to Databricks provider changes. I updated the branch so hopefully this should be gone now.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770631295
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
Review Comment:
added
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
Review Comment:
added to sync and async version
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2772988667
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
Review Comment:
I updated the code to avoid this
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "alexott (via GitHub)" <gi...@apache.org>.
alexott commented on PR #61458:
URL: https://github.com/apache/airflow/pull/61458#issuecomment-3914983178
@potiuk, we finished internal and customer testing, so this PR is ready for additional review/merge.
thank you
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2773015612
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
Review Comment:
updated
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770480617
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
Review Comment:
correct, i added there to satisfy the linter, it's not picking up the facts you mentioned above
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2772969499
##########
providers/databricks/docs/connections/databricks.rst:
##########
@@ -91,6 +100,244 @@ Extra (optional)
* ``azure_resource_id``: optional Resource ID of the Azure Databricks workspace (required if managed identity isn't
a user inside workspace)
+ The following parameters are necessary if using authentication with Kubernetes OIDC token federation:
+
+ * ``federated_k8s``: set ``login`` to ``"federated_k8s"`` or add this as extra parameter. When enabled, the hook will fetch a JWT token from Kubernetes and exchange it for a Databricks OAuth token using the `OIDC token exchange API <https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-exchange.html>`_. This authentication method only works when Airflow is running inside a Kubernetes cluster (e.g., AWS EKS, Azure AKS, Google GKE).
Review Comment:
added
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "alexott (via GitHub)" <gi...@apache.org>.
alexott commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2768823315
##########
providers/databricks/docs/connections/databricks.rst:
##########
@@ -91,6 +100,244 @@ Extra (optional)
* ``azure_resource_id``: optional Resource ID of the Azure Databricks workspace (required if managed identity isn't
a user inside workspace)
+ The following parameters are necessary if using authentication with Kubernetes OIDC token federation:
+
+ * ``federated_k8s``: set ``login`` to ``"federated_k8s"`` or add this as extra parameter. When enabled, the hook will fetch a JWT token from Kubernetes and exchange it for a Databricks OAuth token using the `OIDC token exchange API <https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-exchange.html>`_. This authentication method only works when Airflow is running inside a Kubernetes cluster (e.g., AWS EKS, Azure AKS, Google GKE).
+
+ **Two methods are supported for obtaining the Kubernetes JWT token:**
+
+ **Method 1: Projected Volume**
+
+ * ``k8s_projected_volume_token_path``: (optional) path to a [Kubernetes projected volume service account token](https://kubernetes.io/docs/concepts/configuration/secret/#projected-volume). When configured, the hook will read the token directly from this file. The token must be configured in your Pod spec with the appropriate audience and expiration. This is the recommended method as it's simpler and more efficient (no API calls). See the example Pod configuration below.
Review Comment:
This is `.rst` file, so links are done differently than in Markdown
##########
providers/databricks/docs/connections/databricks.rst:
##########
@@ -41,6 +41,13 @@ There are several ways to connect to Databricks using Airflow.
`user inside workspace <https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/service-prin-aad-token#--api-access-for-service-principals-that-are-azure-databricks-workspace-users-and-admins>`_, or `outside of workspace having Owner or Contributor permissions <https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/service-prin-aad-token#--api-access-for-service-principals-that-are-not-workspace-users>`_
4. Using Azure Active Directory (AAD) token obtained for `Azure managed identity <https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token>`_,
when Airflow runs on the VM with assigned managed identity (system-assigned or user-assigned)
+5. Using Databricks-managed Service Principal OAuth
Review Comment:
I maybe would add something like `(available on all supported clouds)`
##########
providers/databricks/docs/connections/databricks.rst:
##########
@@ -91,6 +100,244 @@ Extra (optional)
* ``azure_resource_id``: optional Resource ID of the Azure Databricks workspace (required if managed identity isn't
a user inside workspace)
+ The following parameters are necessary if using authentication with Kubernetes OIDC token federation:
+
+ * ``federated_k8s``: set ``login`` to ``"federated_k8s"`` or add this as extra parameter. When enabled, the hook will fetch a JWT token from Kubernetes and exchange it for a Databricks OAuth token using the `OIDC token exchange API <https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-exchange.html>`_. This authentication method only works when Airflow is running inside a Kubernetes cluster (e.g., AWS EKS, Azure AKS, Google GKE).
Review Comment:
Is it a boolean flag in `extra`?
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
Review Comment:
Maybe wrap this into the function? Just to avoid code duplciation?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770632680
##########
providers/databricks/docs/connections/databricks.rst:
##########
@@ -91,6 +100,244 @@ Extra (optional)
* ``azure_resource_id``: optional Resource ID of the Azure Databricks workspace (required if managed identity isn't
a user inside workspace)
+ The following parameters are necessary if using authentication with Kubernetes OIDC token federation:
+
+ * ``federated_k8s``: set ``login`` to ``"federated_k8s"`` or add this as extra parameter. When enabled, the hook will fetch a JWT token from Kubernetes and exchange it for a Databricks OAuth token using the `OIDC token exchange API <https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-exchange.html>`_. This authentication method only works when Airflow is running inside a Kubernetes cluster (e.g., AWS EKS, Azure AKS, Google GKE).
+
+ **Two methods are supported for obtaining the Kubernetes JWT token:**
+
+ **Method 1: Projected Volume**
+
+ * ``k8s_projected_volume_token_path``: (optional) path to a [Kubernetes projected volume service account token](https://kubernetes.io/docs/concepts/configuration/secret/#projected-volume). When configured, the hook will read the token directly from this file. The token must be configured in your Pod spec with the appropriate audience and expiration. This is the recommended method as it's simpler and more efficient (no API calls). See the example Pod configuration below.
Review Comment:
corrected
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #61458:
URL: https://github.com/apache/airflow/pull/61458#issuecomment-3848846860
Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide (https://github.com/apache/airflow/blob/main/contributing-docs/README.rst)
Here are some useful points:
- Pay attention to the quality of your code (ruff, mypy and type annotations). Our [prek-hooks]( https://github.com/apache/airflow/blob/main/contributing-docs/08_static_code_checks.rst#prerequisites-for-prek-hooks) will help you with that.
- In case of a new feature add useful documentation (in docstrings or in `docs/` directory). Adding a new operator? Check this short [guide](https://github.com/apache/airflow/blob/main/airflow-core/docs/howto/custom-operator.rst) Consider adding an example DAG that shows how users should use it.
- Consider using [Breeze environment](https://github.com/apache/airflow/blob/main/dev/breeze/doc/README.rst) for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
- Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
- Please follow [ASF Code of Conduct](https://www.apache.org/foundation/policies/conduct) for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
- Be sure to read the [Airflow Coding style]( https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#coding-style-and-best-practices).
- Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
Apache Airflow is a community-driven project and together we are making it better 🚀.
In case of doubts contact the developers at:
Mailing List: dev@airflow.apache.org
Slack: https://s.apache.org/airflow-slack
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770542179
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
Review Comment:
the tenacity context manager is what enables the retry mechanism. It catches exceptions and decides whether to retry or fail
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
Review Comment:
the tenacity context manager is what enables the retry mechanism. It catches exceptions and decides whether to retry or fail, see also above
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "alexott (via GitHub)" <gi...@apache.org>.
alexott commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2803037213
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +544,360 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str = self.databricks_conn.extra_dejson["k8s_projected_volume_token_path"]
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str = self.databricks_conn.extra_dejson["k8s_projected_volume_token_path"]
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ @staticmethod
+ def _build_k8s_token_request_payload(audience: str, expiration_seconds: int) -> dict[str, Any]:
+ """
+ Build the JSON payload for Kubernetes TokenRequest API.
+
+ :param audience: The audience value for the JWT token
+ :param expiration_seconds: Token expiration in seconds
+ :return: TokenRequest API payload dictionary
+ """
+ return {
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ }
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json=self._build_k8s_token_request_payload(audience, expiration_seconds),
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ try:
+ response_json = resp.json()
+ return response_json["status"]["token"]
+ except (JSONDecodeError, ValueError) as e:
+ raise AirflowException(
+ f"Invalid JSON response from Kubernetes API. Response: {resp.text[:500]}"
+ ) from e
+ except KeyError as e:
+ raise AirflowException(
+ f"Malformed Kubernetes token response: missing key '{e}'. "
+ f"Response: {resp.text[:500]}"
+ ) from e
+ except FileNotFoundError as e:
+ raise AirflowException(
+ "Kubernetes service account token not found. "
+ "This authentication method only works when running inside a Kubernetes cluster."
+ ) from e
+ except RetryError:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token after {self.retry_limit} retries. Giving up."
+ )
+ except requests_exceptions.HTTPError as e:
+ msg = f"Failed to get Kubernetes JWT token. Response: {e.response.content.decode()}, Status Code: {e.response.status_code}"
+ raise AirflowException(msg)
+
+ raise RuntimeError("Failed to get JWT token")
+
+ async def _a_get_k8s_token_request_api(self) -> str:
+ """Async version of _get_k8s_token_request_api()."""
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ async with aiofiles.open(token_path) as f:
+ in_cluster_token = (await f.read()).strip()
+
+ async with aiofiles.open(namespace_path) as f:
+ namespace = (await f.read()).strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ async for attempt in self._a_get_retry_object():
+ with attempt:
+ async with self._session.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json=self._build_k8s_token_request_payload(audience, expiration_seconds),
+ ssl=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ ) as resp:
+ resp.raise_for_status()
+ try:
+ jsn = await resp.json()
+ return jsn["status"]["token"]
+ except (aiohttp.ContentTypeError, ValueError) as e:
+ # Try to read response text if JSON parsing failed
+ try:
+ response_text = await resp.text()
+ except Exception:
+ response_text = "unable to read response"
+ raise AirflowException(
+ f"Invalid JSON response from Kubernetes API. Response: {response_text[:500]}"
+ ) from e
+ except KeyError as e:
+ # Response body already consumed, use the parsed JSON for error message
+ raise AirflowException(
+ f"Malformed Kubernetes token response: missing key '{e}'. "
+ f"Response structure: {jsn}"
+ ) from e
+ except FileNotFoundError as e:
+ raise AirflowException(
+ "Kubernetes service account token not found. "
+ "This authentication method only works when running inside a Kubernetes cluster."
+ ) from e
+ except RetryError:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token after {self.retry_limit} retries. Giving up."
+ )
+ except aiohttp.ClientResponseError as err:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token. Response: {err.message}, Status Code: {err.status}"
+ )
+ raise RuntimeError("Failed to get JWT token")
+
+ def _get_required_client_id(self) -> str:
+ """
+ Get and validate client_id for Kubernetes OIDC token federation.
+
+ :return: Service principal client ID
+ :raises AirflowException: If client_id is not provided
+ """
+ client_id = self.databricks_conn.extra_dejson.get("client_id", None)
Review Comment:
Do we really need `None` as a default value? Normal Python `dict.get` returns None if there is no entry
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #61458:
URL: https://github.com/apache/airflow/pull/61458#issuecomment-3905406005
@sryza - maybe you can take a look ?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770477669
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
correct, i added this to satisfy the linter, that's the only reason
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
correct, i added this to satisfy the linter, that's the only reason
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770484491
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
Review Comment:
let me add this
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770480617
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
Review Comment:
correct, i added this to satisfy the linter, it's not picking up the facts you mentioned above
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "Nataneljpwd (via GitHub)" <gi...@apache.org>.
Nataneljpwd commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2769661110
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
Review Comment:
I know it is rare, but what if we get a malformed response?
Won't it be better to except for a keyerror as well?
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
+ except FileNotFoundError as e:
+ raise AirflowException(
+ "Kubernetes service account token not found. "
+ "This authentication method only works when running inside a Kubernetes cluster."
+ ) from e
+ except RetryError:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token after {self.retry_limit} retries. Giving up."
+ )
Review Comment:
I don't think this can happen the way it is currently implemented
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
For what exactly are we retrying here? We have a raise for status in case of failure, and so other retries won't happen.
What kind of failure are you expecting here other than an http failure? It seems that if it fails, we just jump to the except block which surrounds the loop
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
Review Comment:
Do we need this check if we imply that we do have this configuration, and we have checked that already?
And even if so, we can catch it in the try except block
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
Review Comment:
If we return, a retry won't be triggered, nor if we fail, maybe the "with attempt" does something that I am missing?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770477669
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
correct, i added there to satisfy the linter, it's the only reason it's there
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770530754
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
Following the existing pattern in this hook here. The retriable errors are:
* ClientConnectorError or TimeoutError (network issues)
* HTTP status >= 500 (server errors)
* HTTP 429 (rate limiting)
* HTTP 400 with error code "COULD_NOT_ACQUIRE_LOCK"
*
Everything else is not retried, goes straight to the except block
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2803507311
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +544,360 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str = self.databricks_conn.extra_dejson["k8s_projected_volume_token_path"]
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str = self.databricks_conn.extra_dejson["k8s_projected_volume_token_path"]
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ @staticmethod
+ def _build_k8s_token_request_payload(audience: str, expiration_seconds: int) -> dict[str, Any]:
+ """
+ Build the JSON payload for Kubernetes TokenRequest API.
+
+ :param audience: The audience value for the JWT token
+ :param expiration_seconds: Token expiration in seconds
+ :return: TokenRequest API payload dictionary
+ """
+ return {
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ }
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json=self._build_k8s_token_request_payload(audience, expiration_seconds),
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ try:
+ response_json = resp.json()
+ return response_json["status"]["token"]
+ except (JSONDecodeError, ValueError) as e:
+ raise AirflowException(
+ f"Invalid JSON response from Kubernetes API. Response: {resp.text[:500]}"
+ ) from e
+ except KeyError as e:
+ raise AirflowException(
+ f"Malformed Kubernetes token response: missing key '{e}'. "
+ f"Response: {resp.text[:500]}"
+ ) from e
+ except FileNotFoundError as e:
+ raise AirflowException(
+ "Kubernetes service account token not found. "
+ "This authentication method only works when running inside a Kubernetes cluster."
+ ) from e
+ except RetryError:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token after {self.retry_limit} retries. Giving up."
+ )
+ except requests_exceptions.HTTPError as e:
+ msg = f"Failed to get Kubernetes JWT token. Response: {e.response.content.decode()}, Status Code: {e.response.status_code}"
+ raise AirflowException(msg)
+
+ raise RuntimeError("Failed to get JWT token")
+
+ async def _a_get_k8s_token_request_api(self) -> str:
+ """Async version of _get_k8s_token_request_api()."""
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ async with aiofiles.open(token_path) as f:
+ in_cluster_token = (await f.read()).strip()
+
+ async with aiofiles.open(namespace_path) as f:
+ namespace = (await f.read()).strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ async for attempt in self._a_get_retry_object():
+ with attempt:
+ async with self._session.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json=self._build_k8s_token_request_payload(audience, expiration_seconds),
+ ssl=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ ) as resp:
+ resp.raise_for_status()
+ try:
+ jsn = await resp.json()
+ return jsn["status"]["token"]
+ except (aiohttp.ContentTypeError, ValueError) as e:
+ # Try to read response text if JSON parsing failed
+ try:
+ response_text = await resp.text()
+ except Exception:
+ response_text = "unable to read response"
+ raise AirflowException(
+ f"Invalid JSON response from Kubernetes API. Response: {response_text[:500]}"
+ ) from e
+ except KeyError as e:
+ # Response body already consumed, use the parsed JSON for error message
+ raise AirflowException(
+ f"Malformed Kubernetes token response: missing key '{e}'. "
+ f"Response structure: {jsn}"
+ ) from e
+ except FileNotFoundError as e:
+ raise AirflowException(
+ "Kubernetes service account token not found. "
+ "This authentication method only works when running inside a Kubernetes cluster."
+ ) from e
+ except RetryError:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token after {self.retry_limit} retries. Giving up."
+ )
+ except aiohttp.ClientResponseError as err:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token. Response: {err.message}, Status Code: {err.status}"
+ )
+ raise RuntimeError("Failed to get JWT token")
+
+ def _get_required_client_id(self) -> str:
+ """
+ Get and validate client_id for Kubernetes OIDC token federation.
+
+ :return: Service principal client ID
+ :raises AirflowException: If client_id is not provided
+ """
+ client_id = self.databricks_conn.extra_dejson.get("client_id", None)
Review Comment:
right, updated and added unit test for the case when client id is not provided
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "Nataneljpwd (via GitHub)" <gi...@apache.org>.
Nataneljpwd commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2773584782
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
Ok, sounds good
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
Ok, sounds good
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770530754
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
Review Comment:
Following the existing pattern in this hook here. The retriable errors are:
* ClientConnectorError or TimeoutError (network issues)
* HTTP status >= 500 (server errors)
* HTTP 429 (rate limiting)
* HTTP 400 with error code "COULD_NOT_ACQUIRE_LOCK"
Everything else is not retried, goes straight to the except block
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770573516
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
+ except FileNotFoundError as e:
+ raise AirflowException(
+ "Kubernetes service account token not found. "
+ "This authentication method only works when running inside a Kubernetes cluster."
+ ) from e
+ except RetryError:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token after {self.retry_limit} retries. Giving up."
+ )
Review Comment:
The tenacity retry mechanism will raise `RetryError` when a retryable exception occurs and retry attempts are exhausted. Most transient errors that will try to retry will resolve within the retry limit. So this is this is reachable, but will be rare in practice. Again following existing pattern in this hook.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2772955650
##########
providers/databricks/docs/connections/databricks.rst:
##########
@@ -41,6 +41,13 @@ There are several ways to connect to Databricks using Airflow.
`user inside workspace <https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/service-prin-aad-token#--api-access-for-service-principals-that-are-azure-databricks-workspace-users-and-admins>`_, or `outside of workspace having Owner or Contributor permissions <https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/service-prin-aad-token#--api-access-for-service-principals-that-are-not-workspace-users>`_
4. Using Azure Active Directory (AAD) token obtained for `Azure managed identity <https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token>`_,
when Airflow runs on the VM with assigned managed identity (system-assigned or user-assigned)
+5. Using Databricks-managed Service Principal OAuth
Review Comment:
corrected
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk commented on PR #61458:
URL: https://github.com/apache/airflow/pull/61458#issuecomment-3905409640
Ah I see we have more people from Databricks here :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770636319
##########
providers/databricks/docs/connections/databricks.rst:
##########
@@ -91,6 +100,244 @@ Extra (optional)
* ``azure_resource_id``: optional Resource ID of the Azure Databricks workspace (required if managed identity isn't
a user inside workspace)
+ The following parameters are necessary if using authentication with Kubernetes OIDC token federation:
+
+ * ``federated_k8s``: set ``login`` to ``"federated_k8s"`` or add this as extra parameter. When enabled, the hook will fetch a JWT token from Kubernetes and exchange it for a Databricks OAuth token using the `OIDC token exchange API <https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-exchange.html>`_. This authentication method only works when Airflow is running inside a Kubernetes cluster (e.g., AWS EKS, Azure AKS, Google GKE).
Review Comment:
yes, will add this to the doc
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "mwojtyczka (via GitHub)" <gi...@apache.org>.
mwojtyczka commented on code in PR #61458:
URL: https://github.com/apache/airflow/pull/61458#discussion_r2770573516
##########
providers/databricks/src/airflow/providers/databricks/hooks/databricks_base.py:
##########
@@ -525,6 +543,318 @@ def _is_oauth_token_valid(token: dict, time_key="expires_on") -> bool:
return int(token[time_key]) > (int(time.time()) + TOKEN_REFRESH_LEAD_TIME)
+ def _get_k8s_jwt_token(self) -> str:
+ """
+ Get JWT token from Kubernetes.
+
+ Supports two methods:
+ 1. Projected volume: reads token directly from configured path
+ 2. TokenRequest API: dynamically requests token from K8s API
+
+ :return: JWT Service Account token string
+ """
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return self._get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return self._get_k8s_token_request_api()
+
+ async def _a_get_k8s_jwt_token(self) -> str:
+ """Async version of _get_k8s_jwt_token()."""
+ if "k8s_projected_volume_token_path" in self.databricks_conn.extra_dejson:
+ self.log.info("Using Kubernetes projected volume token")
+ return await self._a_get_k8s_projected_volume_token()
+
+ self.log.info("Using Kubernetes TokenRequest API")
+ return await self._a_get_k8s_token_request_api()
+
+ def _get_k8s_projected_volume_token(self) -> str:
+ """
+ Get JWT token from Kubernetes projected volume.
+
+ Reads a pre-configured service account token from a projected volume.
+ The token should be configured in the Pod spec with the desired audience
+ and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ with open(projected_token_path) as f:
+ token = f.read().strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ async def _a_get_k8s_projected_volume_token(self) -> str:
+ """Async version of _get_k8s_projected_volume_token()."""
+ projected_token_path: str | None = self.databricks_conn.extra_dejson.get(
+ "k8s_projected_volume_token_path"
+ )
+
+ if not projected_token_path:
+ raise AirflowException("k8s_projected_volume_token_path is not configured in connection extras")
+
+ try:
+ async with aiofiles.open(projected_token_path) as f:
+ token = (await f.read()).strip()
+
+ if not token:
+ raise AirflowException(f"Token file at {projected_token_path} is empty")
+
+ self.log.debug("Successfully read token from projected volume at %s", projected_token_path)
+ return token
+ except FileNotFoundError as e:
+ raise AirflowException(
+ f"Kubernetes projected volume token not found at {projected_token_path}. "
+ "Ensure your Pod has a projected volume configured with serviceAccountToken."
+ ) from e
+ except PermissionError as e:
+ raise AirflowException(f"Permission denied reading token from {projected_token_path}") from e
+
+ def _get_k8s_token_request_api(self) -> str:
+ """
+ Get JWT token using Kubernetes TokenRequest API.
+
+ Dynamically requests a service account token from the Kubernetes API server
+ with custom audience and expiration settings.
+
+ :return: JWT Service Account token string
+ """
+ audience = self.databricks_conn.extra_dejson.get("audience", DEFAULT_K8S_AUDIENCE)
+ expiration_seconds = self.databricks_conn.extra_dejson.get("expiration_seconds", 3600)
+ token_path = self.databricks_conn.extra_dejson.get(
+ "k8s_token_path", DEFAULT_K8S_SERVICE_ACCOUNT_TOKEN_PATH
+ )
+ namespace_path = self.databricks_conn.extra_dejson.get(
+ "k8s_namespace_path", DEFAULT_K8S_NAMESPACE_PATH
+ )
+
+ try:
+ with open(token_path) as f:
+ in_cluster_token = f.read().strip()
+
+ with open(namespace_path) as f:
+ namespace = f.read().strip()
+
+ # Call Kubernetes TokenRequest API with the in-cluster token
+ token_request_url = (
+ f"{K8S_TOKEN_SERVICE_URL}/api/v1/namespaces/{namespace}/serviceaccounts/default/token"
+ )
+
+ for attempt in self._get_retry_object():
+ with attempt:
+ resp = requests.post(
+ token_request_url,
+ headers={
+ "Authorization": f"Bearer {in_cluster_token}",
+ "Content-Type": "application/json",
+ },
+ json={
+ "apiVersion": "authentication.k8s.io/v1",
+ "kind": "TokenRequest",
+ "spec": {
+ "audiences": [audience],
+ "expirationSeconds": expiration_seconds,
+ },
+ },
+ verify=False, # K8s in-cluster uses self-signed certs
+ timeout=self.token_timeout_seconds,
+ )
+ resp.raise_for_status()
+ return resp.json()["status"]["token"]
+ except FileNotFoundError as e:
+ raise AirflowException(
+ "Kubernetes service account token not found. "
+ "This authentication method only works when running inside a Kubernetes cluster."
+ ) from e
+ except RetryError:
+ raise AirflowException(
+ f"Failed to get Kubernetes JWT token after {self.retry_limit} retries. Giving up."
+ )
Review Comment:
The tenacity retry mechanism will raise this exception when a retryable exception occurs and retry attempts are exhausted. Most transient errors that will try to retry will resolve within the retry limit. So this is this is reachable, but will be rare in practice. Again following existing pattern in this hook.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "boring-cyborg[bot] (via GitHub)" <gi...@apache.org>.
boring-cyborg[bot] commented on PR #61458:
URL: https://github.com/apache/airflow/pull/61458#issuecomment-3915035900
Awesome work, congrats on your first merged pull request! You are invited to check our [Issue Tracker](https://github.com/apache/airflow/issues) for additional contributions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Databricks OIDC token federation for Kubernetes deployment [airflow]
Posted by "potiuk (via GitHub)" <gi...@apache.org>.
potiuk merged PR #61458:
URL: https://github.com/apache/airflow/pull/61458
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org