codeant-ai-for-open-source[bot] commented on code in PR #40669: URL: https://github.com/apache/superset/pull/40669#discussion_r3400366348
########## superset/security/password_change.py: ########## @@ -0,0 +1,173 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Force-password-change-on-first-use enforcement. + +A per-user ``password_must_change`` flag (on ``UserAttribute``) marks accounts — +typically created by an administrator — that must set a new password before +they can use the rest of the application. When ``ENABLE_FORCE_PASSWORD_CHANGE`` +is enabled, a ``before_request`` hook redirects such users to the password-reset +page until they change it; the flag is cleared automatically on a successful +*self-service* password reset (see ``SupersetSecurityManager.reset_password``). +An admin-initiated reset deliberately preserves the flag so the target user is +still forced to change the temporary password at next login. +""" + +from __future__ import annotations + +import logging +from typing import Any, Optional + +from flask import current_app, flash, g, redirect, request, url_for +from flask_babel import gettext as __ + +from superset.utils.decorators import transaction + +logger = logging.getLogger(__name__) + +# Flask endpoints take the form ``<ViewClass>.<method>`` (or a bare name for +# function views). The following must remain reachable while a password change +# is pending, otherwise the redirect would loop: the auth views (login/logout +# for every auth backend), the password-reset and user-info-edit views, static +# assets, and the health check. We match the *view-class* component (the part +# before the dot) exactly against the allow-list below rather than doing a +# substring search, so unrelated endpoints that merely share a substring (e.g. +# an "Author"-named view, or any name containing "health"/"static") are not +# accidentally exempted from enforcement. +_EXEMPT_VIEW_CLASSES = frozenset( + { + "AuthDBView", + "AuthLDAPView", + "AuthOAuthView", + "AuthOIDView", + "AuthRemoteUserView", + "ResetMyPasswordView", + "ResetPasswordView", + "UserInfoEditView", + } +) + +# Exact endpoint names (function views / Flask built-ins) that are always exempt. +_EXEMPT_ENDPOINTS = frozenset({"static", "appbuilder.static", "health", "healthcheck"}) + + +def _get_user_attribute(user_id: int) -> Optional[Any]: + # Imported lazily to avoid import cycles at app-init time. + from superset.extensions import db + from superset.models.user_attributes import UserAttribute + + # The ``user_attribute`` table does not enforce uniqueness on ``user_id``, + # so a user could have more than one row. ``.one_or_none()`` would raise + # ``MultipleResultsFound`` (a 500) in that case; fetch deterministically by + # ordering on the primary key and taking the first row instead. + return ( + db.session.query(UserAttribute) + .filter(UserAttribute.user_id == user_id) + .order_by(UserAttribute.id) + .first() + ) + + +def password_change_required(user: Any) -> bool: + """Return True if ``user`` has a pending forced password change.""" + user_id = getattr(user, "id", None) + if not user_id: + return False + attr = _get_user_attribute(user_id) + return bool(attr and attr.password_must_change) + + +@transaction() +def set_password_must_change(user_id: int, value: bool = True) -> None: + """Set (or clear) the forced-password-change flag for a user. + + Intended to be called by administrative flows when provisioning an account + that should require a password change on first use. + """ + from superset.extensions import db + from superset.models.user_attributes import UserAttribute + + attr = _get_user_attribute(user_id) + if attr is None: + attr = UserAttribute(user_id=user_id) + db.session.add(attr) + attr.password_must_change = value + + +@transaction() +def clear_password_must_change(user_id: int) -> None: + """Clear the forced-password-change flag for a user, if set.""" + attr = _get_user_attribute(user_id) + if attr and attr.password_must_change: + attr.password_must_change = False + + +def _is_exempt_endpoint(endpoint: Optional[str]) -> bool: + # A missing endpoint (e.g. an unmatched URL) is left to normal 404 handling. + if not endpoint: + return True + if endpoint in _EXEMPT_ENDPOINTS: + return True + # Any blueprint's static route, e.g. "<blueprint>.static". + if endpoint.endswith(".static"): + return True + # Match the view-class component exactly, so e.g. "AuthDBView.login" is + # exempt but an unrelated "AuthorView.list" is not. + view_class = endpoint.split(".", 1)[0] + return view_class in _EXEMPT_VIEW_CLASSES + + +def register_password_change_enforcement(app: Any) -> None: + """Register the before-request hook that enforces pending password changes. + + No-op unless ``ENABLE_FORCE_PASSWORD_CHANGE`` is enabled, so there is zero + per-request overhead in the default configuration. + """ + + @app.before_request + def _enforce_password_change() -> Any: # pylint: disable=unused-variable + if not current_app.config.get("ENABLE_FORCE_PASSWORD_CHANGE"): + return None + + user = getattr(g, "user", None) + if not user or getattr(user, "is_anonymous", True): + return None + + if _is_exempt_endpoint(request.endpoint): + return None + + if not password_change_required(user): + return None + + flash(__("You must change your password before continuing."), "warning") + # Resolve the password-reset page. If that endpoint can't be resolved + # (e.g. a custom security manager without ``ResetMyPasswordView``), fall + # back to logout, which is always exempt from this enforcement. We must + # NOT fall back to "/" or any other non-exempt route: the index re-runs + # this same hook and would trap the user in an infinite 302 loop. If no + # exempt target can be resolved at all, return an error response rather + # than redirect, so a flagged user can never get stuck looping. + for endpoint in ("ResetMyPasswordView.this_form_get", "AuthDBView.logout"): + try: + return redirect(url_for(endpoint)) + except Exception: # noqa: BLE001, S112 # pylint: disable=broad-except + # Try the next exempt fallback; a failed url_for resolution here + # is expected/benign and not worth logging per attempt. + continue Review Comment: **Suggestion:** The fallback redirect target hardcodes `AuthDBView.logout`, but the code explicitly supports non-DB auth backends (`AuthLDAPView`, `AuthOAuthView`, `AuthRemoteUserView`, etc.). In those deployments, if `ResetMyPasswordView` is unavailable, this DB-specific logout endpoint may not resolve and the hook will return 503 on every protected request, effectively locking flagged users out. Resolve logout dynamically for the active auth view (or include all auth logout endpoints in fallback candidates). [logic error] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ Flagged users on non-DB auth receive 503 on access. - ⚠️ Forced-password-change feature unusable on some auth backends. - ⚠️ Misconfiguration yields hard-to-diagnose login-time 503 errors. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. The Superset initialization registers the enforcement hook unconditionally in `superset/initialization/__init__.py:724-739`, where `register_password_change_enforcement(self.superset_app)` wires `_enforce_password_change` as a `before_request` handler. 2. In `superset/security/password_change.py:141-153`, `_enforce_password_change` checks `current_app.config["ENABLE_FORCE_PASSWORD_CHANGE"]` and `g.user` (non-anonymous) and then, for non-exempt endpoints (see `_is_exempt_endpoint` at lines 118-130), calls `password_change_required(user)`; when `UserAttribute.password_must_change` is `True`, the hook proceeds to the redirect logic. 3. At lines 155-163 in `superset/security/password_change.py`, the hook tries to resolve a password-reset endpoint and then a logout endpoint via `for endpoint in ("ResetMyPasswordView.this_form_get", "AuthDBView.logout"):`; any failure in `url_for(endpoint)` is caught and ignored, and if both endpoints fail to resolve, the function falls through to returning `("You must change your password before continuing.", 503)` at lines 171-172. 4. In a deployment where `ENABLE_FORCE_PASSWORD_CHANGE` is `True` but the active authentication setup (for example, a non-DB or custom security manager) does not register `ResetMyPasswordView.this_form_get` or `AuthDBView.logout` as endpoints, every non-exempt request by a flagged user (e.g., `GET "/"` hitting the index view) will cause both `url_for("ResetMyPasswordView.this_form_get")` and `url_for("AuthDBView.logout")` to raise, the hook will return the 503 tuple, and the user will see a 503 on every protected route with no way to proceed, effectively locking them out while the flag is set. ``` </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=db69d4cc92aa40e6a6ecb7b12629ddbb&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=db69d4cc92aa40e6a6ecb7b12629ddbb&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/security/password_change.py **Line:** 163:169 **Comment:** *Logic Error: The fallback redirect target hardcodes `AuthDBView.logout`, but the code explicitly supports non-DB auth backends (`AuthLDAPView`, `AuthOAuthView`, `AuthRemoteUserView`, etc.). In those deployments, if `ResetMyPasswordView` is unavailable, this DB-specific logout endpoint may not resolve and the hook will return 503 on every protected request, effectively locking flagged users out. Resolve logout dynamically for the active auth view (or include all auth logout endpoints in fallback candidates). Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=f2658b9b678bb15a6d45fd933332e73255e696ff5ae15715e85408c158867276&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=f2658b9b678bb15a6d45fd933332e73255e696ff5ae15715e85408c158867276&reaction=dislike'>👎</a> ########## superset/security/password_change.py: ########## @@ -0,0 +1,173 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Force-password-change-on-first-use enforcement. + +A per-user ``password_must_change`` flag (on ``UserAttribute``) marks accounts — +typically created by an administrator — that must set a new password before +they can use the rest of the application. When ``ENABLE_FORCE_PASSWORD_CHANGE`` +is enabled, a ``before_request`` hook redirects such users to the password-reset +page until they change it; the flag is cleared automatically on a successful +*self-service* password reset (see ``SupersetSecurityManager.reset_password``). +An admin-initiated reset deliberately preserves the flag so the target user is +still forced to change the temporary password at next login. +""" + +from __future__ import annotations + +import logging +from typing import Any, Optional + +from flask import current_app, flash, g, redirect, request, url_for +from flask_babel import gettext as __ + +from superset.utils.decorators import transaction + +logger = logging.getLogger(__name__) + +# Flask endpoints take the form ``<ViewClass>.<method>`` (or a bare name for +# function views). The following must remain reachable while a password change +# is pending, otherwise the redirect would loop: the auth views (login/logout +# for every auth backend), the password-reset and user-info-edit views, static +# assets, and the health check. We match the *view-class* component (the part +# before the dot) exactly against the allow-list below rather than doing a +# substring search, so unrelated endpoints that merely share a substring (e.g. +# an "Author"-named view, or any name containing "health"/"static") are not +# accidentally exempted from enforcement. +_EXEMPT_VIEW_CLASSES = frozenset( + { + "AuthDBView", + "AuthLDAPView", + "AuthOAuthView", + "AuthOIDView", + "AuthRemoteUserView", + "ResetMyPasswordView", + "ResetPasswordView", + "UserInfoEditView", + } +) + +# Exact endpoint names (function views / Flask built-ins) that are always exempt. +_EXEMPT_ENDPOINTS = frozenset({"static", "appbuilder.static", "health", "healthcheck"}) + + +def _get_user_attribute(user_id: int) -> Optional[Any]: + # Imported lazily to avoid import cycles at app-init time. + from superset.extensions import db + from superset.models.user_attributes import UserAttribute + + # The ``user_attribute`` table does not enforce uniqueness on ``user_id``, + # so a user could have more than one row. ``.one_or_none()`` would raise + # ``MultipleResultsFound`` (a 500) in that case; fetch deterministically by + # ordering on the primary key and taking the first row instead. + return ( + db.session.query(UserAttribute) + .filter(UserAttribute.user_id == user_id) + .order_by(UserAttribute.id) + .first() + ) + + +def password_change_required(user: Any) -> bool: + """Return True if ``user`` has a pending forced password change.""" + user_id = getattr(user, "id", None) + if not user_id: + return False + attr = _get_user_attribute(user_id) + return bool(attr and attr.password_must_change) + + +@transaction() +def set_password_must_change(user_id: int, value: bool = True) -> None: + """Set (or clear) the forced-password-change flag for a user. + + Intended to be called by administrative flows when provisioning an account + that should require a password change on first use. + """ + from superset.extensions import db + from superset.models.user_attributes import UserAttribute + + attr = _get_user_attribute(user_id) + if attr is None: + attr = UserAttribute(user_id=user_id) + db.session.add(attr) + attr.password_must_change = value Review Comment: **Suggestion:** `set_password_must_change` does a read-then-insert sequence that is not atomic under concurrency. With the unique constraint on `user_attribute.user_id`, two concurrent calls for the same user can both see no row, both insert, and one request will fail with an `IntegrityError` (500). Use an upsert/retry pattern (like the session invalidation code) or catch `IntegrityError` and retry as update. [race condition] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Concurrent flag setting can 500 on user provisioning. - ⚠️ Forced-password-change lifecycle unreliable under parallel admin flows. - ⚠️ IntegrityError noise complicates debugging and monitoring. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Note that the `UserAttribute` model in `superset/models/user_attributes.py` defines a unique constraint on `user_id` via `__table_args__ = (UniqueConstraint("user_id", name="uq_user_attribute_user_id"),)` at approximately line 47 (verified via BulkRead). 2. Observe `set_password_must_change(user_id, value)` in `superset/security/password_change.py:94-107`, which calls `_get_user_attribute(user_id)` and, if it returns `None`, creates `UserAttribute(user_id=user_id)` and `db.session.add(attr)` (lines 103-106), all wrapped in the `@transaction()` decorator. 3. The `transaction()` decorator in `superset/utils/decorators.py:235-39` starts a unit of work and commits with `db.session.commit()` at line 27, rolling back and re-raising any exception (including `IntegrityError`) without retry logic (lines 26-35). 4. In a running Superset app, create a user (any code path that inserts into `ab_user`) and then trigger two concurrent calls to `set_password_must_change(<that_user_id>)` (e.g., two threads or two simultaneous HTTP requests in a future admin provisioning endpoint): both executions see `_get_user_attribute` return `None`, both add a new `UserAttribute` with the same `user_id`, the first commit succeeds, and the second commit hits the unique constraint at `user_attribute.user_id` and raises `IntegrityError`, which bubbles up as a 500 error. ``` </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=96ffe73ae89a4635a5b3b854e45bf465&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=96ffe73ae89a4635a5b3b854e45bf465&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/security/password_change.py **Line:** 103:107 **Comment:** *Race Condition: `set_password_must_change` does a read-then-insert sequence that is not atomic under concurrency. With the unique constraint on `user_attribute.user_id`, two concurrent calls for the same user can both see no row, both insert, and one request will fail with an `IntegrityError` (500). Use an upsert/retry pattern (like the session invalidation code) or catch `IntegrityError` and retry as update. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=246d25fad06f3f8e7dbd1702fb7c4ae834aa286da8041a52aeb5f3d0b37c3e0a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=246d25fad06f3f8e7dbd1702fb7c4ae834aa286da8041a52aeb5f3d0b37c3e0a&reaction=dislike'>👎</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
