codeant-ai-for-open-source[bot] commented on code in PR #40669: URL: https://github.com/apache/superset/pull/40669#discussion_r3400336007
########## tests/unit_tests/security/test_password_change.py: ########## @@ -0,0 +1,214 @@ +# 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. + +from unittest.mock import MagicMock, patch + +import pytest + +from superset.security.password_change import ( + _get_user_attribute, + _is_exempt_endpoint, + password_change_required, +) + + [email protected]( + "endpoint,expected", + [ + (None, True), # static file serving etc. + ("ResetMyPasswordView.this_form_get", True), + ("AuthDBView.login", True), + ("AuthDBView.logout", True), + ("appbuilder.static", True), + ("UserInfoEditView.this_form_post", True), + ("AuthOAuthView.login", True), + ("SomeBlueprint.static", True), + ("health", True), + ("SupersetIndexView.index", False), + ("Superset.dashboard", False), + # Substring over-matching must NOT exempt these (they merely share a + # substring with an exempt token). + ("AuthorView.list", False), + ("HealthDashboardView.show", False), + ("StaticAssetReportView.list", False), + ("UserInfoFancyView.show", False), + ], +) +def test_is_exempt_endpoint(endpoint, expected) -> None: Review Comment: **Suggestion:** Add explicit parameter type hints for both `endpoint` and `expected` so the new test function signature is fully typed. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This new test function has two untyped parameters, `endpoint` and `expected`, which violates the rule that new Python code should be fully typed when surrounding code is being changed. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=0c3543ec91624b958213094f679956f9&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=0c3543ec91624b958213094f679956f9&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:** tests/unit_tests/security/test_password_change.py **Line:** 51:51 **Comment:** *Custom Rule: Add explicit parameter type hints for both `endpoint` and `expected` so the new test function signature is fully typed. 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=d42bcee1477609045618babe695ed6e2bcd14e95ed3c2393d5d8ed4959136684&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=d42bcee1477609045618babe695ed6e2bcd14e95ed3c2393d5d8ed4959136684&reaction=dislike'>👎</a> ########## superset/migrations/versions/2026-06-01_00-00_b7c9d1e2f3a4_add_password_must_change.py: ########## @@ -0,0 +1,47 @@ +# 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. +"""add password_must_change to user_attribute + +Revision ID: b7c9d1e2f3a4 +Revises: f7a1c93e0b21 +Create Date: 2026-06-01 00:00:00.000000 + +""" + +import sqlalchemy as sa + +from superset.migrations.shared.utils import add_columns, drop_columns + +# revision identifiers, used by Alembic. +revision = "b7c9d1e2f3a4" +down_revision = "f7a1c93e0b21" + + +def upgrade(): Review Comment: **Suggestion:** Add an explicit return type hint to `upgrade` so the new function is fully typed. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This is a newly added Python function in a new file, and it has no parameter or return type annotations. The rule requires new Python code to be fully typed, so the suggestion identifies a real violation. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=07a95434b3af45998577b9ec0b0358d8&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=07a95434b3af45998577b9ec0b0358d8&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/migrations/versions/2026-06-01_00-00_b7c9d1e2f3a4_add_password_must_change.py **Line:** 34:34 **Comment:** *Custom Rule: Add an explicit return type hint to `upgrade` so the new function is fully typed. 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=3e4871d1dc09e590c62a90e4b088787008ce882c6cc41e29182f846181733f84&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=3e4871d1dc09e590c62a90e4b088787008ce882c6cc41e29182f846181733f84&reaction=dislike'>👎</a> ########## tests/unit_tests/security/test_password_change.py: ########## @@ -0,0 +1,214 @@ +# 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. + +from unittest.mock import MagicMock, patch + +import pytest + +from superset.security.password_change import ( + _get_user_attribute, + _is_exempt_endpoint, + password_change_required, +) + + [email protected]( + "endpoint,expected", + [ + (None, True), # static file serving etc. + ("ResetMyPasswordView.this_form_get", True), + ("AuthDBView.login", True), + ("AuthDBView.logout", True), + ("appbuilder.static", True), + ("UserInfoEditView.this_form_post", True), + ("AuthOAuthView.login", True), + ("SomeBlueprint.static", True), + ("health", True), + ("SupersetIndexView.index", False), + ("Superset.dashboard", False), + # Substring over-matching must NOT exempt these (they merely share a + # substring with an exempt token). + ("AuthorView.list", False), + ("HealthDashboardView.show", False), + ("StaticAssetReportView.list", False), + ("UserInfoFancyView.show", False), + ], +) +def test_is_exempt_endpoint(endpoint, expected) -> None: + # The password-reset / auth / static endpoints must stay reachable to avoid + # a redirect loop while a change is pending. + assert _is_exempt_endpoint(endpoint) is expected + + +def test_password_change_required() -> None: + user = MagicMock() + user.id = 5 + + with patch( + "superset.security.password_change._get_user_attribute" + ) as mock_get_attr: + mock_get_attr.return_value = MagicMock(password_must_change=True) + assert password_change_required(user) is True + + mock_get_attr.return_value = MagicMock(password_must_change=False) + assert password_change_required(user) is False + + mock_get_attr.return_value = None + assert password_change_required(user) is False + + +def test_password_change_required_no_user_id() -> None: + user = MagicMock() + user.id = None + assert password_change_required(user) is False + + +def test_get_user_attribute_deterministic_with_duplicates() -> None: + # The ``user_attribute`` table does not enforce uniqueness on ``user_id``, + # so duplicate rows are possible. The query must not raise (which + # ``.one_or_none()`` would have done via ``MultipleResultsFound``); it must + # fetch a single row deterministically via ``order_by(id).first()``. + query = MagicMock() + db = MagicMock() + db.session.query.return_value = query + query.filter.return_value = query + query.order_by.return_value = query + sentinel = MagicMock(name="first_row") + query.first.return_value = sentinel + + with ( + patch("superset.extensions.db", db), + patch("superset.models.user_attributes.UserAttribute") as user_attribute, + ): + result = _get_user_attribute(5) + + # Deterministic ordering on the primary key, then ``.first()`` — never + # ``.one_or_none()``, which could 500 on duplicate rows. + query.order_by.assert_called_once_with(user_attribute.id) + query.first.assert_called_once_with() + assert not query.one_or_none.called + assert result is sentinel + + [email protected] Review Comment: **Suggestion:** Add a return type annotation to this fixture function to keep the new function definition fully typed. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> The fixture is a newly added Python function with no return type annotation, so it violates the rule requiring new Python code to be fully typed. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6c38eda2d1be4e42b8bd07e25b70e4c7&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=6c38eda2d1be4e42b8bd07e25b70e4c7&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:** tests/unit_tests/security/test_password_change.py **Line:** 107:107 **Comment:** *Custom Rule: Add a return type annotation to this fixture function to keep the new function definition fully typed. 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=08faf87eb363a00f21c872758b732ad504364c58d30ecc71544f487a6cb1e323&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=08faf87eb363a00f21c872758b732ad504364c58d30ecc71544f487a6cb1e323&reaction=dislike'>👎</a> ########## tests/unit_tests/security/test_password_change.py: ########## @@ -0,0 +1,214 @@ +# 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. + +from unittest.mock import MagicMock, patch + +import pytest + +from superset.security.password_change import ( + _get_user_attribute, + _is_exempt_endpoint, + password_change_required, +) + + [email protected]( + "endpoint,expected", + [ + (None, True), # static file serving etc. + ("ResetMyPasswordView.this_form_get", True), + ("AuthDBView.login", True), + ("AuthDBView.logout", True), + ("appbuilder.static", True), + ("UserInfoEditView.this_form_post", True), + ("AuthOAuthView.login", True), + ("SomeBlueprint.static", True), + ("health", True), + ("SupersetIndexView.index", False), + ("Superset.dashboard", False), + # Substring over-matching must NOT exempt these (they merely share a + # substring with an exempt token). + ("AuthorView.list", False), + ("HealthDashboardView.show", False), + ("StaticAssetReportView.list", False), + ("UserInfoFancyView.show", False), + ], +) +def test_is_exempt_endpoint(endpoint, expected) -> None: + # The password-reset / auth / static endpoints must stay reachable to avoid + # a redirect loop while a change is pending. + assert _is_exempt_endpoint(endpoint) is expected + + +def test_password_change_required() -> None: + user = MagicMock() + user.id = 5 + + with patch( + "superset.security.password_change._get_user_attribute" + ) as mock_get_attr: + mock_get_attr.return_value = MagicMock(password_must_change=True) + assert password_change_required(user) is True + + mock_get_attr.return_value = MagicMock(password_must_change=False) + assert password_change_required(user) is False + + mock_get_attr.return_value = None + assert password_change_required(user) is False + + +def test_password_change_required_no_user_id() -> None: + user = MagicMock() + user.id = None + assert password_change_required(user) is False + + +def test_get_user_attribute_deterministic_with_duplicates() -> None: + # The ``user_attribute`` table does not enforce uniqueness on ``user_id``, + # so duplicate rows are possible. The query must not raise (which + # ``.one_or_none()`` would have done via ``MultipleResultsFound``); it must + # fetch a single row deterministically via ``order_by(id).first()``. + query = MagicMock() + db = MagicMock() + db.session.query.return_value = query + query.filter.return_value = query + query.order_by.return_value = query + sentinel = MagicMock(name="first_row") + query.first.return_value = sentinel + + with ( + patch("superset.extensions.db", db), + patch("superset.models.user_attributes.UserAttribute") as user_attribute, + ): + result = _get_user_attribute(5) + + # Deterministic ordering on the primary key, then ``.first()`` — never + # ``.one_or_none()``, which could 500 on duplicate rows. + query.order_by.assert_called_once_with(user_attribute.id) + query.first.assert_called_once_with() + assert not query.one_or_none.called + assert result is sentinel + + [email protected] +def enforcement_app(): + """A minimal Flask app with the enforcement hook registered and a flagged + user, used to exercise the before-request redirect behavior end to end.""" + from flask import Flask, g + + from superset.security.password_change import ( + register_password_change_enforcement, + ) + + app = Flask(__name__) + app.config["ENABLE_FORCE_PASSWORD_CHANGE"] = True + app.secret_key = "test" # noqa: S105 + + user = MagicMock() + user.id = 5 + user.is_anonymous = False + + @app.before_request + def _set_user() -> None: # pylint: disable=unused-variable + g.user = user + + # A non-exempt route that, if redirected to, would re-trigger enforcement. + @app.route("/") + def index() -> str: # pylint: disable=unused-variable + return "index" + + register_password_change_enforcement(app) + return app + + [email protected](autouse=True) +def _no_babel_flash(): + """The minimal test app has no babel/flash messaging set up; stub them so + the enforcement hook's translation + flash calls don't blow up. These are + incidental to the redirect-target logic under test.""" + with ( + patch("superset.security.password_change.flash"), + patch("superset.security.password_change.__", side_effect=lambda s: s), + ): + yield + + +def test_enforcement_redirects_to_reset_view(enforcement_app) -> None: Review Comment: **Suggestion:** Add a type hint for the `enforcement_app` parameter so this new test function has fully typed inputs. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> The new test function accepts `enforcement_app` without a type annotation, which matches the rule violation for untyped parameters in newly added Python functions. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=dbd9e12897144c7582bec349122b022d&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=dbd9e12897144c7582bec349122b022d&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:** tests/unit_tests/security/test_password_change.py **Line:** 150:150 **Comment:** *Custom Rule: Add a type hint for the `enforcement_app` parameter so this new test function has fully typed inputs. 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=fce8b2cc6675c02662fbc9a1218ceb0a3b7ccfbc02ce10f6bb76d1722f3da9af&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=fce8b2cc6675c02662fbc9a1218ceb0a3b7ccfbc02ce10f6bb76d1722f3da9af&reaction=dislike'>👎</a> ########## tests/unit_tests/security/test_password_change.py: ########## @@ -0,0 +1,214 @@ +# 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. + +from unittest.mock import MagicMock, patch + +import pytest + +from superset.security.password_change import ( + _get_user_attribute, + _is_exempt_endpoint, + password_change_required, +) + + [email protected]( + "endpoint,expected", + [ + (None, True), # static file serving etc. + ("ResetMyPasswordView.this_form_get", True), + ("AuthDBView.login", True), + ("AuthDBView.logout", True), + ("appbuilder.static", True), + ("UserInfoEditView.this_form_post", True), + ("AuthOAuthView.login", True), + ("SomeBlueprint.static", True), + ("health", True), + ("SupersetIndexView.index", False), + ("Superset.dashboard", False), + # Substring over-matching must NOT exempt these (they merely share a + # substring with an exempt token). + ("AuthorView.list", False), + ("HealthDashboardView.show", False), + ("StaticAssetReportView.list", False), + ("UserInfoFancyView.show", False), + ], +) +def test_is_exempt_endpoint(endpoint, expected) -> None: + # The password-reset / auth / static endpoints must stay reachable to avoid + # a redirect loop while a change is pending. + assert _is_exempt_endpoint(endpoint) is expected + + +def test_password_change_required() -> None: Review Comment: **Suggestion:** Add an inline docstring to this newly added test function to comply with the documentation requirement for new functions. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This newly added function has no docstring in the file state shown, so it violates the rule that new Python functions and classes should include docstrings. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=cafa7996e76d4a33a4b6228552bfdae7&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=cafa7996e76d4a33a4b6228552bfdae7&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:** tests/unit_tests/security/test_password_change.py **Line:** 57:57 **Comment:** *Custom Rule: Add an inline docstring to this newly added test function to comply with the documentation requirement for new functions. 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=dcd01834de34af4fd1bfc5d865a40d3fa8e4e11fa2ac813e6747f4567d8cbe3a&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=dcd01834de34af4fd1bfc5d865a40d3fa8e4e11fa2ac813e6747f4567d8cbe3a&reaction=dislike'>👎</a> ########## tests/unit_tests/security/test_password_change.py: ########## @@ -0,0 +1,214 @@ +# 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. + +from unittest.mock import MagicMock, patch + +import pytest + +from superset.security.password_change import ( + _get_user_attribute, + _is_exempt_endpoint, + password_change_required, +) + + [email protected]( + "endpoint,expected", + [ + (None, True), # static file serving etc. + ("ResetMyPasswordView.this_form_get", True), + ("AuthDBView.login", True), + ("AuthDBView.logout", True), + ("appbuilder.static", True), + ("UserInfoEditView.this_form_post", True), + ("AuthOAuthView.login", True), + ("SomeBlueprint.static", True), + ("health", True), + ("SupersetIndexView.index", False), + ("Superset.dashboard", False), + # Substring over-matching must NOT exempt these (they merely share a + # substring with an exempt token). + ("AuthorView.list", False), + ("HealthDashboardView.show", False), + ("StaticAssetReportView.list", False), + ("UserInfoFancyView.show", False), + ], +) +def test_is_exempt_endpoint(endpoint, expected) -> None: + # The password-reset / auth / static endpoints must stay reachable to avoid + # a redirect loop while a change is pending. + assert _is_exempt_endpoint(endpoint) is expected + + +def test_password_change_required() -> None: + user = MagicMock() + user.id = 5 + + with patch( + "superset.security.password_change._get_user_attribute" + ) as mock_get_attr: + mock_get_attr.return_value = MagicMock(password_must_change=True) + assert password_change_required(user) is True + + mock_get_attr.return_value = MagicMock(password_must_change=False) + assert password_change_required(user) is False + + mock_get_attr.return_value = None + assert password_change_required(user) is False + + +def test_password_change_required_no_user_id() -> None: + user = MagicMock() + user.id = None + assert password_change_required(user) is False + + +def test_get_user_attribute_deterministic_with_duplicates() -> None: + # The ``user_attribute`` table does not enforce uniqueness on ``user_id``, + # so duplicate rows are possible. The query must not raise (which + # ``.one_or_none()`` would have done via ``MultipleResultsFound``); it must + # fetch a single row deterministically via ``order_by(id).first()``. + query = MagicMock() + db = MagicMock() + db.session.query.return_value = query + query.filter.return_value = query + query.order_by.return_value = query + sentinel = MagicMock(name="first_row") + query.first.return_value = sentinel + + with ( + patch("superset.extensions.db", db), + patch("superset.models.user_attributes.UserAttribute") as user_attribute, + ): + result = _get_user_attribute(5) + + # Deterministic ordering on the primary key, then ``.first()`` — never + # ``.one_or_none()``, which could 500 on duplicate rows. + query.order_by.assert_called_once_with(user_attribute.id) + query.first.assert_called_once_with() + assert not query.one_or_none.called + assert result is sentinel + + [email protected] +def enforcement_app(): + """A minimal Flask app with the enforcement hook registered and a flagged + user, used to exercise the before-request redirect behavior end to end.""" + from flask import Flask, g + + from superset.security.password_change import ( + register_password_change_enforcement, + ) + + app = Flask(__name__) + app.config["ENABLE_FORCE_PASSWORD_CHANGE"] = True + app.secret_key = "test" # noqa: S105 + + user = MagicMock() + user.id = 5 + user.is_anonymous = False + + @app.before_request + def _set_user() -> None: # pylint: disable=unused-variable + g.user = user + + # A non-exempt route that, if redirected to, would re-trigger enforcement. + @app.route("/") + def index() -> str: # pylint: disable=unused-variable + return "index" + + register_password_change_enforcement(app) + return app + + [email protected](autouse=True) Review Comment: **Suggestion:** Add a return type annotation for this generator-style fixture so it complies with full typing requirements. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> This newly added generator-style fixture has no return type annotation, so it does violate the full-typing rule for new Python code. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=a8c5ebdc9b6e4efc9cefd2f48651c222&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=a8c5ebdc9b6e4efc9cefd2f48651c222&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:** tests/unit_tests/security/test_password_change.py **Line:** 138:138 **Comment:** *Custom Rule: Add a return type annotation for this generator-style fixture so it complies with full typing requirements. 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=4aa0a7dcd71ad35fef52f7bd92f6a3db90193cbd154f00fc50db64eecc1efafa&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=4aa0a7dcd71ad35fef52f7bd92f6a3db90193cbd154f00fc50db64eecc1efafa&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 + + +@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 Review Comment: **Suggestion:** Add an inline docstring to this newly added nested function to document its purpose and behavior, consistent with the requirement that new functions be documented. [custom_rule] **Severity Level:** Minor ⚠️ <details> <summary><b>Why it matters? 🤔 </b></summary> The nested function `_enforce_password_change` is newly added and does not include a docstring. The custom rule requires new Python functions and classes to be documented inline, so this is a real violation. </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b665928ec6f145798d9fd125e1453b24&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=b665928ec6f145798d9fd125e1453b24&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:** 141:141 **Comment:** *Custom Rule: Add an inline docstring to this newly added nested function to document its purpose and behavior, consistent with the requirement that new functions be documented. 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=c60cd0ec067efd51409523abaf71626a444d1207bbc86fb0671de0f6812a7caf&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40669&comment_hash=c60cd0ec067efd51409523abaf71626a444d1207bbc86fb0671de0f6812a7caf&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]
