~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
security: fix mass assignment in subscription updates (#3131)
LearningCircuit8e1547e6e3b4
diff --git a/changelog.d/3131.bugfix.md b/changelog.d/3131.bugfix.mdnew file mode 100644index 0000000000..3dbd0b482e--- /dev/null+++ b/changelog.d/3131.bugfix.md@@ -0,0 +1 @@+`PUT /news/api/subscription/folders/{id}` accepts a request body that includes the folder's own `id`/`created_at`/`updated_at` fields; those fields are ignored rather than written. `PUT /news/api/subscription/subscriptions/{id}` accepts a request body that includes its own PUT response's `id`/`next_refresh`/`last_refresh` fields; those are likewise ignored rather than written.diff --git a/changelog.d/3131.security.md b/changelog.d/3131.security.mdnew file mode 100644index 0000000000..fdb4008f14--- /dev/null+++ b/changelog.d/3131.security.md@@ -0,0 +1 @@+Compact subscription updates now reject unsupported fields and invalid values before database access, preventing mass assignment while preserving folder, notes, refresh interval, and active or paused status updates.diff --git a/src/local_deep_research/news/constants.py b/src/local_deep_research/news/constants.pynew file mode 100644index 0000000000..dadcebb0ae--- /dev/null+++ b/src/local_deep_research/news/constants.py@@ -0,0 +1,211 @@+"""Shared constants for the news subsystem."""++from ..database.models.news import SubscriptionFolder++# Subscription scheduling bounds. Shared by the create route and both+# update routes (``web/routers/news_flask_api.py`` imports these back) so+# their limits cannot drift apart.+NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES = 1+NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES = 10_080++# ``NewsSubscription.name`` is ``Column(String(255))`` (database/models/+# news.py:63) -- this mirrors that column's length, it is not an+# independently chosen limit.+COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH = 255++COMPACT_SUBSCRIPTION_DIRECT_FIELDS = (+ "folder",+ "folder_id",+ "name",+ "notes",+ "refresh_interval_minutes",+)+COMPACT_SUBSCRIPTION_INPUT_FIELDS = frozenset(+ (*COMPACT_SUBSCRIPTION_DIRECT_FIELDS, "is_active", "status")+)+COMPACT_SUBSCRIPTION_STATUSES = frozenset({"active", "paused"})++# The exact key set of the response body+# ``news_flask_api._update_subscription_folder_sync`` returns from a+# successful PUT /news/api/subscription/subscriptions/{id}. NewsSubscription+# has no ``to_dict()`` (unlike SubscriptionFolder below), so this is hand-kept+# in sync with that dict literal rather than introspected off the model --+# deliberately NOT "every NewsSubscription column minus the allowlist", which+# would also swallow genuinely sensitive, non-response columns such as+# ``custom_endpoint`` (the very field #5603/this PR's docstring call out as+# needing to stay rejected, not silently dropped).+COMPACT_SUBSCRIPTION_RESPONSE_FIELDS = frozenset(+ (+ "id",+ "name",+ "status",+ "is_active",+ "folder_id",+ "refresh_interval_minutes",+ "next_refresh",+ "last_refresh",+ )+)+# Fields the endpoint's own response echoes back that are not writable.+# A client that PUTs its own prior PUT response back (change one field,+# resend the rest) always resends these; rejecting them broke that pattern.+# They are still never written -- see the allowlist-only comprehension at+# the end of normalize_compact_subscription_update -- only no longer+# rejected for merely being present.+COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS = (+ COMPACT_SUBSCRIPTION_RESPONSE_FIELDS - COMPACT_SUBSCRIPTION_INPUT_FIELDS+)+++def normalize_compact_subscription_update(data):+ unsupported_fields = (+ set(data)+ - COMPACT_SUBSCRIPTION_INPUT_FIELDS+ - COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS+ )+ if unsupported_fields:+ fields = ", ".join(sorted(unsupported_fields))+ raise ValueError(f"Unsupported subscription update fields: {fields}")++ if "is_active" in data and type(data["is_active"]) is not bool:+ raise ValueError("is_active must be a boolean")++ if "status" in data and (+ type(data["status"]) is not str+ or data["status"] not in COMPACT_SUBSCRIPTION_STATUSES+ ):+ raise ValueError("status must be 'active' or 'paused'")++ if "refresh_interval_minutes" in data and (+ type(data["refresh_interval_minutes"]) is not int+ or not NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES+ <= data["refresh_interval_minutes"]+ <= NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES+ ):+ raise ValueError(+ "refresh_interval_minutes must be an integer between "+ f"{NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES} and "+ f"{NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES}"+ )++ for field in ("folder", "folder_id", "name", "notes"):+ if (+ field in data+ and data[field] is not None+ and type(data[field]) is not str+ ):+ raise ValueError(f"{field} must be a string or null")++ # ``name`` is user-editable through the full ``PUT /subscriptions/{id}``+ # route's ``field_mapping`` (web/routers/news_flask_api.py) and shares+ # that column's length bound here.+ if (+ "name" in data+ and isinstance(data["name"], str)+ and len(data["name"]) > COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH+ ):+ raise ValueError(+ "name exceeds maximum length of "+ f"{COMPACT_SUBSCRIPTION_NAME_MAX_LENGTH} characters"+ )++ update_data = {+ field: data[field]+ for field in COMPACT_SUBSCRIPTION_DIRECT_FIELDS+ if field in data+ }+ if "is_active" in data:+ update_data["status"] = "active" if data["is_active"] else "paused"+ if "status" in data:+ update_data["status"] = data["status"]+ return update_data+++# The SubscriptionFolder model's user-editable columns (see+# database/models/news.py). id/created_at/updated_at are deliberately+# excluded -- they are server-managed, so setattr must never reach them --+# but see FOLDER_READONLY_ECHO_FIELDS below: excluded from *writes* is not+# the same as rejecting a request that merely *mentions* them.+FOLDER_UPDATABLE_FIELDS = frozenset(+ ("name", "description", "color", "icon", "is_default", "sort_order")+)++# SubscriptionFolder.to_dict() emits every column on the model, including+# id/created_at/updated_at, which are not in FOLDER_UPDATABLE_FIELDS above.+# A read-modify-write client (GET the folder, change ``name``, PUT the whole+# to_dict() body back) always resends those three. Derived from the live+# model's columns -- not hardcoded -- so it can't drift from what to_dict()+# actually returns; anything that's a real column here is inherently safe to+# ignore rather than reject, since FOLDER_UPDATABLE_FIELDS below still+# decides what actually gets written regardless of what this set allows+# through the door.+FOLDER_READONLY_ECHO_FIELDS = (+ frozenset(column.name for column in SubscriptionFolder.__table__.columns)+ - FOLDER_UPDATABLE_FIELDS+)+++def normalize_folder_update(data):+ """Validate a folder update payload against the allowlisted fields.++ ``FolderManager.update_folder`` used to accept any key for which+ ``hasattr(folder, key)`` was true on the live SQLAlchemy instance --+ which holds not just for real columns but also for ORM internals like+ ``_sa_instance_state``, ``metadata``/``registry``, and the bound+ ``to_dict`` method. A request body could therefore corrupt ORM+ identity state or shadow ``to_dict`` on the instance (breaking the+ route's own ``folder.to_dict()`` call on the same request). Restrict+ updates to the model's real, user-editable columns instead.++ Field-name allowlisting alone isn't enough: ``FolderManager.update_folder``+ does a blind ``setattr(folder, key, value)`` loop over whatever survives+ here, straight into the SQLAlchemy session. A wrong-typed value (e.g.+ ``{"sort_order": "abc"}``) either dies as an opaque 500 at+ ``session.commit()`` or, thanks to SQLite's dynamic column typing,+ silently coerces/stores the wrong type instead of erroring at all. So+ type-check each field here too, mirroring+ :func:`normalize_compact_subscription_update`'s style -- an invalid body+ must never reach the session.++ Keys in :data:`FOLDER_READONLY_ECHO_FIELDS` (``id``, ``created_at``,+ ``updated_at``) are accepted but ignored rather than rejected: they are+ exactly what ``folder.to_dict()`` echoes back, so a client doing a+ normal read-modify-write round trip always resends them. The final+ dict comprehension below still only pulls from+ ``FOLDER_UPDATABLE_FIELDS``, so none of them ever reaches ``setattr`` --+ this only changes whether *mentioning* them 400s the whole request.+ """+ unsupported_fields = (+ set(data) - FOLDER_UPDATABLE_FIELDS - FOLDER_READONLY_ECHO_FIELDS+ )+ if unsupported_fields:+ fields = ", ".join(sorted(unsupported_fields))+ raise ValueError(f"Unsupported folder update fields: {fields}")++ # ``name`` is NOT NULL on the SubscriptionFolder model (database/models/+ # news.py), so unlike description/color/icon it cannot accept a null.+ if "name" in data and type(data["name"]) is not str:+ raise ValueError("name must be a string")++ for field in ("description", "color", "icon"):+ if (+ field in data+ and data[field] is not None+ and type(data[field]) is not str+ ):+ raise ValueError(f"{field} must be a string or null")++ if "is_default" in data and type(data["is_default"]) is not bool:+ raise ValueError("is_default must be a boolean")++ # ``type(x) is not int`` (rather than ``isinstance``) also rejects a+ # bool masquerading as an int -- ``type(True) is bool``, not ``int`` --+ # matching the convention already used above for ``is_default`` and by+ # ``normalize_compact_subscription_update`` for ``is_active``/+ # ``refresh_interval_minutes``.+ if "sort_order" in data and type(data["sort_order"]) is not int:+ raise ValueError("sort_order must be an integer")++ return {+ field: data[field] for field in FOLDER_UPDATABLE_FIELDS if field in data+ }diff --git a/src/local_deep_research/news/folder_manager.py b/src/local_deep_research/news/folder_manager.pyindex 030144b053..8ceff958f8 100644--- a/src/local_deep_research/news/folder_manager.py+++ b/src/local_deep_research/news/folder_manager.py@@ -10,6 +10,10 @@ from ..database.models import (SubscriptionFolder,NewsSubscription as BaseSubscription,)+from .constants import (+ normalize_compact_subscription_update,+ normalize_folder_update,+)class FolderManager:@@ -45,17 +49,25 @@ class FolderManager:def update_folder(self, folder_id: int, **kwargs) -> Optional[SubscriptionFolder]:- """Update a folder."""+ """Update a folder.++ ``kwargs`` is validated against :data:`FOLDER_UPDATABLE_FIELDS` via+ :func:`normalize_folder_update` before anything else runs -- the+ blind ``hasattr``-gated ``setattr`` loop this replaced accepted any+ attribute name the SQLAlchemy model instance had, including+ ORM-internal ones (``_sa_instance_state``) and the bound+ ``to_dict`` method, either of which corrupts the instance or the+ route's subsequent ``folder.to_dict()`` call. Raises ``ValueError``+ naming the offending field(s) for anything outside the allowlist.+ """+ update_data = normalize_folder_update(kwargs)+folder = self.session.get(SubscriptionFolder, folder_id)if not folder:return None- for key, value in kwargs.items():- if hasattr(folder, key) and key not in [- "id",- "created_at",- ]:- setattr(folder, key, value)+ for key, value in update_data.items():+ setattr(folder, key, value)folder.updated_at = datetime.now(timezone.utc) # type: ignore[assignment]self.session.commit()@@ -120,6 +132,7 @@ class FolderManager:self, subscription_id: str, **kwargs) -> Optional[BaseSubscription]:"""Update a subscription."""+ update_data = normalize_compact_subscription_update(kwargs)sub = (self.session.query(BaseSubscription).filter_by(id=subscription_id)@@ -128,17 +141,16 @@ class FolderManager:if not sub:return None- for key, value in kwargs.items():- if hasattr(sub, key) and key not in ["id", "created_at"]:- setattr(sub, key, value)+ for key, value in update_data.items():+ setattr(sub, key, value)# Recalculate next_refresh if refresh_interval_minutes changed- if "refresh_interval_minutes" in kwargs:+ if "refresh_interval_minutes" in update_data:from datetime import timedeltafrom loguru import loggerold_next = sub.next_refresh- new_minutes = kwargs["refresh_interval_minutes"]+ new_minutes = update_data["refresh_interval_minutes"]if sub.last_refresh:sub.next_refresh = sub.last_refresh + timedelta( # type: ignore[assignment]diff --git a/src/local_deep_research/web/routers/news_flask_api.py b/src/local_deep_research/web/routers/news_flask_api.pyindex 1124b976b4..9943aeddc7 100644--- a/src/local_deep_research/web/routers/news_flask_api.py+++ b/src/local_deep_research/web/routers/news_flask_api.py@@ -22,6 +22,12 @@ from loguru import loggerfrom ...llm.providers.base import normalize_providerfrom ...news import api+from ...news.constants import (+ NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES,+ NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES,+ normalize_compact_subscription_update,+ normalize_folder_update,+)from ...news.exceptions import NewsAPIExceptionfrom ...news.folder_manager import FolderManagerfrom ...database.models import SubscriptionFolder@@ -47,8 +53,12 @@ NEWS_BATCH_FEEDBACK_MAX_CARD_IDS = NEWS_FEED_MAX_LIMIT# their request-boundary limits in one place so the create route and both# update routes cannot drift apart. One minute and one week are both offered# by the current UI, so those are the inclusive refresh bounds.-NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES = 1-NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES = 10_080+# NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES / MAX_REFRESH_MINUTES live in+# ``news/constants.py`` (imported above) since+# ``normalize_compact_subscription_update`` there needs the same bounds;+# re-exported here (rather than duplicated) so existing+# ``news_flask_api.NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES`` references keep+# working.NEWS_SUBSCRIPTION_MAX_QUERY_LENGTH = 10_000NEWS_SUBSCRIPTION_MAX_SEARCH_ITERATIONS = 20# The subscription form (news-subscription-form.html) advertises max="20"@@ -1760,14 +1770,42 @@ async def create_folder(async def update_folder(request: Request, folder_id, username: Annotated[str, Depends(require_auth)]):- """Update a folder"""+ """Update a folder.++ Restricted to an explicit allowlist (``name``, ``description``,+ ``color``, ``icon``, ``is_default``, ``sort_order``) via+ :func:`normalize_folder_update` -- ``FolderManager.update_folder`` used+ to run a blind ``hasattr``-gated ``setattr`` loop, which is true for+ SQLAlchemy internals (``_sa_instance_state``) and the bound ``to_dict``+ method too, not just real columns. Validate before dispatching to the+ DB thread so an invalid body never reaches the session.+ """data, _body_err = await read_json_dict(request, "simple", "Request body must be valid JSON")if _body_err is not None:return _body_err+ try:+ normalize_folder_update(data)+ except ValueError as error:+ return _subscription_validation_error(str(error))def _impl():+ # Defense in depth: normalize_folder_update already rejected+ # unsupported fields above (route level, before dispatch to this+ # DB thread), but FolderManager.update_folder validates again, so+ # any caller reaching it directly still gets the same 400 (named+ # field). Run that check here too, but BEFORE opening the DB+ # session/transaction below -- narrowly scoped to just this call+ # so it can never catch an unrelated ValueError raised by the+ # DB/ORM layer inside the ``with`` block and echo its message as+ # if it were a validation error (wrong status code, and a+ # potential internal-detail leak).+ try:+ normalize_folder_update(data)+ except ValueError as e:+ return _subscription_validation_error(str(e))+try:with get_user_db_session(username) as session:manager = FolderManager(session)@@ -1862,32 +1900,28 @@ async def update_subscription_folder(subscription_id,username: Annotated[str, Depends(require_auth)],):- """Update a subscription (mainly for folder assignment)"""+ """Update a subscription (mainly for folder assignment).++ Restricted to an explicit allowlist (``folder``, ``folder_id``,+ ``name``, ``notes``, ``refresh_interval_minutes``, ``is_active``,+ ``status``) via :func:`normalize_compact_subscription_update` -- the+ blind ``setattr`` loop this route used to run wrote any matching+ column, so a request body could reach protected or privileged columns+ (``custom_endpoint`` included, a third write path alongside+ create_subscription / update_subscription that #5603 could only+ SSRF-check rather than close). Reject unsupported fields at the+ boundary, before the sync helper's unredacted log line, so this route+ cannot persist anything its allowlisted siblings reject.+ """data, _body_err = await read_json_dict(request, "simple", "Request body must be valid JSON")if _body_err is not None:return _body_err- validation_error = _validate_subscription_payload(- data,- query_field="query_or_topic",- refresh_field="refresh_interval_minutes",- )- if validation_error is not None:- return validation_error- # ``_update_subscription_folder_sync``'s blind setattr loop writes any- # matching column, so ``custom_endpoint`` reaches storage here too -- a- # third write path alongside create_subscription / update_subscription.- # Validate it at the boundary, before the sync helper's unredacted log- # line, so this route cannot persist an SSRF endpoint its siblings- # reject. Ported from #5603, which closed the same gap on the Flask- # blueprint this router replaced.- if "custom_endpoint" in data:- bad_endpoint = await _reject_custom_endpoint_async(- data.get("custom_endpoint")- )- if bad_endpoint is not None:- return bad_endpoint+ try:+ normalize_compact_subscription_update(data)+ except ValueError as error:+ return _subscription_validation_error(str(error))return await run_db_sync(_update_subscription_folder_sync, data, subscription_id, username)@@ -1895,16 +1929,13 @@ async def update_subscription_folder(def _update_subscription_folder_sync(data, subscription_id, username):try:- validation_error = _validate_subscription_payload(- data,- query_field="query_or_topic",- refresh_field="refresh_interval_minutes",- )- if validation_error is not None:- return validation_error+ try:+ update_data = normalize_compact_subscription_update(data)+ except ValueError as error:+ return _subscription_validation_error(str(error))logger.info(- f"Updating subscription {subscription_id} with data: {data}"+ f"Updating subscription {subscription_id} with data: {update_data}")with get_user_db_session(username) as session:@@ -1924,32 +1955,19 @@ def _update_subscription_folder_sync(data, subscription_id, username):{"error": "Subscription not found"}, status_code=404)- # `status` is the single source of truth for active/paused (the- # scheduler keys on it, not the legacy is_active column). Translate- # an is_active toggle into status and keep both out of the blind- # setattr loop below -- otherwise a body like {"is_active": false}- # would flip only the legacy column while status stayed "active"- # and the scheduler would keep running the subscription. Mirrors- # api.update_subscription's translation.- if "is_active" in data:- sub.status = "active" if data["is_active"] else "paused"- if "status" in data:- sub.status = data["status"]-- # Update remaining fields- for key, value in data.items():- if hasattr(sub, key) and key not in [- "id",- "user_id",- "created_at",- "is_active",- "status",- ]:- setattr(sub, key, value)+ # `normalize_compact_subscription_update` already translated a+ # legacy `is_active` toggle into canonical `status` (with an+ # explicit `status` taking precedence) and restricted+ # `update_data` to the allowlisted fields -- no blind setattr+ # over the raw request body, so protected columns (id, user_id,+ # created_at, ...) and unrelated ones (custom_endpoint included)+ # can never be reached from this route.+ for key, value in update_data.items():+ setattr(sub, key, value)# Recalculate next_refresh if refresh_interval_minutes changed- if "refresh_interval_minutes" in data:- new_minutes = data["refresh_interval_minutes"]+ if "refresh_interval_minutes" in update_data:+ new_minutes = update_data["refresh_interval_minutes"]if sub.last_refresh:sub.next_refresh = sub.last_refresh + timedelta(minutes=new_minutesdiff --git a/tests/news/test_folder_manager.py b/tests/news/test_folder_manager.pyindex 3cea28330e..f5115c56cf 100644--- a/tests/news/test_folder_manager.py+++ b/tests/news/test_folder_manager.py@@ -12,6 +12,8 @@ Tests cover:from datetime import datetime, timezone, timedeltafrom unittest.mock import MagicMock, patch+import pytest+class TestFolderManagerInit:"""Tests for FolderManager initialization."""@@ -358,8 +360,8 @@ class TestUpdateSubscription:assert mock_sub.updated_at is not Noneassert before <= mock_sub.updated_at <= after- def test_update_does_not_modify_id(self):- """Test that update_subscription does not modify id."""+ def test_update_ignores_readonly_id(self):+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManagermock_session = MagicMock()@@ -373,12 +375,14 @@ class TestUpdateSubscription:manager = FolderManager(mock_session)- # Try to update id (should be ignored)+ original_value = mock_sub.idmanager.update_subscription("sub-123", id="new-id")+ assert mock_sub.id == original_valueassert mock_sub.id == "sub-123"+ mock_session.commit.assert_called_once_with()- def test_update_does_not_modify_created_at(self):+ def test_update_rejects_protected_created_at(self):"""Test that update_subscription does not modify created_at."""from local_deep_research.news.folder_manager import FolderManager@@ -395,11 +399,13 @@ class TestUpdateSubscription:manager = FolderManager(mock_session)- # Try to update created_at (should be ignored)new_created = datetime(2024, 6, 1, 0, 0, 0, tzinfo=timezone.utc)- manager.update_subscription("sub-123", created_at=new_created)+ with pytest.raises(ValueError):+ manager.update_subscription("sub-123", created_at=new_created)assert mock_sub.created_at == original_created+ mock_session.query.assert_not_called()+ mock_session.commit.assert_not_called()class TestGetSubscriptionStats:diff --git a/tests/news/test_folder_manager_behavior.py b/tests/news/test_folder_manager_behavior.pyindex 3dac326de6..e02fdc1da9 100644--- a/tests/news/test_folder_manager_behavior.py+++ b/tests/news/test_folder_manager_behavior.py@@ -6,6 +6,8 @@ Tests CRUD operations, subscription management, and serialization with mocked sefrom datetime import datetime, timezonefrom unittest.mock import Mock, MagicMock, PropertyMock+import pytest+from local_deep_research.news.folder_manager import FolderManager@@ -211,21 +213,49 @@ class TestUpdateFolder:assert result is not Nonesession.commit.assert_called_once()- def test_does_not_update_id(self):+ def test_ignores_readonly_id(self):+ """Accept response echoes without changing server-owned values."""session = _make_mock_session()folder = _make_mock_folder()session.get.return_value = folderfm = FolderManager(session)+ original_value = folder.idfm.update_folder("f-1", id="should-not-change")- # id is in the protected list, so setattr should not be called for it+ assert folder.id == original_value+ session.commit.assert_called_once_with()def test_does_not_update_created_at(self):+ """Accept response echoes without changing server-owned values."""session = _make_mock_session()folder = _make_mock_folder()session.get.return_value = folderfm = FolderManager(session)+ original_value = folder.created_atfm.update_folder("f-1", created_at="should-not-change")- # created_at is in the protected list+ assert folder.created_at == original_value+ session.commit.assert_called_once_with()++ def test_rejects_to_dict_field(self):+ """A body naming the bound ``to_dict`` method must raise, not+ overwrite the method or reach the session."""+ session = _make_mock_session()+ folder = _make_mock_folder()+ session.get.return_value = folder+ fm = FolderManager(session)+ with pytest.raises(ValueError, match="to_dict"):+ fm.update_folder("f-1", to_dict="x")+ session.commit.assert_not_called()++ def test_rejects_sa_instance_state_field(self):+ """A body naming ``_sa_instance_state`` must raise, not corrupt+ SQLAlchemy's ORM identity tracking."""+ session = _make_mock_session()+ folder = _make_mock_folder()+ session.get.return_value = folder+ fm = FolderManager(session)+ with pytest.raises(ValueError, match="_sa_instance_state"):+ fm.update_folder("f-1", _sa_instance_state=1)+ session.commit.assert_not_called()def test_sets_updated_at(self):session = _make_mock_session()@@ -337,8 +367,11 @@ class TestUpdateSubscription:sub)fm = FolderManager(session)+ original_value = sub.idfm.update_subscription("sub-1", id="should-not-change")- # id is protected+ assert sub.id == original_value++ session.commit.assert_called_once_with()def test_recalculates_next_refresh_on_interval_change(self):session = _make_mock_session()diff --git a/tests/news/test_folder_manager_comprehensive.py b/tests/news/test_folder_manager_comprehensive.pyindex 0e2eba6c6a..ddb2e60818 100644--- a/tests/news/test_folder_manager_comprehensive.py+++ b/tests/news/test_folder_manager_comprehensive.py@@ -7,6 +7,8 @@ from unittest.mock import Mockfrom datetime import datetime, timezone, timedeltaimport uuid+import pytest+class TestFolderManagerInit:"""Tests for FolderManager initialization."""@@ -182,7 +184,7 @@ class TestUpdateFolder:assert mock_folder.description == "New desc"def test_does_not_update_id(self):- """Test does not update folder ID."""+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManagermock_folder = Mock()@@ -191,13 +193,16 @@ class TestUpdateFolder:mock_session.get.return_value = mock_foldermanager = FolderManager(mock_session)+ original_value = mock_folder.idmanager.update_folder(1, id="new-id")+ assert mock_folder.id == original_value- # ID should not change+ # The echoed ID must never replace the stored identity.assert mock_folder.id == "original-id"+ mock_session.commit.assert_called_once_with()def test_does_not_update_created_at(self):- """Test does not update created_at."""+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManageroriginal_time = datetime(2023, 1, 1, tzinfo=timezone.utc)@@ -207,9 +212,58 @@ class TestUpdateFolder:mock_session.get.return_value = mock_foldermanager = FolderManager(mock_session)+ original_value = mock_folder.created_atmanager.update_folder(1, created_at=datetime.now(timezone.utc))+ assert mock_folder.created_at == original_valueassert mock_folder.created_at == original_time+ mock_session.commit.assert_called_once_with()++ def test_rejects_to_dict_field(self):+ """A body naming the bound ``to_dict`` method must 400, not+ overwrite the method or corrupt the ORM instance."""+ from local_deep_research.news.folder_manager import FolderManager++ mock_folder = Mock()+ mock_session = Mock()+ mock_session.get.return_value = mock_folder++ manager = FolderManager(mock_session)+ with pytest.raises(ValueError, match="to_dict"):+ manager.update_folder(1, to_dict="x")++ mock_session.commit.assert_not_called()++ def test_rejects_sa_instance_state_field(self):+ """A body naming ``_sa_instance_state`` must 400, not corrupt+ SQLAlchemy's ORM identity tracking for the instance."""+ from local_deep_research.news.folder_manager import FolderManager++ mock_folder = Mock()+ mock_session = Mock()+ mock_session.get.return_value = mock_folder++ manager = FolderManager(mock_session)+ with pytest.raises(ValueError, match="_sa_instance_state"):+ manager.update_folder(1, _sa_instance_state=1)++ mock_session.commit.assert_not_called()++ def test_allowlisted_field_still_updates(self):+ """The allowlist narrows the method, it does not break it."""+ from local_deep_research.news.folder_manager import FolderManager++ mock_folder = Mock()+ mock_folder.color = "#000000"+ mock_session = Mock()+ mock_session.get.return_value = mock_folder++ manager = FolderManager(mock_session)+ result = manager.update_folder(1, color="#ffffff")++ assert result is mock_folder+ assert mock_folder.color == "#ffffff"+ mock_session.commit.assert_called_once()def test_updates_updated_at(self):"""Test updates updated_at timestamp."""@@ -402,7 +456,7 @@ class TestUpdateSubscription:mock_session.query().filter_by().first.return_value = Nonemanager = FolderManager(mock_session)- result = manager.update_subscription("sub-123", name="New Name")+ result = manager.update_subscription("sub-123", status="active")assert result is None@@ -420,19 +474,24 @@ class TestUpdateSubscription:assert mock_sub.folder == "New Folder"- def test_does_not_update_id(self):- """Test does not update subscription ID."""+ def test_ignores_readonly_id(self):+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManagermock_sub = Mock()mock_sub.id = "original-id"mock_session = Mock()- mock_session.query().filter_by().first.return_value = mock_sub+ mock_query = Mock()+ mock_query.filter_by.return_value.first.return_value = mock_sub+ mock_session.query.return_value = mock_querymanager = FolderManager(mock_session)+ original_value = mock_sub.idmanager.update_subscription("sub-123", id="new-id")+ assert mock_sub.id == original_valueassert mock_sub.id == "original-id"+ mock_session.commit.assert_called_once_with()def test_recalculates_next_refresh(self):"""Test recalculates next_refresh when interval changes."""diff --git a/tests/news/test_folder_manager_extended.py b/tests/news/test_folder_manager_extended.pyindex 35cc0ec90c..88b6c29117 100644--- a/tests/news/test_folder_manager_extended.py+++ b/tests/news/test_folder_manager_extended.py@@ -18,6 +18,8 @@ Tests cover:from unittest.mock import MagicMockfrom datetime import datetime, timezone, timedelta+import pytest+class TestFolderManagerInit:"""Tests for FolderManager initialization."""@@ -162,7 +164,7 @@ class TestUpdateFolder:assert result is Nonedef test_update_does_not_modify_id(self):- """Does not modify folder id."""+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManagermock_session = MagicMock()@@ -171,12 +173,15 @@ class TestUpdateFolder:mock_session.get.return_value = mock_foldermanager = FolderManager(mock_session)+ original_value = mock_folder.idmanager.update_folder(1, id=999)+ assert mock_folder.id == original_valueassert mock_folder.id == 1+ mock_session.commit.assert_called_once_with()def test_update_does_not_modify_created_at(self):- """Does not modify created_at."""+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManagermock_session = MagicMock()@@ -187,9 +192,42 @@ class TestUpdateFolder:manager = FolderManager(mock_session)new_created = datetime(2024, 6, 1, tzinfo=timezone.utc)+ original_value = mock_folder.created_atmanager.update_folder(1, created_at=new_created)+ assert mock_folder.created_at == original_valueassert mock_folder.created_at == original_created+ mock_session.commit.assert_called_once_with()++ def test_update_rejects_to_dict_field(self):+ """A body naming the bound ``to_dict`` method must raise, not+ overwrite the method or reach the session."""+ from local_deep_research.news.folder_manager import FolderManager++ mock_session = MagicMock()+ mock_folder = MagicMock()+ mock_session.get.return_value = mock_folder++ manager = FolderManager(mock_session)+ with pytest.raises(ValueError, match="to_dict"):+ manager.update_folder(1, to_dict="x")++ mock_session.commit.assert_not_called()++ def test_update_rejects_sa_instance_state_field(self):+ """A body naming ``_sa_instance_state`` must raise, not corrupt+ SQLAlchemy's ORM identity tracking."""+ from local_deep_research.news.folder_manager import FolderManager++ mock_session = MagicMock()+ mock_folder = MagicMock()+ mock_session.get.return_value = mock_folder++ manager = FolderManager(mock_session)+ with pytest.raises(ValueError, match="_sa_instance_state"):+ manager.update_folder(1, _sa_instance_state=1)++ mock_session.commit.assert_not_called()def test_update_multiple_fields(self):"""Updates multiple fields at once."""@@ -346,8 +384,7 @@ class TestGetSubscriptionsByFolder:class TestUpdateSubscriptionExtended:"""Extended tests for update_subscription method."""- def test_update_changes_query_or_topic(self):- """Updates query_or_topic field."""+ def test_update_rejects_query_or_topic(self):from local_deep_research.news.folder_manager import FolderManagermock_session = MagicMock()@@ -358,12 +395,12 @@ class TestUpdateSubscriptionExtended:mock_session.query.return_value.filter_by.return_value.first.return_value = mock_submanager = FolderManager(mock_session)- result = manager.update_subscription(- "sub-123", query_or_topic="New Query"- )+ with pytest.raises(ValueError):+ manager.update_subscription("sub-123", query_or_topic="New Query")- assert mock_sub.query_or_topic == "New Query"- assert result == mock_sub+ assert mock_sub.query_or_topic == "Old Query"+ mock_session.query.assert_not_called()+ mock_session.commit.assert_not_called()def test_update_changes_folder(self):"""Updates folder field."""@@ -657,21 +694,17 @@ class TestFolderManagerEdgeCases:assert result is mock_foldermock_session.commit.assert_called_once()- def test_subscription_with_zero_interval(self):- """Handles subscription with zero refresh interval."""+ def test_update_rejects_zero_interval_before_database_access(self):from local_deep_research.news.folder_manager import FolderManagermock_session = MagicMock()- mock_sub = MagicMock()- mock_sub.last_refresh = datetime.now(timezone.utc)- mock_sub.updated_at = None- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_sub-manager = FolderManager(mock_session)- manager.update_subscription("sub-123", refresh_interval_minutes=0)- # next_refresh should be same as last_refresh (0 minutes later)- assert mock_sub.next_refresh is not None+ with pytest.raises(ValueError, match="refresh_interval_minutes"):+ manager.update_subscription("sub-123", refresh_interval_minutes=0)++ mock_session.query.assert_not_called()+ mock_session.commit.assert_not_called()def test_stats_with_no_subscriptions(self):"""Returns zeros when no subscriptions exist."""diff --git a/tests/news/test_folder_manager_news_extended.py b/tests/news/test_folder_manager_news_extended.pyindex 414fb41d1d..e0e3afa786 100644--- a/tests/news/test_folder_manager_news_extended.py+++ b/tests/news/test_folder_manager_news_extended.py@@ -182,7 +182,7 @@ class TestUpdateFolder:assert result is Nonedef test_ignores_id_field(self, mock_session):- """Ignores id field in updates."""+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManagermock_folder = Mock()@@ -191,13 +191,16 @@ class TestUpdateFolder:mock_session.commit = Mock()manager = FolderManager(mock_session)+ original_value = mock_folder.idmanager.update_folder(1, id=999)+ assert mock_folder.id == original_value# ID should not changeassert mock_folder.id == 1+ mock_session.commit.assert_called_once_with()def test_ignores_created_at_field(self, mock_session):- """Ignores created_at field in updates."""+ """Accept response echoes without changing server-owned values."""from local_deep_research.news.folder_manager import FolderManageroriginal_created = datetime.now(timezone.utc)@@ -208,10 +211,43 @@ class TestUpdateFolder:manager = FolderManager(mock_session)new_created = datetime.now(timezone.utc) - timedelta(days=1)+ original_value = mock_folder.created_atmanager.update_folder(1, created_at=new_created)+ assert mock_folder.created_at == original_value# created_at should not changeassert mock_folder.created_at == original_created+ mock_session.commit.assert_called_once_with()++ def test_rejects_to_dict_field(self, mock_session):+ """A body naming the bound ``to_dict`` method must raise, not+ overwrite the method or reach the session."""+ from local_deep_research.news.folder_manager import FolderManager++ mock_folder = Mock()+ mock_session.get.return_value = mock_folder+ mock_session.commit = Mock()++ manager = FolderManager(mock_session)+ with pytest.raises(ValueError, match="to_dict"):+ manager.update_folder(1, to_dict="x")++ mock_session.commit.assert_not_called()++ def test_rejects_sa_instance_state_field(self, mock_session):+ """A body naming ``_sa_instance_state`` must raise, not corrupt+ SQLAlchemy's ORM identity tracking."""+ from local_deep_research.news.folder_manager import FolderManager++ mock_folder = Mock()+ mock_session.get.return_value = mock_folder+ mock_session.commit = Mock()++ manager = FolderManager(mock_session)+ with pytest.raises(ValueError, match="_sa_instance_state"):+ manager.update_folder(1, _sa_instance_state=1)++ mock_session.commit.assert_not_called()def test_updates_updated_at(self, mock_session):"""Updates updated_at timestamp."""@@ -346,15 +382,15 @@ class TestUpdateSubscription:from local_deep_research.news.folder_manager import FolderManagermock_sub = Mock()- mock_sub.name = "Old Name"+ mock_sub.folder = "Old Folder"mock_session.query.return_value.filter_by.return_value.first.return_value = mock_submock_session.commit = Mock()manager = FolderManager(mock_session)- result = manager.update_subscription("sub-1", name="New Name")+ result = manager.update_subscription("sub-1", folder="New Folder")assert result is mock_sub- assert mock_sub.name == "New Name"+ assert mock_sub.folder == "New Folder"def test_returns_none_for_nonexistent(self, mock_session):"""Returns None for nonexistent subscription."""@@ -363,7 +399,7 @@ class TestUpdateSubscription:mock_session.query.return_value.filter_by.return_value.first.return_value = Nonemanager = FolderManager(mock_session)- result = manager.update_subscription("nonexistent", name="New")+ result = manager.update_subscription("nonexistent", status="active")assert result is None@@ -395,7 +431,7 @@ class TestUpdateSubscription:mock_session.commit = Mock()manager = FolderManager(mock_session)- manager.update_subscription("sub-1", name="New")+ manager.update_subscription("sub-1", folder="New Folder")assert mock_sub.updated_at is not Nonediff --git a/tests/news/test_news_run_subscription_ported.py b/tests/news/test_news_run_subscription_ported.pyindex e4dc1a8ced..ae2862526a 100644--- a/tests/news/test_news_run_subscription_ported.py+++ b/tests/news/test_news_run_subscription_ported.py@@ -30,6 +30,11 @@ from unittest.mock import MagicMock, patchimport pytest+from local_deep_research.news.constants import (+ COMPACT_SUBSCRIPTION_INPUT_FIELDS,+ COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS,+ COMPACT_SUBSCRIPTION_RESPONSE_FIELDS,+)from local_deep_research.web.routers import news_flask_apiSESSION_CONTEXT = "local_deep_research.database.session_context"@@ -42,112 +47,81 @@ USERNAME = "alice"SUB_ID = "sub-1"NEXT_REFRESH = datetime(2026, 8, 25, tzinfo=timezone.utc)-LEGACY_REFRESH_ERROR = (- "refresh_interval_minutes must be an integer between "- f"{news_flask_api.NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES} and "- f"{news_flask_api.NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES}"-)-LEGACY_ITERATIONS_ERROR = (- "search_iterations must be an integer between 1 and "- f"{news_flask_api.NEWS_SUBSCRIPTION_MAX_SEARCH_ITERATIONS}"-)-LEGACY_QUESTIONS_ERROR = (- "questions_per_iteration must be an integer between 1 and "- f"{news_flask_api.NEWS_SUBSCRIPTION_MAX_QUESTIONS_PER_ITERATION}"-)--LEGACY_INVALID_SUBSCRIPTION_PAYLOADS = [- pytest.param(- {"query_or_topic": {}}, "query must be a string", id="query-object"- ),- pytest.param(- {"query_or_topic": " "}, "query is required", id="query-blank"- ),+# ``PUT /news/api/subscription/subscriptions/{id}`` -- the "compact" update+# route -- used to run a blind ``setattr`` loop over the whole request body,+# so it accepted every field the *other* update route+# (``PUT /subscriptions/{id}``) accepts (query_or_topic, name,+# model_provider, search_iterations, ...), protected columns (id, user_id,+# created_at), and custom_endpoint -- which it merely SSRF-checked rather+# than reject. It is now restricted to an explicit allowlist (folder,+# folder_id, name, notes, refresh_interval_minutes, is_active, status) via+# ``normalize_compact_subscription_update``. Read-only fields echoed in the+# route's own PUT response (id, next_refresh, last_refresh) are accepted+# but never written, so a client can PUT that response back unchanged.+# Other unsupported fields are rejected before database access; writable+# fields retain type/range checks.+COMPACT_UPDATE_REJECTED_PAYLOADS = [+ *[+ pytest.param(+ {field: value},+ f"Unsupported subscription update fields: {field}",+ id=f"unsupported-{field}",+ )+ for field, value in (+ ("query_or_topic", "new topic"),+ ("model_provider", "OPENAI"),+ ("search_iterations", 5),+ ("questions_per_iteration", 5),+ # Previously reached storage via the blind setattr loop and was+ # only SSRF-checked (#5603), not rejected outright.+ ("custom_endpoint", "http://169.254.169.254/latest/meta-data/"),+ ("user_id", "mallory"),+ ("created_at", "1999-01-01"),+ )+ ],pytest.param(- {- "query_or_topic": "q"- * (news_flask_api.NEWS_SUBSCRIPTION_MAX_QUERY_LENGTH + 1)- },- "query exceeds maximum length of "- f"{news_flask_api.NEWS_SUBSCRIPTION_MAX_QUERY_LENGTH} characters",- id="query-over-limit",+ {"folder_id": "f1", "user_id": "mallory"},+ "Unsupported subscription update fields: user_id",+ id="mixed-allowed-and-unsupported",),pytest.param(- {"name": {}}, "name must be a string or null", id="name-object"+ {"status": "expired"},+ "status must be 'active' or 'paused'",+ id="status-invalid-value",),pytest.param(- {"folder_id": {}},- "folder_id must be a string or null",- id="folder-object",+ {"status": 1},+ "status must be 'active' or 'paused'",+ id="status-wrong-type",),- *[- pytest.param(- {"model_provider": value},- "model_provider must be a string or null",- id=f"model-provider-{label}",- )- for label, value in (- ("int", 1),- ("bool", True),- ("list", []),- ("object", {}),- )- ],*[pytest.param({"refresh_interval_minutes": value},- LEGACY_REFRESH_ERROR,+ "refresh_interval_minutes must be an integer between 1 and 10080",id=f"refresh-{label}",)for label, value in (("zero", 0),("negative", -1),- (- "over-limit",- news_flask_api.NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES + 1,- ),+ ("over-limit", 10081),("string", "60"),- ("float", 60.0),("bool", True),("null", None),- ("huge", 2**63),)],*[pytest.param(- {"search_iterations": value},- LEGACY_ITERATIONS_ERROR,- id=f"iterations-{label}",- )- for label, value in (- ("zero", 0),- (- "over-limit",- news_flask_api.NEWS_SUBSCRIPTION_MAX_SEARCH_ITERATIONS + 1,- ),- ("string", "2"),- ("bool", True),- ("null", None),- )- ],- *[- pytest.param(- {"questions_per_iteration": value},- LEGACY_QUESTIONS_ERROR,- id=f"questions-{label}",- )- for label, value in (- ("zero", 0),- (- "over-limit",- news_flask_api.NEWS_SUBSCRIPTION_MAX_QUESTIONS_PER_ITERATION- + 1,- ),- ("string", "2"),- ("bool", True),- ("null", None),+ {field: 123},+ f"{field} must be a string or null",+ id=f"{field}-wrong-type",)+ for field in ("folder", "folder_id", "name", "notes")],+ pytest.param(+ {"name": "x" * 256},+ "name exceeds maximum length of 255 characters",+ id="name-too-long",+ ),]@@ -532,10 +506,8 @@ class TestSubscriptionFolderUpdate:assert _body(result) == {"error": "is_active must be a boolean"}session.query.assert_not_called()- @pytest.mark.parametrize(- "data,message", LEGACY_INVALID_SUBSCRIPTION_PAYLOADS- )- def test_invalid_shared_fields_are_rejected_before_database_access(+ @pytest.mark.parametrize("data,message", COMPACT_UPDATE_REJECTED_PAYLOADS)+ def test_unsupported_or_invalid_fields_are_rejected_before_database_access(self, data, message):result, session = _folder_update(data)@@ -544,18 +516,14 @@ class TestSubscriptionFolderUpdate:assert _body(result) == {"error": message}session.query.assert_not_called()- @pytest.mark.parametrize(- "data,message", LEGACY_INVALID_SUBSCRIPTION_PAYLOADS- )+ @pytest.mark.parametrize("data,message", COMPACT_UPDATE_REJECTED_PAYLOADS)def test_async_route_rejects_before_endpoint_resolution_or_offload(self, data, message):- with (- patch.object(- news_flask_api, "_reject_custom_endpoint_async"- ) as endpoint_check,- patch.object(news_flask_api, "run_db_sync") as offload,- ):+ # ``_reject_custom_endpoint_async`` is no longer wired into this+ # route at all -- ``custom_endpoint`` is now rejected outright as an+ # unsupported field, so there is nothing left to SSRF-check here.+ with patch.object(news_flask_api, "run_db_sync") as offload:result = asyncio.run(news_flask_api.update_subscription_folder(request=_JsonRequest(data),@@ -566,35 +534,22 @@ class TestSubscriptionFolderUpdate:assert result.status_code == 400assert _body(result) == {"error": message}- endpoint_check.assert_not_awaited()offload.assert_not_called()@pytest.mark.parametrize("data",[+ # search_iterations / questions_per_iteration are not part of+ # the compact allowlist (they stay on the full+ # ``PUT /subscriptions/{id}`` route) -- only+ # refresh_interval_minutes is exercised here.pytest.param(- {- "refresh_interval_minutes": (- news_flask_api.NEWS_SUBSCRIPTION_MIN_REFRESH_MINUTES- ),- "search_iterations": 1,- "questions_per_iteration": 1,- },- id="minimums",+ {"refresh_interval_minutes": 1},+ id="minimum",),pytest.param(- {- "refresh_interval_minutes": (- news_flask_api.NEWS_SUBSCRIPTION_MAX_REFRESH_MINUTES- ),- "search_iterations": (- news_flask_api.NEWS_SUBSCRIPTION_MAX_SEARCH_ITERATIONS- ),- "questions_per_iteration": (- news_flask_api.NEWS_SUBSCRIPTION_MAX_QUESTIONS_PER_ITERATION- ),- },- id="maximums",+ {"refresh_interval_minutes": 10080},+ id="maximum",),],)@@ -630,14 +585,119 @@ class TestSubscriptionFolderUpdate:assert result["folder_id"] == "folder-9"assert result["is_active"] is True- def test_protected_columns_are_never_overwritten(self):- """``id``/``user_id``/``created_at`` are excluded from the blind- ``setattr`` loop: a body carrying them must not reassign the row."""+ def test_response_key_set_matches_the_hand_kept_constant(self):+ """``COMPACT_SUBSCRIPTION_RESPONSE_FIELDS`` (news/constants.py) is+ hand-kept in sync with the response dict literal in+ ``_update_subscription_folder_sync`` -- ``NewsSubscription`` has no+ ``to_dict()`` to introspect. Pin the two together here so a field+ added to one and not the other is caught instead of silently+ drifting (news/constants.py:28-36)."""+ sub = _sub_row()+ result, _ = _folder_update({"folder_id": "folder-9"}, sub)++ assert set(result) == COMPACT_SUBSCRIPTION_RESPONSE_FIELDS++ def test_input_fields_are_disjoint_from_the_readonly_echo_set(self):+ """A field cannot be simultaneously writable and merely-tolerated:+ ``COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS`` is derived as+ ``COMPACT_SUBSCRIPTION_RESPONSE_FIELDS -+ COMPACT_SUBSCRIPTION_INPUT_FIELDS`` in news/constants.py, which+ guarantees this by construction -- pinned here so a future edit+ that hardcodes the echo set instead of deriving it cannot silently+ reintroduce an overlap."""+ assert COMPACT_SUBSCRIPTION_INPUT_FIELDS.isdisjoint(+ COMPACT_SUBSCRIPTION_READONLY_ECHO_FIELDS+ )++ @pytest.mark.parametrize(+ "echoed",+ [+ {"id": "hijacked"},+ {"next_refresh": "1999-01-01T00:00:00+00:00"},+ {"last_refresh": "1999-01-01T00:00:00+00:00"},+ {+ "id": "hijacked",+ "next_refresh": "1999-01-01T00:00:00+00:00",+ "last_refresh": "1999-01-01T00:00:00+00:00",+ },+ ],+ ids=["id", "next-refresh", "last-refresh", "all-echoes"],+ )+ def test_readonly_response_fields_are_ignored_without_blocking_updates(+ self, echoed+ ):+ """``id``/``next_refresh``/``last_refresh`` are the route's own PUT+ response fields it never writes -- unlike ``name``, which the full+ ``PUT /subscriptions/{id}`` route's ``field_mapping`` has always let+ a caller set, so this route treats it as an ordinary writable+ field, not a read-only echo (covered separately below)."""+ sub = _sub_row()+ original = {+ "id": sub.id,+ "next_refresh": sub.next_refresh,+ "last_refresh": sub.last_refresh,+ }+ data = {**echoed, "folder_id": "folder-9"}++ # Drive the async boundary and the real sync implementation together:+ # neither may reject response echoes, and neither may persist them.+ async def run_sync(function, payload, subscription_id, username):+ assert function is news_flask_api._update_subscription_folder_sync+ assert subscription_id == SUB_ID+ assert username == USERNAME+ result, session = _folder_update(payload, sub)+ session.commit.assert_called_once_with()+ return result++ with patch.object(news_flask_api, "run_db_sync", side_effect=run_sync):+ result = asyncio.run(+ news_flask_api.update_subscription_folder(+ request=_JsonRequest(data),+ subscription_id=SUB_ID,+ username=USERNAME,+ )+ )++ assert sub.folder_id == "folder-9"+ assert result["folder_id"] == "folder-9"+ for field, value in original.items():+ assert getattr(sub, field) == value+ assert result[field] == value+ assert data == {**echoed, "folder_id": "folder-9"}++ def test_a_rename_through_the_compact_route_is_written(self):+ """``name`` is on the compact route's allowlist (unlike ``id``/+ ``next_refresh``/``last_refresh`` above): a body naming it along+ with another writable field writes both, matching the full+ ``PUT /subscriptions/{id}`` route's ``field_mapping`` behaviour."""+ sub = _sub_row()++ async def run_sync(function, payload, subscription_id, username):+ result, session = _folder_update(payload, sub)+ session.commit.assert_called_once_with()+ return result++ with patch.object(news_flask_api, "run_db_sync", side_effect=run_sync):+ result = asyncio.run(+ news_flask_api.update_subscription_folder(+ request=_JsonRequest({"name": "Renamed", "folder": "A"}),+ subscription_id=SUB_ID,+ username=USERNAME,+ )+ )++ assert sub.name == "Renamed"+ assert sub.folder == "A"+ assert result["name"] == "Renamed"++ def test_protected_columns_reject_the_whole_update_without_mutation(self):+ """Unsupported user_id/created_at reject the whole body, including+ allowed folder_id and the otherwise tolerated read-only id echo."""sub = _sub_row()sub.user_id = "alice"sub.created_at = "2020-01-01"- _folder_update(+ result, session = _folder_update({"id": "hijacked","user_id": "mallory",@@ -647,10 +707,12 @@ class TestSubscriptionFolderUpdate:sub,)+ assert result.status_code == 400assert sub.id == SUB_IDassert sub.user_id == "alice"assert sub.created_at == "2020-01-01"- assert sub.folder_id == "f1"+ assert sub.folder_id is None+ session.query.assert_not_called()def test_an_absent_subscription_is_a_404(self):result, _ = _folder_update({"folder_id": "f1"}, None)diff --git a/tests/security/test_news_router_ssrf.py b/tests/security/test_news_router_ssrf.pyindex dbbe5cb851..719483a8c2 100644--- a/tests/security/test_news_router_ssrf.py+++ b/tests/security/test_news_router_ssrf.py@@ -279,11 +279,18 @@ class TestUpdateSubscriptionRouteRejectsSSRF:class TestUpdateSubscriptionFolderRouteRejectsSSRF:"""PUT /news/api/subscription/subscriptions/<id> is the third write path.- Unlike the other two it persists through a blind ``setattr`` loop- straight to a DB session rather than through the ``news.api`` module, so- it is stubbed at ``get_user_db_session`` instead of the ``api`` mock. It- is also the one the FastAPI port dropped and the merge had to restore:- deleting its guard call leaves every other test in this file green.+ Unlike the other two it persists through a ``setattr`` loop straight to a+ DB session rather than through the ``news.api`` module, so it is stubbed+ at ``get_user_db_session`` instead of the ``api`` mock. It is also the+ one the FastAPI port dropped and the merge had to restore: deleting its+ guard call leaves every other test in this file green.++ Its guard is no longer the SSRF check the other two write paths use --+ ``normalize_compact_subscription_update`` restricts this route to an+ explicit field allowlist (``folder``, ``folder_id``, ``notes``,+ ``refresh_interval_minutes``, ``is_active``, ``status``), so+ ``custom_endpoint`` is rejected as an unsupported field before+ ``_reject_custom_endpoint`` ever runs."""@staticmethod@@ -310,12 +317,44 @@ class TestUpdateSubscriptionFolderRouteRejectsSSRF:assert response.status_code == 400, ("PUT /news/api/subscription/subscriptions/<id> accepted a "- f"metadata URL (HTTP {response.status_code}) through the "- "folder-update route's blind setattr loop"+ f"metadata URL (HTTP {response.status_code}) -- custom_endpoint "+ "must be rejected on this route (now as an unsupported field, "+ "before it could ever reach an SSRF check)")live.db_session.assert_not_called()- def test_ollama_endpoint_is_not_rejected(self, live):+ def test_custom_endpoint_is_rejected_as_unsupported_field(self, live):+ """custom_endpoint is not on this route's allowlist at all.++ This used to send a *valid* local-LLM endpoint and assert the SSRF+ guard let it through, the way ``update_subscription`` still does.+ This route now enforces an explicit field allowlist (``folder``,+ ``folder_id``, ``notes``, ``refresh_interval_minutes``,+ ``is_active``, ``status``) via+ ``normalize_compact_subscription_update``, so even a valid endpoint+ never reaches the SSRF check -- it 400s as an unsupported field+ instead. That is a stronger guarantee than the old SSRF check: the+ field can never be written through this route, safe or not.+ """+ live.db_session.reset_mock()+ response = live.client.put(+ f"/news/api/subscription/subscriptions/{A_UUID}",+ json={"custom_endpoint": "http://localhost:11434/v1"},+ follow_redirects=False,+ )++ assert response.status_code == 400+ assert "custom_endpoint" in response.json()["error"]+ live.db_session.assert_not_called()++ def test_allowlisted_field_is_still_accepted(self, live):+ """The allowlist narrows the route, it does not break it.++ A field the allowlist does carry (``folder``) must still reach the+ DB session, so the rejection above is proven to be about+ ``custom_endpoint`` specifically and not the route 400ing on+ everything.+ """sub = self._stub_subscription()mock_session = MagicMock()mock_session.query.return_value.filter_by.return_value.first.return_value = sub@@ -324,14 +363,149 @@ class TestUpdateSubscriptionFolderRouteRejectsSSRF:response = live.client.put(f"/news/api/subscription/subscriptions/{A_UUID}",- json={"custom_endpoint": "http://localhost:11434/v1"},+ json={"folder": "AI News"},follow_redirects=False,)- assert response.status_code != 400+ assert response.status_code == 200, (+ f"PUT /news/api/subscription/subscriptions/<id> rejected an "+ f"allowlisted field (HTTP {response.status_code}) -- "+ f"{response.text[:200]}"+ )live.db_session.assert_called_once()+class TestUpdateFolderRouteRejectsMassAssignment:+ """PUT /news/api/subscription/folders/<id> -- the folder-update sibling+ of ``update_subscription_folder`` above.++ ``FolderManager.update_folder`` used to run a blind ``setattr`` loop+ gated only by ``hasattr(folder, key)`` on the live SQLAlchemy instance.+ That is true for real columns, but also for ORM internals+ (``_sa_instance_state``) and the bound ``to_dict`` method, so a request+ body naming either one corrupted the instance or broke the route's own+ ``folder.to_dict()`` call on the same request (500, not a clean 400).+ ``normalize_folder_update`` closes this the same way+ ``normalize_compact_subscription_update`` closed the subscription+ route's equivalent hole: an explicit field allowlist checked before the+ DB session is ever opened.+ """++ def test_to_dict_field_is_rejected_as_unsupported(self, live):+ live.db_session.reset_mock()+ response = live.client.put(+ "/news/api/subscription/folders/folder-1",+ json={"to_dict": "x"},+ follow_redirects=False,+ )++ assert response.status_code == 400, (+ "PUT /news/api/subscription/folders/<id> accepted a body "+ f"naming to_dict (HTTP {response.status_code}) -- this used to "+ "shadow the bound to_dict method on the instance and 500 the "+ "route's own folder.to_dict() call"+ )+ assert "to_dict" in response.json()["error"]+ live.db_session.assert_not_called()++ def test_sa_instance_state_field_is_rejected_as_unsupported(self, live):+ live.db_session.reset_mock()+ response = live.client.put(+ "/news/api/subscription/folders/folder-1",+ json={"_sa_instance_state": 1},+ follow_redirects=False,+ )++ assert response.status_code == 400, (+ "PUT /news/api/subscription/folders/<id> accepted a body "+ f"naming _sa_instance_state (HTTP {response.status_code}) -- "+ "this used to corrupt SQLAlchemy's ORM identity tracking for "+ "the instance"+ )+ assert "_sa_instance_state" in response.json()["error"]+ live.db_session.assert_not_called()++ def test_allowlisted_field_is_still_accepted(self, live):+ """The allowlist narrows the route, it does not break it.++ A field the allowlist does carry (``color``) must still reach the+ DB session, so the rejections above are proven to be about the+ specific unsupported fields and not the route 400ing on everything.+ """+ folder = SimpleNamespace(+ id="folder-1",+ name="Test Folder",+ description=None,+ color="#000000",+ icon=None,+ is_default=False,+ sort_order=0,+ created_at=None,+ updated_at=None,+ to_dict=lambda: {"id": "folder-1", "color": "#ffffff"},+ )+ mock_session = MagicMock()+ mock_session.get.return_value = folder+ live.db_session.reset_mock()+ live.db_session.return_value.__enter__.return_value = mock_session++ response = live.client.put(+ "/news/api/subscription/folders/folder-1",+ json={"color": "#ffffff"},+ follow_redirects=False,+ )++ assert response.status_code == 200, (+ f"PUT /news/api/subscription/folders/<id> rejected an "+ f"allowlisted field (HTTP {response.status_code}) -- "+ f"{response.text[:200]}"+ )+ live.db_session.assert_called_once()++ @pytest.mark.parametrize(+ "field,value",+ [+ ("name", 123),+ ("name", None),+ ("description", 123),+ ("color", 123),+ ("icon", 123),+ ("is_default", "not-a-bool"),+ ("is_default", 1),+ ("sort_order", "abc"),+ ("sort_order", True),+ ("sort_order", 1.5),+ ],+ )+ def test_wrong_typed_field_is_rejected_with_400(self, live, field, value):+ """Field-name allowlisting alone is not enough: a wrong-typed value+ for an allowlisted field used to reach ``FolderManager.update_folder``'s+ blind ``setattr``/``session.commit()`` unchecked -- an opaque 500,+ or a silently miscoerced value thanks to SQLite's dynamic column+ typing. ``normalize_folder_update`` must reject it with a clean 400+ naming the field before the DB session is ever opened, the same+ contract as the field-name checks above.++ ``is_default=1`` and ``sort_order=True`` cover a bool masquerading+ as an int/not-quite-bool -- ``type(x) is`` (not ``isinstance``)+ checks must not accidentally accept these.+ """+ live.db_session.reset_mock()+ response = live.client.put(+ "/news/api/subscription/folders/folder-1",+ json={field: value},+ follow_redirects=False,+ )++ assert response.status_code == 400, (+ f"PUT /news/api/subscription/folders/<id> accepted "+ f"{field}={value!r} (HTTP {response.status_code}) instead of "+ "rejecting the wrong type before the session was opened"+ )+ assert field in response.json()["error"]+ live.db_session.assert_not_called()++class TestFeedRouteValidatesSubscriptionId:"""GET /news/api/feed takes subscription_id from the query string."""diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.pyindex ffcd8bb64e..0eae834484 100644--- a/tests/web/test_route_table_parity.py+++ b/tests/web/test_route_table_parity.py@@ -1725,6 +1725,17 @@ EXPECTED_STATUS_CODES_GAINED = {("POST", "/settings/api/search-favorites/toggle"): [403],("POST", "/settings/save_all_settings"): [403],("PUT", "/settings/api/search-favorites"): [403],+ # Mass-assignment fix: FolderManager.update_folder used to run a blind+ # hasattr-gated setattr loop (accepting any field name, including+ # SQLAlchemy internals). normalize_folder_update now allowlists+ # updatable fields and type-validates each one before dispatch, 400ing+ # a genuinely unexpected field name or a wrong-typed value instead of+ # silently ignoring/misapplying it. The allowlisted id/created_at/+ # updated_at read-modify-write echo (folder.to_dict()'s own output) is+ # tolerated, not rejected -- this 400 is still reachable via any other+ # unknown field or a type error (e.g. sort_order not an int).+ # news_flask_api.py:update_folder, news/constants.py:normalize_folder_update.+ ("PUT", "/news/api/subscription/folders/{}"): [400],}# Routes whose Flask handler put an `error` key in a JSON body and whose