You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/08/09 15:55:13 UTC
(superset) 03/03: fix(security): invalidate sessions on password reset; sync user Subject atomically
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch fix-account-session-hardening
in repository https://gitbox.apache.org/repos/asf/superset.git
commit e44d5d4f75768b93cdfc9a34ac9f310d9397955e
Author: Amin Ghadersohi <am...@gmail.com>
AuthorDate: Sun Aug 9 08:36:18 2026 -0700
fix(security): invalidate sessions on password reset; sync user Subject atomically
SupersetSecurityManager.reset_password (used by both the self-service and
admin-initiated reset flows) now stamps the session-invalidation epoch for
the target user after the password is reset, so outstanding sessions for
the account stop working. SupersetUserApi gains a terminate_sessions
action (DELETE /api/v1/security/users/<pk>/sessions, gated the same way as
the existing put action) so an admin can end a specific user's sessions
directly, without disabling the account.
SupersetUserApi.post/put also used to commit the FAB user write, then sync
the corresponding Subject row in a second, separate commit -- so a failure
in that second commit left an orphaned user with no matching Subject row.
The sync now happens in pre_add/pre_update, which FAB calls before the
commit that datamodel.add/edit issues, so both writes ride the same
transaction and roll back together on failure.
Co-Authored-By: Claude Sonnet 5 <no...@anthropic.com>
---
superset/security/manager.py | 106 ++++++--
.../test_password_change_session_invalidation.py | 108 +++++++--
.../test_superset_user_api_subject_sync.py | 269 +++++++++++++--------
3 files changed, 335 insertions(+), 148 deletions(-)
diff --git a/superset/security/manager.py b/superset/security/manager.py
index 5dc044d4a89..99dd62f923c 100644
--- a/superset/security/manager.py
+++ b/superset/security/manager.py
@@ -36,7 +36,7 @@ from urllib.parse import quote
from flask import current_app, Flask, g, has_app_context, Request, Response
from flask_appbuilder import Model
-from flask_appbuilder.api import expose, protect, safe
+from flask_appbuilder.api import expose, permission_name, protect, safe
from flask_appbuilder.models.filters import BaseFilter
from flask_appbuilder.security.sqla.apis import GroupApi, RoleApi, UserApi
from flask_appbuilder.security.sqla.apis.permission_view_menu.api import (
@@ -392,8 +392,11 @@ class SupersetUserApi(UserApi):
"""
Overriding the UserApi to sync Subject rows, filter excluded users,
handle deletion constraints, and add audit logging.
- UserApi has custom post/put that bypass hooks, so we override them
- and sync after the parent method succeeds.
+
+ The Subject sync happens in ``pre_add``/``pre_update``, which FAB calls
+ *before* the commit that ``self.datamodel.add``/``edit`` issues -- so the
+ sync rides that same commit rather than needing one of its own after the
+ fact.
"""
base_filters = [["username", ExcludeUsersFilter, lambda: []]]
@@ -413,6 +416,34 @@ class SupersetUserApi(UserApi):
"changed_on",
]
+ def pre_add(self, item: Model) -> None:
+ """Hash the password (FAB's own ``pre_add``), then sync the user's
+ ``Subject`` row before FAB's own commit.
+
+ ``UserApi.post`` calls ``pre_add`` *before* ``self.datamodel.add``,
+ which is what actually issues the commit -- so flushing the new user
+ here (to obtain its id) and syncing its ``Subject`` row alongside it
+ means both writes ride the same transaction and commit together,
+ instead of the subject sync needing a second, separate commit after
+ the fact.
+ """
+ super().pre_add(item)
+ from superset.daos.user import UserDAO
+
+ self.datamodel.session.add(item)
+ self.datamodel.session.flush()
+ UserDAO._sync_subject(item)
+
+ def pre_update(self, item: Model, data: dict[str, Any]) -> None:
+ """Same reasoning as ``pre_add``: ``UserApi.put`` calls ``pre_update``
+ before ``self.datamodel.edit`` commits, so the subject sync lands in
+ that same transaction.
+ """
+ super().pre_update(item, data)
+ from superset.daos.user import UserDAO
+
+ UserDAO._sync_subject(item)
+
@expose("/", methods=["POST"])
@protect()
@safe
@@ -428,17 +459,7 @@ class SupersetUserApi(UserApi):
500:
description: Server error
"""
- response = super().post()
- if response.status_code == 201:
- from superset.daos.user import UserDAO
-
- user_id = response.json.get("id")
- if user_id:
- user = self.datamodel.session.get(self.datamodel.obj, user_id)
- if user:
- UserDAO._sync_subject(user)
- self.datamodel.session.commit() # pylint: disable=consider-using-transaction
- return response
+ return super().post()
@expose("/<pk>", methods=["PUT"])
@protect()
@@ -462,15 +483,42 @@ class SupersetUserApi(UserApi):
500:
description: Server error
"""
- response = super().put(pk)
- if response.status_code == 200:
- from superset.daos.user import UserDAO
+ return super().put(pk)
- user = self.datamodel.get(pk, self._base_filters)
- if user:
- UserDAO._sync_subject(user)
- self.datamodel.session.commit() # pylint: disable=consider-using-transaction
- return response
+ @expose("/<int:pk>/sessions", methods=["DELETE"])
+ @protect()
+ @permission_name("put")
+ @safe
+ def terminate_sessions(self, pk: int) -> Response:
+ """Terminate a user's outstanding sessions without disabling their account.
+ ---
+ delete:
+ parameters:
+ - in: path
+ name: pk
+ schema:
+ type: integer
+ responses:
+ 200:
+ description: Sessions terminated
+ 404:
+ $ref: '#/components/responses/404'
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ from superset.security.session_invalidation import invalidate_sessions_for_user
+
+ user = self.datamodel.get(pk, self._base_filters)
+ if not user:
+ return self.response_404()
+
+ invalidate_sessions_for_user(user.id)
+ self.datamodel.session.commit() # pylint: disable=consider-using-transaction
+ _log_audit_event(
+ "UserSessionsTerminated",
+ {"target_username": user.username, "target_user_id": user.id},
+ )
+ return self.response(200, message="User sessions terminated.")
def pre_delete(self, item: Model) -> None:
from superset.daos.user import UserDAO
@@ -1553,9 +1601,23 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods
bypassed. We distinguish the two by comparing the acting user
(``g.user``) against the target ``userid``: they match for a
self-service reset and differ for an admin reset.
+
+ Also stamps the session-invalidation epoch for the target user, so
+ any session for the account that predates this reset stops working --
+ regardless of which of the two paths triggered it.
"""
super().reset_password(userid, password)
+ # pylint: disable=import-outside-toplevel
+ from superset import db
+ from superset.security.session_invalidation import invalidate_sessions_for_user
+
+ invalidate_sessions_for_user(int(userid))
+ # ``super().reset_password`` (FAB's ``update_user``) already committed
+ # its own change in a separate transaction, so the epoch stamp above
+ # needs its own commit too, rather than riding an existing one.
+ db.session.commit() # pylint: disable=consider-using-transaction
+
acting_user = getattr(g, "user", None)
acting_user_id = getattr(acting_user, "id", None)
# ``userid`` arrives as a string (the ``pk`` request arg) on the admin
diff --git a/tests/unit_tests/security/test_password_change_session_invalidation.py b/tests/unit_tests/security/test_password_change_session_invalidation.py
index 7ffb204bfe6..0386400e2e3 100644
--- a/tests/unit_tests/security/test_password_change_session_invalidation.py
+++ b/tests/unit_tests/security/test_password_change_session_invalidation.py
@@ -17,18 +17,19 @@
"""Password-change paths and the session-invalidation epoch.
``UserAttribute.sessions_invalidated_at`` (see
-``superset.security.session_invalidation``) is the only mechanism that forces
-outstanding sessions to log out; it is currently stamped exclusively by the
+``superset.security.session_invalidation``) is the mechanism that forces
+outstanding sessions to log out. Originally it was stamped exclusively by the
``after_update`` listener that fires when an account's ``active`` flag flips
-to ``False``. These tests document that none of the password-change paths --
-self-service reset, admin-initiated reset, or the ``PUT /api/v1/me/``
-self-service update -- stamp that epoch, so a session stolen before a
-password change remains valid after it.
+to ``False``; these tests now cover the additional password-change paths --
+self-service reset, admin-initiated reset, and the ``PUT /api/v1/me/``
+self-service update -- which also stamp that epoch, so a session authenticated
+before a password change stops working after it.
"""
from __future__ import annotations
from collections.abc import Iterator
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -37,6 +38,7 @@ from flask_appbuilder.security.sqla.models import User
from superset import db, security_manager
from superset.daos.user import UserDAO
from superset.models.user_attributes import UserAttribute
+from superset.security.manager import SupersetUserApi
from superset.views.users.api import CurrentUserRestApi
from tests.unit_tests.fixtures.common import admin_user, after_each # noqa: F401
@@ -85,13 +87,13 @@ def two_admins() -> Iterator[tuple[User, User]]:
db.session.commit()
-def test_self_service_password_reset_does_not_invalidate_other_sessions(
+def test_self_service_password_reset_invalidates_other_sessions(
two_admins: tuple[User, User],
) -> None:
"""``SupersetSecurityManager.reset_password`` used for a self-service
- reset (acting user resets their own password) leaves the session epoch
- untouched, so any other outstanding session for the account keeps working
- after the password changes.
+ reset (acting user resets their own password) stamps the session epoch,
+ so any other outstanding session for the account stops working after the
+ password changes.
"""
target, _actor = two_admins
@@ -99,16 +101,16 @@ def test_self_service_password_reset_does_not_invalidate_other_sessions(
mock_g.user = target
security_manager.reset_password(target.id, "BrandNewPassw0rd!")
- assert _invalidated_at(target.id) is None
+ assert _invalidated_at(target.id) is not None
-def test_admin_password_reset_does_not_invalidate_target_sessions(
+def test_admin_password_reset_invalidates_target_sessions(
two_admins: tuple[User, User],
) -> None:
- """An admin-initiated reset of *another* user's password -- the closest
- existing action to "terminate that user's sessions" -- also leaves the
- epoch untouched. There is no admin action that forces a target user's
- outstanding sessions to log out short of disabling their account.
+ """An admin-initiated reset of *another* user's password also stamps the
+ epoch, so the target's outstanding sessions stop working -- this is the
+ closest existing action to an explicit "terminate that user's sessions",
+ short of disabling the account.
"""
target, actor = two_admins
@@ -116,16 +118,17 @@ def test_admin_password_reset_does_not_invalidate_target_sessions(
mock_g.user = actor # differs from target: an admin-initiated reset
security_manager.reset_password(target.id, "TemporaryPassw0rd!")
- assert _invalidated_at(target.id) is None
+ assert _invalidated_at(target.id) is not None
-def test_update_me_password_change_does_not_invalidate_other_sessions(
+def test_update_me_password_change_invalidates_other_sessions(
admin_user: User, # noqa: F811
after_each: None, # noqa: F811
) -> None:
"""The ``PUT /api/v1/me/`` self-service password change (``pre_update`` +
- ``UserDAO.update`` in ``CurrentUserRestApi.update_me``) also never stamps
- the session-invalidation epoch.
+ ``UserDAO.update`` in ``CurrentUserRestApi.update_me``) also stamps the
+ session-invalidation epoch. ``admin_user`` starts with no password set, so
+ no ``current_password`` proof is required for this change to go through.
"""
api = CurrentUserRestApi()
data = {"password": "BrandNewPassw0rd!"}
@@ -136,4 +139,67 @@ def test_update_me_password_change_does_not_invalidate_other_sessions(
UserDAO.update(item=admin_user, attributes=data)
db.session.flush()
- assert _invalidated_at(admin_user.id) is None
+ assert _invalidated_at(admin_user.id) is not None
+
+
+def _make_api_for_target(user: User) -> SupersetUserApi:
+ """A ``SupersetUserApi`` instance wired to a fake ``datamodel`` that
+ resolves any pk lookup to ``user`` -- enough to exercise
+ ``terminate_sessions`` without going through HTTP/auth plumbing, mirroring
+ the pattern used in ``test_superset_user_api_subject_sync.py``.
+ """
+ api = SupersetUserApi()
+ api.datamodel = SimpleNamespace(
+ session=db.session,
+ obj=User,
+ get=lambda pk, base_filters=None: user,
+ )
+ api._base_filters = None
+ return api
+
+
+def test_terminate_sessions_action_stamps_target_epoch_without_disabling_account(
+ after_each: None, # noqa: F811
+) -> None:
+ """``SupersetUserApi.terminate_sessions`` -- the direct, explicit
+ "terminate this user's sessions" admin action -- stamps the epoch for the
+ target user without flipping ``active`` or otherwise touching the account,
+ unlike the only other action that has this effect (disabling the user).
+ """
+ role = db.session.query(security_manager.role_model).filter_by(name="Admin").one()
+ user = User(
+ first_name="Target",
+ last_name="User",
+ email="terminate_sessions_target@example.org",
+ username="terminate_sessions_target",
+ roles=[role],
+ )
+ db.session.add(user)
+ db.session.flush()
+
+ with patch.object(security_manager, "has_access", return_value=True):
+ response = _make_api_for_target(user).terminate_sessions(user.id)
+
+ assert response.status_code == 200
+ assert _invalidated_at(user.id) is not None
+ assert user.active
+
+
+def test_terminate_sessions_action_404s_for_unknown_user(
+ after_each: None, # noqa: F811
+) -> None:
+ """A pk that doesn't resolve to a user (or is filtered out by
+ ``base_filters``) 404s rather than stamping anything.
+ """
+ api = SupersetUserApi()
+ api.datamodel = SimpleNamespace(
+ session=db.session,
+ obj=User,
+ get=lambda pk, base_filters=None: None,
+ )
+ api._base_filters = None
+
+ with patch.object(security_manager, "has_access", return_value=True):
+ response = api.terminate_sessions(999999)
+
+ assert response.status_code == 404
diff --git a/tests/unit_tests/security/test_superset_user_api_subject_sync.py b/tests/unit_tests/security/test_superset_user_api_subject_sync.py
index f693ecc4ab3..e7af3ace2b3 100644
--- a/tests/unit_tests/security/test_superset_user_api_subject_sync.py
+++ b/tests/unit_tests/security/test_superset_user_api_subject_sync.py
@@ -14,13 +14,20 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-"""``SupersetUserApi.post``/``put`` commit the FAB user write, then sync the
-corresponding ``Subject`` row in a *separate* transaction. These tests show
-that when the second commit fails, the already-committed user is left
-without a compensating rollback: the ``@safe`` decorator on the endpoint
-catches the failure and turns it into a generic 500 response, and nothing
-deletes the user or retries the sync -- so the user row exists with no
-matching ``Subject`` row, and the only visible trace is a 500.
+"""``SupersetUserApi`` syncs the ``Subject`` row that mirrors each ``User``.
+
+``UserApi.post``/``put`` call ``self.pre_add``/``self.pre_update`` *before*
+the write that actually commits (``self.datamodel.add``/``edit``). Overriding
+those hooks -- instead of syncing after the fact, in a second commit issued
+once ``post``/``put`` have already returned -- means the subject sync rides
+the same transaction as the user write: one commit persists both, and a
+failure of that commit rolls both back together instead of leaving an
+orphaned user with no matching ``Subject`` row.
+
+These tests exercise ``pre_add``/``pre_update`` directly, plus the exact call
+pairs FAB's ``UserApi.post``/``put`` make (``pre_add``/``pre_update`` followed
+by the real ``SQLAInterface.add``/``edit``), to confirm that pairing shares a
+single commit and a single rollback.
"""
from __future__ import annotations
@@ -28,9 +35,8 @@ from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
-from flask_appbuilder.security.sqla.apis.user.api import UserApi
+from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.security.sqla.models import User
-from sqlalchemy.exc import IntegrityError
from superset import db, security_manager
from superset.security.manager import SupersetUserApi
@@ -39,132 +45,185 @@ from superset.subjects.types import SubjectType
from tests.unit_tests.fixtures.common import after_each # noqa: F401
-def _make_user(username: str) -> User:
- role = db.session.query(security_manager.role_model).filter_by(name="Admin").one()
+def _admin_role() -> object:
+ return db.session.query(security_manager.role_model).filter_by(name="Admin").one()
+
+
+def _make_pending_user(username: str) -> User:
+ """A transient ``User``, not yet added to the session.
+
+ Mirrors what FAB's ``UserApi.post()`` builds (``model = User()``, with
+ attributes set from the request payload) just before it calls
+ ``self.pre_add(model)`` and then ``self.datamodel.add(model)``.
+ """
+ return User(
+ first_name="New",
+ last_name="Guy",
+ email=f"{username}@example.org",
+ username=username,
+ roles=[_admin_role()],
+ password="irrelevant-pre-hash-value", # noqa: S106
+ )
+
+
+def _make_persisted_user(username: str) -> User:
+ """A ``User`` already committed, standing in for one an earlier request
+ created -- the starting point for a ``put``/``pre_update`` flow.
+ """
user = User(
first_name="New",
last_name="Guy",
email=f"{username}@example.org",
username=username,
- roles=[role],
+ roles=[_admin_role()],
)
db.session.add(user)
- db.session.commit() # simulate FAB's UserApi.post/put already committing
+ db.session.commit()
return user
-def test_post_leaves_user_without_subject_when_sync_commit_fails(
- after_each: None, # noqa: F811
-) -> None:
- """If the subject-sync commit in ``SupersetUserApi.post`` fails, the
- ``@safe`` decorator on the endpoint catches the exception and turns it
- into a generic 500 -- there is no ``except`` clause in ``post`` itself
- that would delete the just-created user or otherwise compensate.
- """
- user = _make_user("new_guy_post")
-
- fake_response = SimpleNamespace(status_code=201, json={"id": user.id})
+def _api_for(session=db.session) -> SupersetUserApi: # noqa: ANN001
api = SupersetUserApi()
- api.datamodel = SimpleNamespace(session=db.session, obj=User)
-
- with (
- patch.object(UserApi, "post", return_value=fake_response),
- patch.object(security_manager, "has_access", return_value=True),
- patch.object(
- db.session,
- "commit",
- side_effect=IntegrityError("stmt", {}, Exception("boom")),
- ),
- ):
- response = api.post()
-
- # The failure is swallowed into a generic 500 by the ``@safe`` decorator
- # -- not surfaced as e.g. a 422 tied to the user that was actually
- # created, and definitely not retried or compensated.
- assert response.status_code == 500
-
- db.session.rollback()
-
- # The user row from the (separate, already-succeeded) FAB commit is
- # still there ...
- assert db.session.query(User).filter_by(id=user.id).one_or_none() is not None
- # ... but the Subject row the failed commit was supposed to persist is
- # not, since nothing compensates for the failed sync.
- assert (
+ api.datamodel = SQLAInterface(User, session)
+ # FAB's own ``pre_update`` (which ``SupersetUserApi.pre_update`` calls via
+ # ``super()``) reads ``self.appbuilder.sm.current_user.id`` to stamp
+ # ``changed_by_fk`` -- stand in for the acting admin so that lookup
+ # succeeds outside of a real request/login context.
+ api.appbuilder = SimpleNamespace(
+ sm=SimpleNamespace(current_user=SimpleNamespace(id=1))
+ )
+ return api
+
+
+def _subject_for(user_id: int) -> Subject | None:
+ return (
db.session.query(Subject)
- .filter_by(user_id=user.id, type=SubjectType.USER)
+ .filter_by(user_id=user_id, type=SubjectType.USER)
.one_or_none()
- is None
)
-def test_put_leaves_user_without_subject_when_sync_commit_fails(
+def test_pre_add_syncs_subject_without_committing(
after_each: None, # noqa: F811
) -> None:
- """Same gap as ``post``, for ``SupersetUserApi.put``."""
- user = _make_user("new_guy_put")
+ """``pre_add`` flushes the new user (to obtain its id) and syncs its
+ ``Subject`` row, but does not commit -- that's still FAB's job, in
+ ``self.datamodel.add``, which runs right after.
+ """
+ user = _make_pending_user("new_guy_pre_add")
+ api = _api_for()
- fake_response = SimpleNamespace(status_code=200)
- api = SupersetUserApi()
- api.datamodel = SimpleNamespace(
- session=db.session,
- obj=User,
- get=lambda pk, base_filters=None: user,
- )
- api._base_filters = None
+ real_commit = db.session.commit
+ commit_calls = MagicMock(wraps=real_commit)
+ with patch.object(db.session, "commit", commit_calls):
+ api.pre_add(user)
- with (
- patch.object(UserApi, "put", return_value=fake_response),
- patch.object(security_manager, "has_access", return_value=True),
- patch.object(
- db.session,
- "commit",
- side_effect=IntegrityError("stmt", {}, Exception("boom")),
- ),
- ):
- response = api.put(user.id)
+ assert commit_calls.call_count == 0
+ assert user.id is not None
+ assert _subject_for(user.id) is not None
- assert response.status_code == 500
- db.session.rollback()
+def test_pre_add_and_datamodel_add_share_a_single_commit(
+ after_each: None, # noqa: F811
+) -> None:
+ """The exact pair of calls FAB's ``UserApi.post()`` makes --
+ ``self.pre_add(model)`` then ``self.datamodel.add(model)`` -- persist the
+ user and its ``Subject`` row together, via exactly one commit.
+ """
+ user = _make_pending_user("new_guy_shared_commit")
+ api = _api_for()
- assert db.session.query(User).filter_by(id=user.id).one_or_none() is not None
- assert (
- db.session.query(Subject)
- .filter_by(user_id=user.id, type=SubjectType.USER)
- .one_or_none()
- is None
- )
+ real_commit = db.session.commit
+ commit_calls = MagicMock(wraps=real_commit)
+ with patch.object(db.session, "commit", commit_calls):
+ api.pre_add(user)
+ api.datamodel.add(user)
+
+ assert commit_calls.call_count == 1
+ subject = _subject_for(user.id)
+ assert subject is not None
-def test_post_success_path_still_syncs_subject_in_a_second_commit(
+def test_pre_add_failure_rolls_back_user_and_subject_together(
after_each: None, # noqa: F811
) -> None:
- """Baseline/control: on the happy path the subject row is created, via a
- ``self.datamodel.session.commit()`` distinct from the one FAB's
- ``UserApi.post`` already issued for the user row -- i.e. two commits, not
- one atomic transaction.
+ """If the commit that follows ``pre_add`` fails (standing in: FAB's own
+ ``self.datamodel.add`` raising), the new user and the ``Subject`` row
+ flushed alongside it roll back together -- there is no window where the
+ user persists without a matching ``Subject``.
"""
- user = _make_user("new_guy_ok")
- fake_response = SimpleNamespace(status_code=201, json={"id": user.id})
- api = SupersetUserApi()
- api.datamodel = SimpleNamespace(session=db.session, obj=User)
+ user = _make_pending_user("new_guy_pre_add_fail")
+ api = _api_for()
+
+ api.pre_add(user)
+ user_id = user.id
+ assert user_id is not None
+ assert _subject_for(user_id) is not None # flushed, visible pre-rollback
+
+ db.session.rollback() # stands in for the follow-up commit failing
+
+ assert db.session.query(User).filter_by(id=user_id).one_or_none() is None
+ assert _subject_for(user_id) is None
+
+
+def test_pre_update_syncs_subject_without_committing(
+ after_each: None, # noqa: F811
+) -> None:
+ """Same reasoning as ``pre_add``, for an edit: ``pre_update`` syncs the
+ ``Subject`` row without committing, ahead of FAB's own
+ ``self.datamodel.edit``.
+ """
+ user = _make_persisted_user("new_guy_pre_update")
+ api = _api_for()
real_commit = db.session.commit
commit_calls = MagicMock(wraps=real_commit)
+ with patch.object(db.session, "commit", commit_calls):
+ api.pre_update(user, {})
- with (
- patch.object(UserApi, "post", return_value=fake_response),
- patch.object(security_manager, "has_access", return_value=True),
- patch.object(db.session, "commit", commit_calls),
- ):
- response = api.post()
+ assert commit_calls.call_count == 0
+ assert _subject_for(user.id) is not None
- assert response is fake_response
- assert commit_calls.call_count == 1 # the sync's own, separate commit
- subject = (
- db.session.query(Subject)
- .filter_by(user_id=user.id, type=SubjectType.USER)
- .one_or_none()
- )
- assert subject is not None
+
+def test_pre_update_and_datamodel_edit_share_a_single_commit(
+ after_each: None, # noqa: F811
+) -> None:
+ """The exact pair of calls FAB's ``UserApi.put()`` makes --
+ ``self.pre_update(model, item)`` then ``self.datamodel.edit(model)`` --
+ persist the edit and the ``Subject`` sync together, via exactly one
+ commit.
+ """
+ user = _make_persisted_user("new_guy_shared_commit_put")
+ api = _api_for()
+
+ real_commit = db.session.commit
+ commit_calls = MagicMock(wraps=real_commit)
+ with patch.object(db.session, "commit", commit_calls):
+ api.pre_update(user, {})
+ api.datamodel.edit(user)
+
+ assert commit_calls.call_count == 1
+ assert _subject_for(user.id) is not None
+
+
+def test_pre_update_failure_rolls_back_subject_sync_without_orphaning(
+ after_each: None, # noqa: F811
+) -> None:
+ """If the commit that follows ``pre_update`` fails, the ``Subject`` row it
+ flushed rolls back too -- the previously-persisted user row (created by
+ an earlier, already-successful request) is left exactly as it was, with
+ no half-applied sync attached to it.
+ """
+ user = _make_persisted_user("new_guy_pre_update_fail")
+ user_id = user.id
+ api = _api_for()
+
+ api.pre_update(user, {})
+ assert _subject_for(user_id) is not None # flushed, visible pre-rollback
+
+ db.session.rollback() # stands in for the follow-up commit failing
+
+ # The user itself predates this (failed) request and survives.
+ assert db.session.query(User).filter_by(id=user_id).one_or_none() is not None
+ # But the subject sync this request attempted never landed.
+ assert _subject_for(user_id) is None