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:12 UTC
(superset) 02/03: fix(security): require current password proof to change account password
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 55adaa9e300fc0e03d0b8907bc24142b8bcf0194
Author: Amin Ghadersohi <am...@gmail.com>
AuthorDate: Sun Aug 9 08:35:21 2026 -0700
fix(security): require current password proof to change account password
CurrentUserRestApi.update_me accepted a new password with no proof of the
existing one, and pre_update's plaintext password briefly overwrote the
hash it had just computed before UserDAO.update persisted it, since both
lived in the same dict passed through as DAO attributes.
CurrentUserPutSchema now carries a current_password field, required
whenever password is present; pre_update verifies it against the stored
hash (skipped only for accounts with no password set yet), pops both
password and current_password out of the attributes dict once it has
used them, and stamps the session-invalidation epoch so a password
change also ends any other outstanding session for the account.
Co-Authored-By: Claude Sonnet 5 <no...@anthropic.com>
---
superset/security/session_invalidation.py | 17 +++++
superset/views/users/api.py | 29 ++++++++-
superset/views/users/schemas.py | 28 ++++++++-
tests/unit_tests/views/test_current_user_api.py | 82 ++++++++++++++++++-------
4 files changed, 130 insertions(+), 26 deletions(-)
diff --git a/superset/security/session_invalidation.py b/superset/security/session_invalidation.py
index c76d16e386e..89728ff18ce 100644
--- a/superset/security/session_invalidation.py
+++ b/superset/security/session_invalidation.py
@@ -187,6 +187,23 @@ def invalidate_user_sessions(connection: Any, user_id: int) -> None:
_stamp_existing()
+def invalidate_sessions_for_user(user_id: int) -> None:
+ """Stamp the invalidation epoch for ``user_id`` from ordinary application code.
+
+ Convenience wrapper around ``invalidate_user_sessions`` for callers that
+ don't have the raw ``Connection`` the ``after_update`` event listener
+ receives -- e.g. a password-change flow. The stamp is written through the
+ current session's own connection, so it participates in whatever
+ transaction the caller's other pending changes belong to; it is not
+ committed here, so the caller's own commit (or the next flush that
+ triggers one) is what makes it durable.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset.extensions import db
+
+ invalidate_user_sessions(db.session.connection(), user_id)
+
+
def _stamp_epoch_on_disable(_mapper: Any, connection: Any, target: Any) -> None:
history = inspect(target).attrs.active.history
# Only act when ``active`` actually changed to False — ignore the
diff --git a/superset/views/users/api.py b/superset/views/users/api.py
index 5a1275f6b4d..e8f7464b224 100644
--- a/superset/views/users/api.py
+++ b/superset/views/users/api.py
@@ -23,11 +23,12 @@ from flask_appbuilder.security.decorators import protect
from flask_appbuilder.security.sqla.models import User
from marshmallow import ValidationError
from sqlalchemy.orm.exc import NoResultFound
-from werkzeug.security import generate_password_hash
+from werkzeug.security import check_password_hash, generate_password_hash
from superset import is_feature_enabled
from superset.daos.user import UserDAO
from superset.extensions import db, event_logger
+from superset.security.session_invalidation import invalidate_sessions_for_user
from superset.utils.slack import get_user_avatar, SlackClientError
from superset.views.base_api import BaseSupersetApi, requires_json, statsd_metrics
from superset.views.users.schemas import CurrentUserPutSchema, UserResponseSchema
@@ -49,12 +50,36 @@ class CurrentUserRestApi(BaseSupersetApi):
def pre_update(self, item: User, data: Dict[str, Any]) -> None:
item.changed_on = datetime.now()
item.changed_by_fk = g.user.id
+ # Pop unconditionally: this key is only meaningful for verifying a
+ # password change below, and it isn't a real column on the user
+ # model -- it must never reach ``UserDAO.update``'s ``setattr`` loop.
+ current_password = data.pop("current_password", None)
if "password" in data and data["password"]:
+ # An account with no password set yet (e.g. provisioned via an
+ # external auth backend) has nothing to prove knowledge of; for
+ # every other account, the caller must confirm the existing
+ # password before it can be replaced.
+ proof_ok = current_password and check_password_hash(
+ item.password, current_password
+ )
+ if item.password and not proof_ok:
+ raise ValidationError(
+ {"current_password": ["Incorrect current password."]}
+ )
+ # Compute and assign the hash, then drop the plaintext from
+ # ``data`` -- it is passed to ``UserDAO.update`` as ``attributes``
+ # right after this, and ``BaseDAO.update`` sets every key in it
+ # via ``setattr``. Leaving the plaintext in would overwrite the
+ # hash just assigned below with the raw value.
+ new_password = data.pop("password")
item.password = generate_password_hash(
- password=data["password"],
+ password=new_password,
method=app.config.get("FAB_PASSWORD_HASH_METHOD", "scrypt"),
salt_length=app.config.get("FAB_PASSWORD_HASH_SALT_LENGTH", 16),
)
+ # A changed password invalidates any other outstanding session
+ # for this account.
+ invalidate_sessions_for_user(item.id)
@expose("/", methods=("GET",))
@protect()
diff --git a/superset/views/users/schemas.py b/superset/views/users/schemas.py
index 6493ba24177..56f0fd2c563 100644
--- a/superset/views/users/schemas.py
+++ b/superset/views/users/schemas.py
@@ -14,17 +14,22 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+from typing import Any
+
from flask_appbuilder.security.sqla.apis.user.schema import User
from flask_appbuilder.security.sqla.apis.user.validator import (
PasswordComplexityValidator,
)
-from marshmallow import fields, Schema
+from marshmallow import fields, Schema, validates_schema, ValidationError
from marshmallow.fields import Boolean, Integer, String
from marshmallow.validate import Length
first_name_description = "The current user's first name"
last_name_description = "The current user's last name"
password_description = "The current user's password for authentication" # noqa: S105
+# Required, and verified against the account's existing password, whenever
+# ``password`` is included in the payload.
+current_password_description = "The current user's existing password" # noqa: S105
class UserGroupSchema(Schema):
@@ -64,3 +69,24 @@ class CurrentUserPutSchema(Schema):
validate=[PasswordComplexityValidator()],
metadata={"description": password_description},
)
+ current_password = fields.String(
+ required=False,
+ load_only=True,
+ metadata={"description": current_password_description},
+ )
+
+ @validates_schema
+ def validate_current_password_required_with_password(
+ self, data: dict[str, Any], **kwargs: object
+ ) -> None:
+ """Require ``current_password`` whenever ``password`` is being set.
+
+ This only checks that the field was supplied -- whether it actually
+ matches the account's existing password is verified against the
+ database in ``CurrentUserRestApi.pre_update``, which has access to
+ the user record this schema doesn't.
+ """
+ if data.get("password") and not data.get("current_password"):
+ raise ValidationError(
+ {"current_password": ["This field is required to change the password."]}
+ )
diff --git a/tests/unit_tests/views/test_current_user_api.py b/tests/unit_tests/views/test_current_user_api.py
index fe8236e2385..59478833978 100644
--- a/tests/unit_tests/views/test_current_user_api.py
+++ b/tests/unit_tests/views/test_current_user_api.py
@@ -27,8 +27,10 @@ from __future__ import annotations
from typing import Any
from unittest.mock import patch
+import pytest
from flask_appbuilder.security.sqla.models import User
-from werkzeug.security import check_password_hash
+from marshmallow import ValidationError
+from werkzeug.security import check_password_hash, generate_password_hash
from superset import db
from superset.daos.user import UserDAO
@@ -51,32 +53,63 @@ def _run_update_me(user: User, data: dict[str, Any]) -> None:
UserDAO.update(item=user, attributes=data)
-def test_current_user_put_schema_has_no_current_password_field() -> None:
- """The payload schema for ``PUT /api/v1/me/`` carries no field for proving
- knowledge of the existing password -- a ``password`` key alone is enough
- to change it.
+def test_current_user_put_schema_has_current_password_field() -> None:
+ """The payload schema for ``PUT /api/v1/me/`` carries a field for proving
+ knowledge of the existing password, required whenever ``password`` is
+ supplied.
"""
- fields = CurrentUserPutSchema().fields
+ schema = CurrentUserPutSchema()
- assert "password" in fields
- assert "current_password" not in fields
- assert "old_password" not in fields
+ assert "password" in schema.fields
+ assert "current_password" in schema.fields
+ with pytest.raises(ValidationError):
+ schema.load({"password": "BrandNewPassw0rd!"})
-def test_update_me_changes_password_without_proof_of_current_password(
+ # Present alongside "password", it loads fine (the schema only checks
+ # that it was *supplied*; whether it's actually correct is verified
+ # against the database in ``CurrentUserRestApi.pre_update``).
+ loaded = schema.load(
+ {"password": "BrandNewPassw0rd!", "current_password": "OldPassw0rd!"}
+ )
+ assert loaded["current_password"] == "OldPassw0rd!" # noqa: S105
+
+
+def test_update_me_rejects_password_change_without_correct_current_password(
admin_user: User, # noqa: F811
after_each: None, # noqa: F811
) -> None:
- """A caller with an authenticated session can change the password by
- supplying only the new value -- no current-password (or other fresh-auth)
- field is read or checked anywhere in the update path.
+ """A caller can no longer change the password by supplying only the new
+ value: an account with an existing password must prove knowledge of it
+ via ``current_password`` -- omitting the field, or getting it wrong, both
+ reject the change and leave the stored password untouched. Supplying the
+ correct current password lets the change through.
"""
- original_password = admin_user.password
-
- _run_update_me(admin_user, {"password": "BrandNewPassw0rd!"})
+ original_hash = generate_password_hash("OldPassw0rd!")
+ admin_user.password = original_hash
+
+ with pytest.raises(ValidationError):
+ _run_update_me(admin_user, {"password": "BrandNewPassw0rd!"})
+ assert admin_user.password == original_hash
+
+ with pytest.raises(ValidationError):
+ _run_update_me(
+ admin_user,
+ {
+ "password": "BrandNewPassw0rd!",
+ "current_password": "WrongPassw0rd!",
+ },
+ )
+ assert admin_user.password == original_hash
+
+ _run_update_me(
+ admin_user,
+ {"password": "BrandNewPassw0rd!", "current_password": "OldPassw0rd!"},
+ )
db.session.flush()
- assert admin_user.password != original_password
+ assert admin_user.password != original_hash
+ assert check_password_hash(admin_user.password, "BrandNewPassw0rd!")
def test_update_me_password_change_persists_a_hash_not_plaintext(
@@ -84,12 +117,15 @@ def test_update_me_password_change_persists_a_hash_not_plaintext(
after_each: None, # noqa: F811
) -> None:
"""``pre_update`` computes ``generate_password_hash(data["password"])`` and
- assigns it to the user, but ``UserDAO.update`` is then called with the
- *same* ``data`` dict as ``attributes`` -- and that dict still has the
- plaintext ``password`` key. ``BaseDAO.update`` blindly ``setattr``s every
- key in ``attributes``, so the plaintext overwrites the hash that was just
- computed, and the plaintext password is what actually reaches the
- database.
+ assigns it to the user, and ``UserDAO.update`` is then called with the
+ *same* ``data`` dict as ``attributes``. ``BaseDAO.update`` blindly
+ ``setattr``s every key in ``attributes``, so ``pre_update`` must remove
+ the plaintext ``password`` key (and any ``current_password``) from that
+ dict once it's done with them, or the plaintext would overwrite the hash
+ that was just computed and reach the database instead of it.
+
+ ``admin_user`` starts with no password set, so this exercises the
+ first-password-set path, which requires no proof of a prior password.
"""
new_password = "BrandNewPassw0rd!" # noqa: S105