This is an automated email from the ASF dual-hosted git repository.
dabla pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git
The following commit(s) were added to refs/heads/main by this push:
new 5fe059fb881 Added asynchronous aget_hook method to BaseHook (#68506)
5fe059fb881 is described below
commit 5fe059fb88113f6e29695f0bbe9bfba93bf0e08a
Author: David Blain <[email protected]>
AuthorDate: Mon Jun 22 13:37:04 2026 +0200
Added asynchronous aget_hook method to BaseHook (#68506)
* refactor: Added asynchronous aget_hook method to BaseHook for use in
async tasks so we don't block the event look when resolving a hook based on
conn_id
* refactor: Fix deadlock in async tasks using aget_connection by using an
async version of mask_secret
* refactor: Fixed test_async_get_connection_masks_secrets
* refactor: Moved local imports for mask secret to top of log module
---
task-sdk/src/airflow/sdk/bases/hook.py | 17 ++++++++++++
task-sdk/src/airflow/sdk/execution_time/context.py | 16 +++++++++---
task-sdk/src/airflow/sdk/log.py | 23 ++++++++++++++---
task-sdk/tests/task_sdk/bases/test_hook.py | 30 +++++++++++++++++++++-
.../task_sdk/execution_time/test_context_cache.py | 29 +++++++++++++++++++++
5 files changed, 106 insertions(+), 9 deletions(-)
diff --git a/task-sdk/src/airflow/sdk/bases/hook.py
b/task-sdk/src/airflow/sdk/bases/hook.py
index 9c70684fd80..2ce625d232b 100644
--- a/task-sdk/src/airflow/sdk/bases/hook.py
+++ b/task-sdk/src/airflow/sdk/bases/hook.py
@@ -88,6 +88,23 @@ class BaseHook(LoggingMixin):
connection = cls.get_connection(conn_id)
return connection.get_hook(hook_params=hook_params)
+ @classmethod
+ async def aget_hook(cls, conn_id: str, hook_params: dict | None = None):
+ """
+ Return default hook for this connection id (async version).
+
+ Use this instead of :meth:`get_hook` when calling from an async context
+ (e.g. inside ``aexecute``). Calling the sync :meth:`get_hook` from the
+ event loop thread blocks the loop and can cause a deadlock when another
+ coroutine is concurrently communicating with the supervisor.
+
+ :param conn_id: connection id
+ :param hook_params: hook parameters
+ :return: default hook for this connection
+ """
+ connection = await cls.aget_connection(conn_id)
+ return connection.get_hook(hook_params=hook_params)
+
def get_conn(self) -> Any:
"""Return connection for the hook."""
raise NotImplementedError()
diff --git a/task-sdk/src/airflow/sdk/execution_time/context.py
b/task-sdk/src/airflow/sdk/execution_time/context.py
index 6cbf3dacadb..be189fe4c97 100644
--- a/task-sdk/src/airflow/sdk/execution_time/context.py
+++ b/task-sdk/src/airflow/sdk/execution_time/context.py
@@ -52,7 +52,7 @@ from airflow.sdk.exceptions import (
AirflowSecretsBackendAccessDenied,
ErrorType,
)
-from airflow.sdk.log import mask_secret
+from airflow.sdk.log import amask_secret, mask_secret
if TYPE_CHECKING:
from pydantic.types import JsonValue
@@ -160,6 +160,14 @@ def _mask_connection_secrets(conn: Connection) -> None:
mask_secret(conn.extra)
+async def _amask_connection_secrets(conn: Connection) -> None:
+ """Async version: mask sensitive connection fields from logs."""
+ if conn.password:
+ await amask_secret(conn.password)
+ if conn.extra:
+ await amask_secret(conn.extra)
+
+
def _convert_variable_result_to_variable(var_result: VariableResult,
deserialize_json: bool) -> Variable:
from airflow.sdk.definitions.variable import Variable
@@ -226,7 +234,7 @@ async def _async_get_connection(conn_id: str) -> Connection:
preset = _preset_connections.get()
if preset is not None and conn_id in preset:
conn = preset[conn_id]
- _mask_connection_secrets(conn)
+ await _amask_connection_secrets(conn)
return conn
from asgiref.sync import sync_to_async
@@ -239,7 +247,7 @@ async def _async_get_connection(conn_id: str) -> Connection:
from airflow.sdk.definitions.connection import Connection
conn = Connection.from_uri(uri, conn_id=conn_id)
- _mask_connection_secrets(conn)
+ await _amask_connection_secrets(conn)
return conn
except SecretCache.NotPresentException:
pass # continue to backends
@@ -261,7 +269,7 @@ async def _async_get_connection(conn_id: str) -> Connection:
if conn:
SecretCache.save_connection_uri(conn_id, conn.get_uri())
- _mask_connection_secrets(conn)
+ await _amask_connection_secrets(conn)
return conn
except AirflowSecretsBackendAccessDenied:
# Authoritative deny — must NOT fall through to a less-restrictive
backend.
diff --git a/task-sdk/src/airflow/sdk/log.py b/task-sdk/src/airflow/sdk/log.py
index 3a8d4b3374d..5e775cbcac4 100644
--- a/task-sdk/src/airflow/sdk/log.py
+++ b/task-sdk/src/airflow/sdk/log.py
@@ -17,6 +17,7 @@
# under the License.
from __future__ import annotations
+from contextlib import suppress
from functools import cache
from pathlib import Path
from typing import TYPE_CHECKING, Any, BinaryIO, TextIO
@@ -35,7 +36,7 @@ if TYPE_CHECKING:
from airflow.sdk.types import Logger, RuntimeTaskInstanceProtocol as
RuntimeTI
-from airflow.sdk._shared.secrets_masker import redact
+from airflow.sdk._shared.secrets_masker import _secrets_masker, redact
class _ActiveLoggingConfig:
@@ -249,10 +250,24 @@ def mask_secret(secret: JsonValue, name: str | None =
None) -> None:
they're masked in both the task subprocess AND supervisor's log output.
Works safely in both sync and async contexts.
"""
- from contextlib import suppress
+ _secrets_masker().add_mask(secret, name)
- from airflow.sdk._shared.secrets_masker import _secrets_masker
+ with suppress(Exception):
+ # Try to tell supervisor (only if in task execution context)
+ from airflow.sdk.execution_time import task_runner
+ from airflow.sdk.execution_time.comms import MaskSecret
+ if comms := getattr(task_runner, "SUPERVISOR_COMMS", None):
+ comms.send(MaskSecret(value=secret, name=name))
+
+
+async def amask_secret(secret: JsonValue, name: str | None = None) -> None:
+ """
+ Async version of mask_secret for use in async contexts.
+
+ Uses asend() instead of send() to avoid deadlock when called from within
+ an async task that already has an asend() in flight.
+ """
_secrets_masker().add_mask(secret, name)
with suppress(Exception):
@@ -261,7 +276,7 @@ def mask_secret(secret: JsonValue, name: str | None = None)
-> None:
from airflow.sdk.execution_time.comms import MaskSecret
if comms := getattr(task_runner, "SUPERVISOR_COMMS", None):
- comms.send(MaskSecret(value=secret, name=name))
+ await comms.asend(MaskSecret(value=secret, name=name))
def reset_logging():
diff --git a/task-sdk/tests/task_sdk/bases/test_hook.py
b/task-sdk/tests/task_sdk/bases/test_hook.py
index 36a1168705c..351f63e039d 100644
--- a/task-sdk/tests/task_sdk/bases/test_hook.py
+++ b/task-sdk/tests/task_sdk/bases/test_hook.py
@@ -80,7 +80,7 @@ class TestBaseHook:
hook = BaseHook(logger_name="")
await hook.aget_connection(conn_id="test_conn")
- mock_supervisor_comms.asend.assert_called_once_with(
+ mock_supervisor_comms.asend.assert_any_call(
msg=GetConnection(conn_id="test_conn"),
)
@@ -100,6 +100,34 @@ class TestBaseHook:
with pytest.raises(AirflowNotFoundException, match="The conn_id
`test_conn` isn't defined"):
await hook.aget_connection(conn_id=conn_id)
+ @pytest.mark.asyncio
+ async def test_aget_hook(self, mock_supervisor_comms):
+ """aget_hook() must use the async connection path and return the hook
for the connection."""
+ conn = ConnectionResult(
+ conn_id="test_conn",
+ conn_type="http",
+ host="https://example.com",
+ login="user",
+ password="password",
+ port=443,
+ )
+
+ mock_supervisor_comms.asend.return_value = conn
+
+ result = await BaseHook.aget_hook(conn_id="test_conn")
+
+ # asend() must have been called for GetConnection — never the blocking
send()
+ mock_supervisor_comms.asend.assert_any_call(
+ msg=GetConnection(conn_id="test_conn"),
+ )
+ # send() must not have been used for GetConnection (other messages
like MaskSecret are allowed)
+ for call_args in mock_supervisor_comms.send.call_args_list:
+ msg = call_args.kwargs.get("msg") or (call_args.args[0] if
call_args.args else None)
+ assert not isinstance(msg, GetConnection), (
+ "send() must not be used for GetConnection; use asend()
instead"
+ )
+ assert result is not None
+
def test_get_connection_secrets_backend_configured(self,
mock_supervisor_comms, tmp_path):
path = tmp_path / "conn.env"
path.write_text("CONN_A=mysql://host_a")
diff --git a/task-sdk/tests/task_sdk/execution_time/test_context_cache.py
b/task-sdk/tests/task_sdk/execution_time/test_context_cache.py
index d415c0334a4..aa3b20ca9ce 100644
--- a/task-sdk/tests/task_sdk/execution_time/test_context_cache.py
+++ b/task-sdk/tests/task_sdk/execution_time/test_context_cache.py
@@ -297,6 +297,35 @@ class TestAsyncConnectionCache:
assert cached_conn.conn_type == "mysql"
assert cached_conn.host == "host"
+ @pytest.mark.asyncio
+ @patch("airflow.sdk.execution_time.context.amask_secret")
+ async def test_async_get_connection_masks_secrets(self, mock_amask_secret):
+ """Test that async connection secrets are masked from logs using
amask_secret."""
+ from airflow.sdk.execution_time.context import _async_get_connection
+
+ conn_id = "test_conn"
+ conn = Connection(
+ conn_id=conn_id, conn_type="mysql", login="user",
password="password", extra='{"key": "value"}'
+ )
+
+ mock_backend = MagicMock(spec=["aget_connection"])
+ mock_backend.aget_connection = AsyncMock(return_value=conn)
+
+ with patch(
+
"airflow.sdk.execution_time.supervisor.ensure_secrets_backend_loaded",
return_value=[mock_backend]
+ ):
+ result = await _async_get_connection(conn_id)
+
+ assert result.conn_id == conn_id
+ # Check that password and extra were masked using amask_secret
(async version)
+ mock_amask_secret.assert_has_calls(
+ [
+ call("password"),
+ call('{"key": "value"}'),
+ ],
+ any_order=True,
+ )
+
class TestCacheDisabled:
"""Test behavior when cache is disabled."""