This is an automated email from the ASF dual-hosted git repository.

vincbeck 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 3af9efd26f5 Redirect to the requested page after AWS SAML login 
(#77208) (#77209)
3af9efd26f5 is described below

commit 3af9efd26f587eef78ef2662d22de8e0887ed81c
Author: Sachin Chandra Yadav <[email protected]>
AuthorDate: Thu Nov 19 00:32:56 2026 +0530

    Redirect to the requested page after AWS SAML login (#77208) (#77209)
    
    The AWS auth manager dropped the `next` URL query parameter passed to
    `/auth/login`, so after signing in users always landed on the home page
    instead of the Dag or log they had opened.
    
    Keep a safe `next` URL in the signed pending login state during the
    SAML round trip and redirect to it from the login callback, falling
    back to `[api] base_url`.
    
    Signed-off-by: Sachin Chandra Yadav <[email protected]>
---
 .../amazon/aws/auth_manager/routes/login.py        |  36 ++++--
 .../amazon/aws/auth_manager/routes/test_login.py   | 128 +++++++++++++++++----
 2 files changed, 132 insertions(+), 32 deletions(-)

diff --git 
a/providers/amazon/src/airflow/providers/amazon/aws/auth_manager/routes/login.py
 
b/providers/amazon/src/airflow/providers/amazon/aws/auth_manager/routes/login.py
index 3f03b59b688..1067c604e73 100644
--- 
a/providers/amazon/src/airflow/providers/amazon/aws/auth_manager/routes/login.py
+++ 
b/providers/amazon/src/airflow/providers/amazon/aws/auth_manager/routes/login.py
@@ -38,6 +38,7 @@ from airflow.api_fastapi.app import (
 )
 from airflow.api_fastapi.auth.managers.base_auth_manager import 
COOKIE_NAME_JWT_TOKEN
 from airflow.api_fastapi.common.router import AirflowRouter
+from airflow.api_fastapi.core_api.security import is_safe_url
 from airflow.providers.amazon.aws.auth_manager.constants import (
     CONF_ALLOW_IDP_INITIATED_LOGIN_KEY,
     CONF_SAML_METADATA_URL_KEY,
@@ -81,6 +82,11 @@ LOGIN_STATE_MAX_AGE = 600
 # invalidate the first. The cap bounds the cookie; the oldest pending login is 
dropped.
 MAX_PENDING_LOGINS = 5
 
+# Cap the JSON-encoded length of the redirect URL stored in the pending entry 
so that
+# 5 pending entries do not push the base64-encoded cookie past the ~4 KB 
browser limit,
+# even when non-Latin-1 characters expand to \uXXXX escapes.
+MAX_NEXT_URL_JSON_LENGTH = 400
+
 LOGIN_MODE_REDIRECT = "login-redirect"
 LOGIN_MODE_TOKEN = "login-token"
 LOGIN_MODES = (LOGIN_MODE_REDIRECT, LOGIN_MODE_TOKEN)
@@ -196,14 +202,22 @@ def _start_login(request: Request, mode: str) -> 
RedirectResponse:
     callback_url = saml_auth.login(f"{mode}:{nonce}")
     response = RedirectResponse(url=callback_url)
     pending = _read_pending_logins(request)[-(MAX_PENDING_LOGINS - 1) :]
-    pending.append(
-        {
-            "nonce": nonce,
-            "request_id": saml_auth.get_last_request_id(),
-            "mode": mode,
-            "exp": time.time() + LOGIN_STATE_MAX_AGE,
-        }
-    )
+    entry: dict[str, Any] = {
+        "nonce": nonce,
+        "request_id": saml_auth.get_last_request_id(),
+        "mode": mode,
+        "exp": time.time() + LOGIN_STATE_MAX_AGE,
+    }
+    if mode == LOGIN_MODE_REDIRECT:
+        next_url = request.query_params.get("next")
+        if next_url:
+            if len(json.dumps(next_url)) <= MAX_NEXT_URL_JSON_LENGTH and 
is_safe_url(
+                next_url, request=request
+            ):
+                entry["next"] = next_url
+            else:
+                log.debug("Dropping next URL %r: exceeds maximum length or is 
unsafe.", next_url)
+    pending.append(entry)
     _write_pending_logins(request, response, pending)
     return response
 
@@ -273,14 +287,16 @@ def login_callback(request: Request):
         username=saml_auth.get_nameid(),
         email=attributes["email"][0] if "email" in attributes else None,
     )
-    url = conf.get("api", "base_url", fallback="/")
+    fallback_url = conf.get("api", "base_url", fallback="/")
+    next_url = matched.get("next") if matched else None
+    redirect_url = next_url or fallback_url
     token = get_auth_manager().generate_jwt(user)
 
     response: Any
     if mode == LOGIN_MODE_REDIRECT:
-        response = RedirectResponse(url=url, status_code=303)
         cookie_path = get_cookie_path()
         secure = _is_secure_request(request)
+        response = RedirectResponse(url=redirect_url, status_code=303)
         # In Airflow 3.1.1 authentication changes, front-end no longer handle 
the token
         # See https://github.com/apache/airflow/pull/55506
         if AIRFLOW_V_3_1_1_PLUS:
diff --git 
a/providers/amazon/tests/unit/amazon/aws/auth_manager/routes/test_login.py 
b/providers/amazon/tests/unit/amazon/aws/auth_manager/routes/test_login.py
index 32a6499e515..c07a4b650fa 100644
--- a/providers/amazon/tests/unit/amazon/aws/auth_manager/routes/test_login.py
+++ b/providers/amazon/tests/unit/amazon/aws/auth_manager/routes/test_login.py
@@ -19,6 +19,7 @@ from __future__ import annotations
 import base64
 import json
 import time
+from typing import Any
 from unittest.mock import Mock, patch
 
 import pytest
@@ -48,6 +49,7 @@ from airflow.providers.amazon.aws.auth_manager.routes.login 
import (  # noqa: E4
     COOKIE_NAME_LOGIN_STATE,
     LOGIN_MODE_REDIRECT,
     LOGIN_MODE_TOKEN,
+    MAX_NEXT_URL_JSON_LENGTH,
     _sign_login_state,
 )
 
@@ -86,27 +88,30 @@ BASE_CONF = {
 }
 
 
-def make_login_state(*entries: tuple[str, str, str], expires_in: float = 600) 
-> str:
+def make_login_state(
+    *entries: tuple[str, str, str] | tuple[str, str, str, str | None],
+    expires_in: float = 600,
+) -> str:
     """
     Build the signed login-state cookie a browser would hold for ``entries``.
 
-    Each entry is ``(nonce, request_id, mode)``. Must be called inside the 
``conf_vars``
-    block that sets the signing key, so the signature matches what the route 
computes.
+    Each entry is ``(nonce, request_id, mode)`` or ``(nonce, request_id, mode, 
next_url)``.
+    Must be called inside the ``conf_vars`` block that sets the signing key, 
so the
+    signature matches what the route computes.
     """
-    payload = base64.urlsafe_b64encode(
-        json.dumps(
-            [
-                {
-                    "nonce": nonce,
-                    "request_id": request_id,
-                    "mode": mode,
-                    "exp": time.time() + expires_in,
-                }
-                for nonce, request_id, mode in entries
-            ],
-            separators=(",", ":"),
-        ).encode()
-    ).decode()
+    items = []
+    for entry in entries:
+        nonce, request_id, mode = entry[:3]
+        item: dict[str, Any] = {
+            "nonce": nonce,
+            "request_id": request_id,
+            "mode": mode,
+            "exp": time.time() + expires_in,
+        }
+        if len(entry) > 3 and entry[3]:
+            item["next"] = entry[3]
+        items.append(item)
+    payload = base64.urlsafe_b64encode(json.dumps(items, separators=(",", 
":")).encode()).decode()
     return f"{payload}.{_sign_login_state(payload)}"
 
 
@@ -118,6 +123,15 @@ def read_login_state_cookie(response) -> str | None:
     return None
 
 
+def parse_login_state_cookie(response) -> list[dict[str, Any]]:
+    """Decode and return the pending login entries from the login-state 
cookie."""
+    cookie = read_login_state_cookie(response)
+    if not cookie:
+        return []
+    payload, _, _ = cookie.rpartition(".")
+    return json.loads(base64.urlsafe_b64decode(payload))
+
+
 @pytest.fixture(autouse=True)
 def no_plugins():
     """
@@ -149,7 +163,7 @@ def get_login_callback_response(
     relay_state: str,
     *,
     base_url: str = "http://testserver";,
-    pending: list[tuple[str, str, str]] | None = None,
+    pending: list[tuple[str, str, str] | tuple[str, str, str, str | None]] | 
None = None,
     raw_login_state: str | None = None,
     expires_in: float = 600,
     in_response_to: str | None = None,
@@ -160,10 +174,11 @@ def get_login_callback_response(
     """
     Post a SAML response to the callback.
 
-    ``pending`` is what this browser has started, as ``(nonce, request_id, 
mode)`` tuples; it
-    defaults to a single entry answering ``relay_state``, i.e. a browser that 
really did start
-    this login. ``raw_login_state`` sets the cookie verbatim instead -- pass 
``""`` for a
-    browser that started nothing.
+    ``pending`` is what this browser has started, as ``(nonce, request_id, 
mode)`` or
+    ``(nonce, request_id, mode, next_url)`` tuples; it defaults to a single 
entry
+    answering ``relay_state``, i.e. a browser that really did start this login.
+    ``raw_login_state`` sets the cookie verbatim instead -- pass ``""`` for a 
browser
+    that started nothing.
     """
     with conf_vars({**BASE_CONF, **(extra_conf or {})}):
         with (
@@ -226,6 +241,75 @@ class TestLoginRouter:
             "https://portal.sso.us-east-1.amazonaws.com/saml/assertion/";
         )
 
+    @pytest.mark.parametrize(
+        ("next_url", "expected_stored_next"),
+        [
+            ("/dags/my_dag", "/dags/my_dag"),
+            ("/dags/my_dag/runs/run_1/tasks/task_1", 
"/dags/my_dag/runs/run_1/tasks/task_1"),
+            ("/dags?search=日本", "/dags?search=日本"),
+            ("https://attacker.example.net/dags";, None),
+            ("//attacker.example.net/dags", None),
+            ("javascript:alert(1)", None),
+            ("/dags/" + "a" * (MAX_NEXT_URL_JSON_LENGTH + 1), None),
+            ("/dags?search=" + "日" * 70, None),
+        ],
+    )
+    def test_login_stores_next_url(self, test_client, next_url, 
expected_stored_next):
+        response = test_client.get(
+            AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login",
+            params={"next": next_url},
+            follow_redirects=False,
+        )
+        assert response.status_code == 307
+        entries = parse_login_state_cookie(response)
+        assert len(entries) == 1
+        assert entries[0].get("next") == expected_stored_next
+
+    def test_login_token_does_not_store_next_url(self, test_client):
+        response = test_client.get(
+            AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login/token",
+            params={"next": "/dags/my_dag"},
+            follow_redirects=False,
+        )
+        assert response.status_code == 307
+        entries = parse_login_state_cookie(response)
+        assert len(entries) == 1
+        assert "next" not in entries[0]
+
+    def test_login_preserves_per_tab_next_url(self, test_client):
+        """Each tab calling /login keeps its own next_url in the pending login 
state."""
+        response1 = test_client.get(
+            AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login",
+            params={"next": "/dags/dag_a"},
+            follow_redirects=False,
+        )
+        assert response1.status_code == 307
+
+        response2 = test_client.get(
+            AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login",
+            params={"next": "/dags/dag_b"},
+            follow_redirects=False,
+        )
+        assert response2.status_code == 307
+
+        entries = parse_login_state_cookie(response2)
+        assert len(entries) == 2
+        assert entries[0].get("next") == "/dags/dag_a"
+        assert entries[1].get("next") == "/dags/dag_b"
+
+    @pytest.mark.parametrize(
+        ("next_url", "expected_location"),
+        [
+            ("/dags/my_dag/runs/run_id/tasks/my_task", 
"/dags/my_dag/runs/run_id/tasks/my_task"),
+            (None, "http://localhost:8080/";),
+        ],
+    )
+    def test_login_callback_redirects_to_next_url(self, next_url, 
expected_location):
+        pending = [(TEST_NONCE, EXPECTED_REQUEST_ID, LOGIN_MODE_REDIRECT, 
next_url)]
+        response = get_login_callback_response(RELAY_REDIRECT, pending=pending)
+        assert response.status_code == 303
+        assert response.headers["location"] == expected_location
+
     def test_login_callback_successful_with_relay_state_redirect(self):
         response = get_login_callback_response(RELAY_REDIRECT)
         assert response.status_code == 303

Reply via email to