Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions providers/fab/src/airflow/providers/fab/www/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,18 @@ def __init__(self, *args, **kwargs):

class AirflowSecureCookieSessionInterface(SessionExemptMixin, SecureCookieSessionInterface):
"""Session interface that exempts some routes and stores session data in a signed cookie."""

def save_session(self, app, session, response):
"""Save session, ensuring cookie values are str for Werkzeug 3.0+."""
# Werkzeug 3.0 removed automatic bytes-to-str coercion in set_cookie().
# The itsdangerous signing serializer may return bytes in some
# configurations; coerce to str so the cookie value is always valid.
original_set_cookie = response.set_cookie

def _str_set_cookie(key, value="", **kwargs):
if isinstance(value, bytes):
value = value.decode("utf-8")
return original_set_cookie(key, value, **kwargs)

response.set_cookie = _str_set_cookie
return super().save_session(app, session, response)
133 changes: 133 additions & 0 deletions providers/fab/tests/unit/fab/www/test_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations

from unittest.mock import MagicMock, patch

from flask_babel import LazyString

from airflow.providers.fab.www.session import (
AirflowSecureCookieSessionInterface,
_LazySafeSerializer,
)


class TestLazySafeSerializer:
def setup_method(self):
self.serializer = _LazySafeSerializer()

def test_dumps_returns_bytes(self):
result = self.serializer.dumps({"key": "value"})
assert isinstance(result, bytes)

def test_roundtrip(self):
data = {"user_id": 42, "role": "Admin", "active": True}
encoded = self.serializer.dumps(data)
decoded = self.serializer.loads(encoded)
assert decoded == data

def test_lazy_string_converted(self):
lazy = LazyString(lambda: "translated")
encoded = self.serializer.dumps({"label": lazy})
decoded = self.serializer.loads(encoded)
assert decoded["label"] == "translated"

def test_empty_session(self):
encoded = self.serializer.dumps({})
decoded = self.serializer.loads(encoded)
assert decoded == {}

def test_nested_data(self):
data = {"prefs": {"theme": "dark", "items": [1, 2, 3]}}
encoded = self.serializer.dumps(data)
decoded = self.serializer.loads(encoded)
assert decoded == data

def test_encode_decode_aliases(self):
data = {"alias": True}
assert self.serializer.encode(data) == self.serializer.dumps(data)

encoded = self.serializer.dumps(data)
assert self.serializer.decode(encoded) == self.serializer.loads(encoded)


class TestAirflowSecureCookieSessionInterface:
"""Test that save_session coerces bytes cookie values to str for Werkzeug 3.0+."""

def test_save_session_decodes_bytes_cookie_value(self):
interface = AirflowSecureCookieSessionInterface()
app = MagicMock()
session = MagicMock()
response = MagicMock()

captured_values = []

def track_set_cookie(key, value="", **kwargs):
captured_values.append(value)

response.set_cookie = track_set_cookie

# Patch the grandparent (SecureCookieSessionInterface) save_session to
# simulate Flask calling set_cookie with bytes. patch.object replaces
# the method on the class with a MagicMock; when called via super() the
# mock's side_effect receives positional args WITHOUT self.
#
# session.py imports `request` via `from flask import request`, so we
# must patch the name in that module's namespace rather than flask.request
# (which is a different reference once the import has been evaluated).
with (
patch("airflow.providers.fab.www.session.request") as mock_request,
patch.object(
type(interface).__mro__[2],
"save_session",
side_effect=lambda *args, **kwargs: response.set_cookie("session", b"signed-bytes-value"),
),
):
mock_request.path = "/any"
interface.save_session(app, session, response)

assert len(captured_values) == 1
assert isinstance(captured_values[0], str)
assert captured_values[0] == "signed-bytes-value"

def test_save_session_passes_str_value_unchanged(self):
interface = AirflowSecureCookieSessionInterface()
app = MagicMock()
session = MagicMock()
response = MagicMock()

captured_values = []

def track_set_cookie(key, value="", **kwargs):
captured_values.append(value)

response.set_cookie = track_set_cookie

with (
patch("airflow.providers.fab.www.session.request") as mock_request,
patch.object(
type(interface).__mro__[2],
"save_session",
side_effect=lambda *args, **kwargs: response.set_cookie("session", "already-a-string"),
),
):
mock_request.path = "/any"
interface.save_session(app, session, response)

assert len(captured_values) == 1
assert isinstance(captured_values[0], str)
assert captured_values[0] == "already-a-string"