codeant-ai-for-open-source[bot] commented on code in PR #40669: URL: https://github.com/apache/superset/pull/40669#discussion_r3384802552
########## superset/security/password_change.py: ########## @@ -0,0 +1,136 @@ +# 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 +password reset (see ``SupersetSecurityManager.reset_password``). +""" + +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__) + +# Endpoint substrings that must remain reachable while a password change is +# pending, otherwise the redirect would loop (login/logout, the password-reset +# and user-info views, static assets, and the health check). +_EXEMPT_ENDPOINT_TOKENS = ( + "static", + "appbuilder", + "login", + "logout", + "resetmypassword", + "resetpassword", + "userinfoedit", + "userinfo", + "auth", + "health", +) + + +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 + + return ( + db.session.query(UserAttribute) + .filter(UserAttribute.user_id == user_id) + .one_or_none() + ) Review Comment: **Suggestion:** Using `.one_or_none()` on `user_attribute` can raise `MultipleResultsFound` and break requests with a 500 if a user has more than one attribute row. This table does not enforce uniqueness on `user_id`, so this query path is not safe; fetch a single row deterministically (for example with `.first()` plus an order) or enforce/repair uniqueness before relying on one-row semantics. [logic error] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ Non-exempt requests for affected users crash with 500. - ❌ Forced password-change enforcement fails when duplicates are present. - ⚠️ Future admin flows using this helper may break. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Note the `user_attribute` table definition in `superset/migrations/versions/2018-08-06_14-38_0c5070e96b57_add_user_attributes_table.py:35-19` creates `user_id` without any UNIQUE constraint, and the model `UserAttribute` in `superset/models/user_attributes.py:36-48` also has no uniqueness on `user_id`. 2. Insert two rows into `user_attribute` for the same user (e.g. `user_id = 5`) using SQL or ORM, creating duplicate attributes; this is allowed by the schema and not prevented by existing writers like `copy_dashboard` in `superset/models/dashboard.py:70-21` or `UserDAO.set_avatar_url` in `superset/daos/user.py:36-41`. 3. Start Superset with this PR and enable `ENABLE_FORCE_PASSWORD_CHANGE` so `register_password_change_enforcement(self.superset_app)` in `superset/initialization/__init__.py:13-19` registers the `_enforce_password_change` `@app.before_request` hook from `superset/security/password_change.py:116-136`. 4. Log in as the affected user and request a non-exempt endpoint such as the index view (`"SupersetIndexView.index"` is verified non-exempt in `superset/tests/unit_tests/security/test_password_change.py:31-39`); `_enforce_password_change` calls `password_change_required` (lines 68-74), which calls `_get_user_attribute` (lines 56-65), and the `.one_or_none()` at line 64 sees 2 rows and raises `MultipleResultsFound`, returning HTTP 500 instead of a normal response. ``` </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=e13645b179324a60981722d2ca9d4f55&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=e13645b179324a60981722d2ca9d4f55&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:** 61:65 **Comment:** *Logic Error: Using `.one_or_none()` on `user_attribute` can raise `MultipleResultsFound` and break requests with a 500 if a user has more than one attribute row. This table does not enforce uniqueness on `user_id`, so this query path is not safe; fetch a single row deterministically (for example with `.first()` plus an order) or enforce/repair uniqueness before relying on one-row semantics. 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=b38a802e2ecf061a387e7bad22b6400a154262a755d8a9173c72e3bd25e8838e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=b38a802e2ecf061a387e7bad22b6400a154262a755d8a9173c72e3bd25e8838e&reaction=dislike'>👎</a> ########## superset/security/password_change.py: ########## @@ -0,0 +1,136 @@ +# 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 +password reset (see ``SupersetSecurityManager.reset_password``). +""" + +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__) + +# Endpoint substrings that must remain reachable while a password change is +# pending, otherwise the redirect would loop (login/logout, the password-reset +# and user-info views, static assets, and the health check). +_EXEMPT_ENDPOINT_TOKENS = ( + "static", + "appbuilder", + "login", + "logout", + "resetmypassword", + "resetpassword", + "userinfoedit", + "userinfo", + "auth", + "health", +) + + +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 + + return ( + db.session.query(UserAttribute) + .filter(UserAttribute.user_id == user_id) + .one_or_none() + ) + + +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: + if not endpoint: + return True + lowered = endpoint.lower() + return any(token in lowered for token in _EXEMPT_ENDPOINT_TOKENS) + + +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") + try: + target = url_for("ResetMyPasswordView.this_form_get") + except Exception: # noqa: BLE001 # pylint: disable=broad-except + target = "/" + return redirect(target) Review Comment: **Suggestion:** Falling back to `"/"` when `url_for("ResetMyPasswordView.this_form_get")` fails creates a redirect loop for flagged users, because the index route is non-exempt and immediately re-triggers the same enforcement logic. Use a guaranteed-exempt fallback endpoint (or skip redirect and return an error page) to avoid infinite 302 loops. [logic error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Flagged users can be stuck in infinite redirect loops. - ❌ Password-change-on-first-use flow fails when URL resolution breaks. - ⚠️ Misconfigured deployments may lock users out of the UI. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Ensure `register_password_change_enforcement(self.superset_app)` is called as in `superset/initialization/__init__.py:13-19` and enable `ENABLE_FORCE_PASSWORD_CHANGE` in config so `_enforce_password_change` in `superset/security/password_change.py:116-136` runs on every request. 2. Configure or modify the app so `url_for("ResetMyPasswordView.this_form_get")` fails (for example, by using a custom security manager or removing `ResetMyPasswordView` so the endpoint name is unknown), causing the `except Exception` block at lines 133-135 to execute and set `target = "/"`. 3. Mark a logged-in user as requiring a password change (e.g. via `set_password_must_change` at lines 77-91), then request the root path `/`, which is handled by `SupersetIndexView.index` (verified non-exempt in `superset/tests/unit_tests/security/test_password_change.py:31-39` since `_is_exempt_endpoint("SupersetIndexView.index")` returns `False`). 4. On each request to `/`, `_enforce_password_change` sees a non-exempt endpoint and a pending password change, attempts `url_for("ResetMyPasswordView.this_form_get")`, falls back to `target = "/"`, and issues `redirect("/")`; the redirected request again hits the same non-exempt index endpoint, re-triggering the same logic and creating an infinite 302 redirect loop for the flagged user. ``` </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=1d195cf3f5ec4308b394b26fd0fc9577&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=1d195cf3f5ec4308b394b26fd0fc9577&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:** 132:136 **Comment:** *Logic Error: Falling back to `"/"` when `url_for("ResetMyPasswordView.this_form_get")` fails creates a redirect loop for flagged users, because the index route is non-exempt and immediately re-triggers the same enforcement logic. Use a guaranteed-exempt fallback endpoint (or skip redirect and return an error page) to avoid infinite 302 loops. 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=ec0486f0ae9c96034c41221b2a38c097a432193231ff533fd82d80e4b06312b9&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=ec0486f0ae9c96034c41221b2a38c097a432193231ff533fd82d80e4b06312b9&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]
