This is an automated email from the ASF dual-hosted git repository.
jason810496 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 8e96f964736 Keep backfill authorization off the API server event loop
(#76493)
8e96f964736 is described below
commit 8e96f96473668784f6d609055cac7c7af27bd62d
Author: Aaron Chen <[email protected]>
AuthorDate: Tue Dec 1 05:22:51 2026 -0800
Keep backfill authorization off the API server event loop (#76493)
* Keep backfill authorization off the API server event loop
* Refactor backfill authorization to remove session dependency from API
handlers
* Clarify comment on session handling in DagModel for better understanding
---
.../src/airflow/api_fastapi/core_api/security.py | 45 +++++---
airflow-core/src/airflow/models/dag.py | 45 ++++++--
.../core_api/routes/public/test_backfills.py | 44 +++++++
.../unit/api_fastapi/core_api/test_security.py | 127 +++++++++++++++------
.../api_fastapi/known_sync_db_on_event_loop.txt | 10 --
airflow-core/tests/unit/models/test_dag.py | 33 +++++-
6 files changed, 234 insertions(+), 70 deletions(-)
diff --git a/airflow-core/src/airflow/api_fastapi/core_api/security.py
b/airflow-core/src/airflow/api_fastapi/core_api/security.py
index e717248e640..f249f6e6442 100644
--- a/airflow-core/src/airflow/api_fastapi/core_api/security.py
+++ b/airflow-core/src/airflow/api_fastapi/core_api/security.py
@@ -200,6 +200,11 @@ def collect_request_tokens(
GetUserDep = Annotated[BaseUser, Depends(get_user)]
+def _get_dag_id_from_request(request: Request) -> str | None:
+ dag_id = request.path_params.get("dag_id") or
request.query_params.get("dag_id")
+ return dag_id if dag_id != "~" else None
+
+
def requires_access_dag(
method: ResourceMethod,
access_entity: DagAccessEntity | None = None,
@@ -213,8 +218,7 @@ def requires_access_dag(
# Prevent from using a nonlocal statement causing test failures.
dag_id = param_dag_id
if dag_id is None:
- dag_id = request.path_params.get("dag_id") or
request.query_params.get("dag_id")
- dag_id = dag_id if dag_id != "~" else None
+ dag_id = _get_dag_id_from_request(request)
team_name = DagModel.get_team_name(dag_id) if dag_id else None
@@ -550,14 +554,16 @@ _BACKFILL_ID_ADAPTER: TypeAdapter[NonNegativeInt] =
TypeAdapter(NonNegativeInt)
BACKFILL_NOT_FOUND = "Backfill not found"
-def _authorize_backfill_in_path(method: ResourceMethod, dag_id: str | None,
user: BaseUser) -> None:
+def _authorize_backfill_in_path(
+ method: ResourceMethod, dag_id: str | None, team_name: str | None, user:
BaseUser
+) -> None:
"""Authorize a backfill named by the request path against that backfill's
Dag alone."""
# ``dag_id`` is None when the id matched no row. Answering 404 there while
a backfill on a Dag
# the caller may not read answers 403 would tell them which backfill ids
exist across Dags.
if dag_id is None:
raise HTTPException(status.HTTP_404_NOT_FOUND, BACKFILL_NOT_FOUND)
- details = DagDetails(id=dag_id, team_name=DagModel.get_team_name(dag_id))
+ details = DagDetails(id=dag_id, team_name=team_name)
auth_manager = get_auth_manager()
if auth_manager.is_authorized_dag(
method=method, access_entity=DagAccessEntity.RUN, details=details,
user=user
@@ -574,13 +580,14 @@ def _authorize_backfill_in_path(method: ResourceMethod,
dag_id: str | None, user
def requires_access_backfill(
method: ResourceMethod,
-) -> Callable[[Request, BaseUser, Session], Coroutine[Any, Any, None]]:
- """Wrap ``requires_access_dag`` and extract the dag_id from the
backfill_id."""
+) -> Callable[[Request, BaseUser], Coroutine[Any, Any, None]]:
+ """Authorize against the backfill's Dag, or the Dag the request names when
there is no backfill_id."""
+ # Lookups use their own short session: a request-scoped one would hold its
connection, idle,
+ # until the sync handler returns.
async def inner(
request: Request,
user: GetUserDep,
- session: SessionDep,
) -> None:
backfill_id_raw = request.path_params.get("backfill_id")
try:
@@ -597,12 +604,14 @@ def requires_access_backfill(
if backfill_id is not None:
# The path names the backfill, so its row is the only
authorization subject: what the
# caller supplies alongside must not decide a decision the path
already scoped.
- dag_id = session.scalar(select(Backfill.dag_id).where(Backfill.id
== backfill_id))
- _authorize_backfill_in_path(method, dag_id, user)
+ async with create_session_async() as session:
+ dag_id = await
session.scalar(select(Backfill.dag_id).where(Backfill.id == backfill_id))
+ team_name = await DagModel.get_team_name_async(dag_id,
session=session) if dag_id else None
+ _authorize_backfill_in_path(method, dag_id, team_name, user)
return
# Left: the routes naming their Dag in the body (create, dry run) or
in the query string
- # (list, read by ``requires_access_dag``), and ids the handler's own
parser will reject.
+ # (list), and ids the handler's own parser will reject.
dag_id = None
# An unreadable body names no Dag, the same state as no body, so it
falls through to the
# authorization below. Broad because ``json.loads`` also raises
UnicodeDecodeError, bare
@@ -617,10 +626,20 @@ def requires_access_backfill(
status_code=status.HTTP_400_BAD_REQUEST,
detail="'dag_id' must be a string",
)
+ if dag_id is None:
+ dag_id = _get_dag_id_from_request(request)
- requires_access_dag(method, DagAccessEntity.RUN, dag_id)(
- request,
- user,
+ team_name = None
+ if dag_id:
+ async with create_session_async() as session:
+ team_name = await DagModel.get_team_name_async(dag_id,
session=session)
+ _requires_access(
+ is_authorized_callback=lambda:
get_auth_manager().is_authorized_dag(
+ method=method,
+ access_entity=DagAccessEntity.RUN,
+ details=DagDetails(id=dag_id, team_name=team_name),
+ user=user,
+ )
)
return inner
diff --git a/airflow-core/src/airflow/models/dag.py
b/airflow-core/src/airflow/models/dag.py
index 750702384ab..0251e6c6749 100644
--- a/airflow-core/src/airflow/models/dag.py
+++ b/airflow-core/src/airflow/models/dag.py
@@ -19,6 +19,7 @@ from __future__ import annotations
from collections import defaultdict
from collections.abc import Callable, Collection
+from contextlib import nullcontext
from datetime import datetime, timedelta
from threading import Lock
from typing import TYPE_CHECKING, Any, cast
@@ -26,7 +27,7 @@ from typing import TYPE_CHECKING, Any, cast
import pendulum
import sqlalchemy as sa
import structlog
-from cachetools import TTLCache, cached
+from cachetools import TTLCache
from dateutil.relativedelta import relativedelta
from sqlalchemy import (
Boolean,
@@ -68,12 +69,13 @@ from airflow.models.dagbundle import DagBundleModel
from airflow.models.dagrun import DagRun
from airflow.models.team import Team
from airflow.serialization.definitions.assets import SerializedAssetUniqueKey
+from airflow.serialization.definitions.notset import NOTSET, ArgNotSet,
is_arg_set
from airflow.serialization.encoders import DAT, encode_deadline_alert
from airflow.serialization.enums import Encoding
from airflow.timetables.base import DataInterval, PartitionMapperInfo,
Timetable
from airflow.timetables.interval import CronDataIntervalTimetable,
DeltaDataIntervalTimetable
from airflow.timetables.simple import NullTimetable, OnceTimetable
-from airflow.utils.session import NEW_SESSION, provide_session
+from airflow.utils.session import NEW_SESSION, create_session, provide_session
from airflow.utils.sqlalchemy import UtcDateTime, with_row_locks
from airflow.utils.state import DagRunState, DagSchedulingState
from airflow.utils.types import DagRunType
@@ -82,6 +84,7 @@ if TYPE_CHECKING:
from typing import TypeAlias
from dateutil.relativedelta import relativedelta
+ from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm.state import InstanceState
from sqlalchemy.sql.elements import ColumnElement
@@ -93,6 +96,7 @@ if TYPE_CHECKING:
)
from airflow.serialization.definitions.dag import SerializedDAG
from airflow.serialization.serialized_objects import LazyDeserializedDAG
+ from airflow.utils.sqlalchemy import Select
UKey: TypeAlias = SerializedAssetUniqueKey
DagStateChangeCallback = Callable[[Context], None]
@@ -120,6 +124,16 @@ def clear_team_name_cache() -> None:
_team_name_cache.clear()
+def _get_cached_team_name(dag_id: str) -> str | None | ArgNotSet:
+ with _team_name_cache_lock:
+ return _team_name_cache.get(dag_id, NOTSET)
+
+
+def _cache_team_name(dag_id: str, team_name: str | None) -> str | None:
+ with _team_name_cache_lock:
+ return _team_name_cache.setdefault(dag_id, team_name)
+
+
def infer_automated_data_interval(timetable: Timetable, logical_date:
datetime) -> DataInterval:
"""
Infer a data interval for a run against this DAG.
@@ -469,8 +483,8 @@ class DagModel(Base):
# Serialization paths that fetch a Dag by primary key cannot apply
loader options
# (e.g. Deadline.handle_miss, asset materialization), so fall back
to the cached
# resolver rather than tripping ``lazy="raise"``. Reuse this
instance's own session:
- # ``get_team_name`` is ``@provide_session``, and the session it
would otherwise open
- # is the *same* scoped session the caller holds, so closing it on
exit would detach
+ # ``get_team_name`` opens a scoped session when none is passed,
and that is the *same*
+ # scoped session the caller holds, so closing it on exit would
detach
# every object still in use.
if state.session is not None:
return DagModel.get_team_name(self.dag_id,
session=state.session)
@@ -896,17 +910,28 @@ class DagModel(Base):
)
@staticmethod
- @cached(_team_name_cache, key=lambda dag_id, **_: dag_id,
lock=_team_name_cache_lock)
- @provide_session
- def get_team_name(dag_id: str, *, session: Session = NEW_SESSION) -> str |
None:
- """Return the team name associated to a Dag or None if it is not owned
by a specific team."""
- stmt = (
+ def _build_team_name_query(dag_id: str) -> Select[str]:
+ return (
select(Team.name)
.join(DagBundleModel.teams)
.join(DagModel, DagModel.bundle_name == DagBundleModel.name)
.where(DagModel.dag_id == dag_id)
)
- return session.scalar(stmt)
+
+ @staticmethod
+ def get_team_name(dag_id: str, *, session: Session | None = None) -> str |
None:
+ """Return the team name associated to a Dag or None if it is not owned
by a specific team."""
+ if is_arg_set(team_name := _get_cached_team_name(dag_id)):
+ return team_name
+ with create_session() if session is None else nullcontext(session) as
session:
+ return _cache_team_name(dag_id,
session.scalar(DagModel._build_team_name_query(dag_id)))
+
+ @staticmethod
+ async def get_team_name_async(dag_id: str, *, session: AsyncSession) ->
str | None:
+ """Return the team name of a Dag like :meth:`get_team_name`, sharing
its cache."""
+ if is_arg_set(team_name := _get_cached_team_name(dag_id)):
+ return team_name
+ return _cache_team_name(dag_id, await
session.scalar(DagModel._build_team_name_query(dag_id)))
@staticmethod
@provide_session
diff --git
a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_backfills.py
b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_backfills.py
index 1796a5c0197..37835d51fc0 100644
---
a/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_backfills.py
+++
b/airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_backfills.py
@@ -1809,3 +1809,47 @@ class TestUnpauseBackfill(TestBackfillEndpoint):
assert (
response_detail["msg"] == "Input should be a valid integer, unable
to parse string as an integer"
)
+
+
+class TestBackfillAuthorizationOffEventLoop(TestBackfillEndpoint):
+ """
+ ``requires_access_backfill`` must not run sync SQL on the event loop.
+
+ The sweep in ``test_event_loop_blocking.py`` uses an empty DB, so it
misses the team lookup and the
+ query-string and body ``dag_id`` routes.
+ """
+
+ @pytest.mark.parametrize(
+ ("method", "url", "with_body"),
+ [
+ pytest.param("GET", "/backfills/{backfill_id}", False, id="get"),
+ pytest.param("GET", "/backfills/{backfill_id}/dag_runs", False,
id="list-dag-runs"),
+ pytest.param("PUT", "/backfills/{backfill_id}/pause", False,
id="pause"),
+ pytest.param("PUT", "/backfills/{backfill_id}/unpause", False,
id="unpause"),
+ pytest.param("PUT", "/backfills/{backfill_id}/cancel", False,
id="cancel"),
+ pytest.param("GET", "/backfills?dag_id={dag_id}", False,
id="list-by-query-dag-id"),
+ pytest.param("POST", "/backfills/dry_run", True,
id="dry-run-by-body-dag-id"),
+ ],
+ )
+ def test_authorization_runs_no_sync_sql_on_the_event_loop(
+ self, session, dag_maker, test_client, event_loop_queries, method,
url, with_body
+ ):
+ with dag_maker(session=session, dag_id="TEST_DAG_1",
schedule="@daily"):
+ EmptyOperator(task_id="mytask")
+ from_date = pendulum.parse("2024-01-01")
+ to_date = pendulum.parse("2024-01-03")
+ backfill = Backfill(dag_id="TEST_DAG_1", from_date=from_date,
to_date=to_date)
+ session.add(backfill)
+ session.commit()
+ body = (
+ {"dag_id": "TEST_DAG_1", "from_date": to_iso(from_date),
"to_date": to_iso(to_date)}
+ if with_body
+ else None
+ )
+
+ response = test_client.request(
+ method, url.format(backfill_id=backfill.id, dag_id="TEST_DAG_1"),
json=body
+ )
+
+ assert response.status_code == 200
+ assert [query.site for query in event_loop_queries] == []
diff --git a/airflow-core/tests/unit/api_fastapi/core_api/test_security.py
b/airflow-core/tests/unit/api_fastapi/core_api/test_security.py
index 73b92bcaa77..e4fdae5c06d 100644
--- a/airflow-core/tests/unit/api_fastapi/core_api/test_security.py
+++ b/airflow-core/tests/unit/api_fastapi/core_api/test_security.py
@@ -16,6 +16,7 @@
# under the License.
from __future__ import annotations
+from contextlib import asynccontextmanager
from json import JSONDecodeError
from unittest.mock import AsyncMock, Mock, patch
@@ -25,7 +26,6 @@ from itsdangerous import URLSafeSerializer
from jwt import ExpiredSignatureError, InvalidTokenError
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from sqlalchemy.orm import Session
from airflow import settings
from airflow.api_fastapi.app import create_app
@@ -111,6 +111,26 @@ def
test_build_dag_run_access_requests_includes_team_name(testing_team):
assert requests[0]["details"].team_name == "testing"
[email protected]
+def backfill_session_events():
+ return []
+
+
[email protected]
+def backfill_lookup_session(backfill_session_events):
+ """Stand in for the short session ``requires_access_backfill`` opens for
its lookups."""
+ session = Mock(spec=AsyncSession)
+
+ @asynccontextmanager
+ async def create_session_async():
+ backfill_session_events.append("open")
+ yield session
+ backfill_session_events.append("close")
+
+ with patch("airflow.api_fastapi.core_api.security.create_session_async",
create_session_async):
+ yield session
+
+
@pytest.mark.asyncio
class TestFastApiSecurity:
@classmethod
@@ -438,10 +458,10 @@ class TestFastApiSecurity:
@pytest.mark.db_test
@pytest.mark.asyncio
- @patch.object(DagModel, "get_team_name")
+ @patch.object(DagModel, "get_team_name_async", autospec=True)
@patch("airflow.api_fastapi.core_api.security.get_auth_manager")
async def test_requires_access_backfill_authorized_from_path(
- self, mock_get_auth_manager, mock_get_team_name
+ self, mock_get_auth_manager, mock_get_team_name,
backfill_lookup_session
):
"""When backfill_id is in path and Backfill exists, dag_id from
backfill is used."""
auth_manager = Mock()
@@ -449,8 +469,7 @@ class TestFastApiSecurity:
mock_get_auth_manager.return_value = auth_manager
mock_get_team_name.return_value = "team1"
- session = Mock()
- session.scalar.return_value = "backfill_dag_id"
+ backfill_lookup_session.scalar.return_value = "backfill_dag_id"
request = Mock()
request.path_params = {"backfill_id": "42"}
@@ -459,7 +478,7 @@ class TestFastApiSecurity:
user = Mock()
inner = requires_access_backfill("PUT")
- await inner(request, user, session)
+ await inner(request, user)
auth_manager.is_authorized_dag.assert_called_once_with(
method="PUT",
@@ -470,10 +489,10 @@ class TestFastApiSecurity:
@pytest.mark.db_test
@pytest.mark.asyncio
- @patch.object(DagModel, "get_team_name")
+ @patch.object(DagModel, "get_team_name_async", autospec=True)
@patch("airflow.api_fastapi.core_api.security.get_auth_manager")
async def test_requires_access_backfill_authorized_from_body(
- self, mock_get_auth_manager, mock_get_team_name
+ self, mock_get_auth_manager, mock_get_team_name,
backfill_lookup_session
):
"""With no backfill_id in the path, dag_id comes from the request body
(POST backfill)."""
auth_manager = Mock()
@@ -481,8 +500,6 @@ class TestFastApiSecurity:
mock_get_auth_manager.return_value = auth_manager
mock_get_team_name.return_value = "team1"
- session = Mock()
-
request = Mock()
request.path_params = {}
request.json = AsyncMock(return_value={"dag_id": "body_dag_id"})
@@ -490,7 +507,7 @@ class TestFastApiSecurity:
user = Mock()
inner = requires_access_backfill("POST")
- await inner(request, user, session)
+ await inner(request, user)
auth_manager.is_authorized_dag.assert_called_once_with(
method="POST",
@@ -501,17 +518,18 @@ class TestFastApiSecurity:
@pytest.mark.db_test
@pytest.mark.asyncio
- @patch.object(DagModel, "get_team_name")
+ @patch.object(DagModel, "get_team_name_async", autospec=True)
@patch("airflow.api_fastapi.core_api.security.get_auth_manager")
- async def test_requires_access_backfill_unauthorized(self,
mock_get_auth_manager, mock_get_team_name):
+ async def test_requires_access_backfill_unauthorized(
+ self, mock_get_auth_manager, mock_get_team_name,
backfill_lookup_session
+ ):
"""A caller who may not read the backfill's Dag is told it does not
exist."""
auth_manager = Mock()
auth_manager.is_authorized_dag.return_value = False
mock_get_auth_manager.return_value = auth_manager
mock_get_team_name.return_value = None
- session = Mock()
- session.scalar.return_value = "unauthorized_dag"
+ backfill_lookup_session.scalar.return_value = "unauthorized_dag"
request = Mock()
request.path_params = {"backfill_id": "1"}
@@ -519,7 +537,7 @@ class TestFastApiSecurity:
inner = requires_access_backfill("GET")
with pytest.raises(HTTPException) as exc_info:
- await inner(request, user, session)
+ await inner(request, user)
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Backfill not found"
@@ -532,10 +550,10 @@ class TestFastApiSecurity:
@pytest.mark.db_test
@pytest.mark.asyncio
- @patch.object(DagModel, "get_team_name")
+ @patch.object(DagModel, "get_team_name_async", autospec=True)
@patch("airflow.api_fastapi.core_api.security.get_auth_manager")
async def test_requires_access_backfill_forbidden_when_the_dag_is_readable(
- self, mock_get_auth_manager, mock_get_team_name
+ self, mock_get_auth_manager, mock_get_team_name,
backfill_lookup_session
):
"""A caller who may read the Dag but not write it keeps the Forbidden
answer."""
auth_manager = Mock(spec=BaseAuthManager)
@@ -543,24 +561,23 @@ class TestFastApiSecurity:
mock_get_auth_manager.return_value = auth_manager
mock_get_team_name.return_value = None
- session = Mock(spec=Session)
- session.scalar.return_value = "readable_dag"
+ backfill_lookup_session.scalar.return_value = "readable_dag"
request = Mock(spec=Request)
request.path_params = {"backfill_id": "1"}
user = Mock(spec=BaseUser)
with pytest.raises(HTTPException) as exc_info:
- await requires_access_backfill("PUT")(request, user, session)
+ await requires_access_backfill("PUT")(request, user)
assert exc_info.value.status_code == 403
@pytest.mark.db_test
@pytest.mark.asyncio
- @patch.object(DagModel, "get_team_name")
+ @patch.object(DagModel, "get_team_name_async", autospec=True)
@patch("airflow.api_fastapi.core_api.security.get_auth_manager")
async def
test_requires_access_backfill_unknown_id_ignores_the_request_dag_id(
- self, mock_get_auth_manager, mock_get_team_name
+ self, mock_get_auth_manager, mock_get_team_name,
backfill_lookup_session
):
"""An unknown backfill is not authorized against a Dag the caller
names."""
auth_manager = Mock(spec=BaseAuthManager)
@@ -568,8 +585,7 @@ class TestFastApiSecurity:
mock_get_auth_manager.return_value = auth_manager
mock_get_team_name.return_value = "team1"
- session = Mock(spec=Session)
- session.scalar.return_value = None
+ backfill_lookup_session.scalar.return_value = None
request = Mock(spec=Request)
request.path_params = {"backfill_id": "999"}
@@ -579,7 +595,7 @@ class TestFastApiSecurity:
user = Mock(spec=BaseUser)
with pytest.raises(HTTPException) as exc_info:
- await requires_access_backfill("PUT")(request, user, session)
+ await requires_access_backfill("PUT")(request, user)
assert exc_info.value.status_code == 404
assert exc_info.value.detail == "Backfill not found"
@@ -588,10 +604,10 @@ class TestFastApiSecurity:
@pytest.mark.db_test
@pytest.mark.asyncio
@pytest.mark.parametrize("backfill_id", ["42", "42.0", "42.00"])
- @patch.object(DagModel, "get_team_name")
+ @patch.object(DagModel, "get_team_name_async", autospec=True)
@patch("airflow.api_fastapi.core_api.security.get_auth_manager")
async def
test_requires_access_backfill_authorizes_the_backfill_the_handler_will_act_on(
- self, mock_get_auth_manager, mock_get_team_name, backfill_id
+ self, mock_get_auth_manager, mock_get_team_name, backfill_id,
backfill_lookup_session
):
"""The dependency must resolve the same backfill the handler does, for
every spelling.
@@ -605,8 +621,7 @@ class TestFastApiSecurity:
mock_get_auth_manager.return_value = auth_manager
mock_get_team_name.return_value = "team1"
- session = Mock(spec=Session)
- session.scalar.return_value = "backfill_dag"
+ backfill_lookup_session.scalar.return_value = "backfill_dag"
request = Mock(spec=Request)
request.path_params = {"backfill_id": backfill_id}
@@ -615,7 +630,7 @@ class TestFastApiSecurity:
user = Mock(spec=BaseUser)
- await requires_access_backfill("PUT")(request, user, session)
+ await requires_access_backfill("PUT")(request, user)
# the backfill's own Dag, not the one supplied on the request
auth_manager.is_authorized_dag.assert_called_once_with(
@@ -625,6 +640,47 @@ class TestFastApiSecurity:
user=user,
)
+ @pytest.mark.db_test
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("path_params", "body"),
+ [
+ pytest.param({"backfill_id": "1"}, {}, id="backfill-in-path"),
+ pytest.param({}, {"dag_id": "body_dag"}, id="dag-in-body"),
+ ],
+ )
+ @patch.object(DagModel, "get_team_name_async", autospec=True)
+ @patch("airflow.api_fastapi.core_api.security.get_auth_manager")
+ async def
test_requires_access_backfill_closes_its_session_before_authorizing(
+ self,
+ mock_get_auth_manager,
+ mock_get_team_name,
+ path_params,
+ body,
+ backfill_lookup_session,
+ backfill_session_events,
+ ):
+ """The lookup session is gone before the handler runs, rather than
held idle through it."""
+
+ def authorize(**_):
+ backfill_session_events.append("authorize")
+ return True
+
+ auth_manager = Mock(spec=BaseAuthManager)
+ auth_manager.is_authorized_dag.side_effect = authorize
+ mock_get_auth_manager.return_value = auth_manager
+ mock_get_team_name.return_value = None
+ backfill_lookup_session.scalar.return_value = "backfill_dag"
+
+ request = Mock(spec=Request)
+ request.path_params = path_params
+ request.query_params = {}
+ request.json = AsyncMock(return_value=body)
+
+ await requires_access_backfill("GET")(request, Mock(spec=BaseUser))
+
+ assert backfill_session_events == ["open", "close", "authorize"]
+
@pytest.mark.db_test
@pytest.mark.asyncio
@patch.object(DagModel, "get_team_name")
@@ -1094,23 +1150,22 @@ class TestFastApiSecurity:
@pytest.mark.db_test
@pytest.mark.parametrize("bad_dag_id", [123, ["x"], {"name": "x"}, True])
- @patch("airflow.api_fastapi.core_api.security.requires_access_dag")
+ @patch("airflow.api_fastapi.core_api.security.get_auth_manager")
async def test_requires_access_backfill_non_string_dag_id_returns_400(
- self, mock_requires_access_dag, bad_dag_id
+ self, mock_get_auth_manager, bad_dag_id
):
"""Non-string dag_id in the body must be rejected with 400 before
authz."""
fastapi_request = Mock()
fastapi_request.path_params = {}
fastapi_request.json = AsyncMock(return_value={"dag_id": bad_dag_id})
user = Mock()
- session = Mock()
with pytest.raises(HTTPException) as exc_info:
- await requires_access_backfill("POST")(fastapi_request, user,
session)
+ await requires_access_backfill("POST")(fastapi_request, user)
assert exc_info.value.status_code == 400
assert "dag_id" in exc_info.value.detail
- mock_requires_access_dag.assert_not_called()
+ mock_get_auth_manager.assert_not_called()
@patch.object(Connection, "get_conn_id_to_team_name_mapping")
@patch("airflow.api_fastapi.core_api.security.get_auth_manager")
diff --git
a/airflow-core/tests/unit/api_fastapi/known_sync_db_on_event_loop.txt
b/airflow-core/tests/unit/api_fastapi/known_sync_db_on_event_loop.txt
index 918ed8e5757..e54e2bb591a 100644
--- a/airflow-core/tests/unit/api_fastapi/known_sync_db_on_event_loop.txt
+++ b/airflow-core/tests/unit/api_fastapi/known_sync_db_on_event_loop.txt
@@ -14,15 +14,5 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-GET /api/v2/backfills/{backfill_id}/dag_runs::default
-GET /api/v2/backfills/{backfill_id}/dag_runs::multi_team
-GET /api/v2/backfills/{backfill_id}::default
-GET /api/v2/backfills/{backfill_id}::multi_team
GET /api/v2/eventLogs/{event_log_id}::default
GET /api/v2/eventLogs/{event_log_id}::multi_team
-PUT /api/v2/backfills/{backfill_id}/cancel::default
-PUT /api/v2/backfills/{backfill_id}/cancel::multi_team
-PUT /api/v2/backfills/{backfill_id}/pause::default
-PUT /api/v2/backfills/{backfill_id}/pause::multi_team
-PUT /api/v2/backfills/{backfill_id}/unpause::default
-PUT /api/v2/backfills/{backfill_id}/unpause::multi_team
diff --git a/airflow-core/tests/unit/models/test_dag.py
b/airflow-core/tests/unit/models/test_dag.py
index 14c5f38a3b4..34d3e60e480 100644
--- a/airflow-core/tests/unit/models/test_dag.py
+++ b/airflow-core/tests/unit/models/test_dag.py
@@ -106,7 +106,7 @@ from airflow.timetables.simple import (
OnceTimetable,
)
from airflow.triggers.base import TriggerEvent
-from airflow.utils.session import create_session
+from airflow.utils.session import create_session, create_session_async
from airflow.utils.sqlalchemy import with_row_locks
from airflow.utils.state import DagRunState, DagSchedulingState, State,
TaskInstanceState
from airflow.utils.types import DagRunTriggeredByType, DagRunType
@@ -3650,6 +3650,37 @@ class TestDagModel:
clear_team_name_cache()
assert DagModel.get_team_name(dag_id, session=session) is None
+ @pytest.mark.asyncio
+ async def test_get_team_name_async_shares_the_cache_of_get_team_name(self,
testing_team):
+ session = settings.Session()
+ team_bundle = DagBundleModel(name="async-team-bundle")
+ team_bundle.teams.append(testing_team)
+ no_team_bundle = DagBundleModel(name="async-no-team-bundle")
+ session.add_all([team_bundle, no_team_bundle])
+ session.flush()
+ dag_id = "test_get_team_name_async"
+ orm_dag = DagModel(dag_id=dag_id, bundle_name="async-team-bundle",
is_stale=False)
+ session.add(orm_dag)
+ # The async lookup reads on its own connection, so it only sees
committed rows.
+ session.commit()
+
+ clear_team_name_cache()
+ async with create_session_async() as async_session:
+ assert await DagModel.get_team_name_async(dag_id,
session=async_session) == "testing"
+
+ # The sync lookup is served from the entry the async one cached.
+ orm_dag.bundle_name = "async-no-team-bundle"
+ session.commit()
+ assert DagModel.get_team_name(dag_id, session=session) == "testing"
+
+ # A cached None is served too, rather than taken for a miss.
+ clear_team_name_cache()
+ assert DagModel.get_team_name(dag_id, session=session) is None
+ orm_dag.bundle_name = "async-team-bundle"
+ session.commit()
+ async with create_session_async() as async_session:
+ assert await DagModel.get_team_name_async(dag_id,
session=async_session) is None
+
def test_get_dag_id_to_team_name_mapping(self, testing_team):
session = settings.Session()
bundle1 = DagBundleModel(name="bundle1")