codeant-ai-for-open-source[bot] commented on code in PR #39469: URL: https://github.com/apache/superset/pull/39469#discussion_r3602396077
########## superset/utils/auth_db_password.py: ########## @@ -0,0 +1,265 @@ +# 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. +"""Password policy helpers for AUTH_DB (database authentication).""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from typing import Any + +from flask import current_app as app +from marshmallow import ValidationError + +# Defaults are merged with ``AUTH_DB_CONFIG`` from Flask config (partial overrides). +AUTH_DB_DEFAULTS: dict[str, Any] = { + "password_min_length": 12, + "password_require_uppercase": True, + "password_require_lowercase": True, + "password_require_digit": True, + "password_require_special": True, + "password_common_list_check": True, + "password_hash_algorithm": "bcrypt", + "reset_token_expiry_minutes": 30, + "reset_rate_limit": "5 per 15 minutes", + "login_rate_limit": "10 per 5 minutes", + "login_max_failures": 5, + "login_lockout_duration_minutes": 15, +} + +_PUBLIC_PASSWORD_POLICY_KEYS: tuple[str, ...] = ( + "password_min_length", + "password_require_uppercase", + "password_require_lowercase", + "password_require_digit", + "password_require_special", + "password_common_list_check", +) + +_SUPPORTED_HASH_ALGORITHMS: frozenset[str] = frozenset({"bcrypt", "argon2"}) + +# bcrypt silently truncates input beyond this UTF-8 byte limit. +BCRYPT_MAX_PASSWORD_BYTES: int = 72 + +_COMMON_PASSWORDS: frozenset[str] = frozenset( + password.lower() + for password in { + "password", + "password1", + "password123", + "123456", + "12345678", + "123456789", + "qwerty", + "abc123", + "monkey", + "letmein", + "trustno1", + "dragon", + "baseball", + "iloveyou", + "master", + "sunshine", + "ashley", + "bailey", + "shadow", + "superman", + "qazwsx", + "michael", + "football", + "welcome", + "jesus", + "ninja", + "mustang", + "password1!", + "admin", + "admin123", + "root", + "toor", + "guest", + "p@ssw0rd", + "Passw0rd", + "Password1", + "Password123", + "Welcome1", + "Qwerty123", + } +) + + +def get_merged_auth_db_config() -> dict[str, Any]: + """Return ``AUTH_DB_DEFAULTS`` merged with ``AUTH_DB_CONFIG`` from app config.""" + overrides: Any = app.config.get("AUTH_DB_CONFIG") or {} + if not isinstance(overrides, Mapping): + raise ValidationError( + { + "AUTH_DB_CONFIG": [ + "Invalid AUTH_DB_CONFIG. Expected a mapping of policy options." + ] + } + ) + return {**AUTH_DB_DEFAULTS, **overrides} + + +def get_auth_db_login_rate_limit_string() -> str: + """ + Return the configured AUTH_DB ``login_rate_limit`` string for Flask-Limiter. + + Used for endpoints that verify a password (for example ``PUT /api/v1/me/password``). + """ + return str( + get_merged_auth_db_config().get( + "login_rate_limit", AUTH_DB_DEFAULTS["login_rate_limit"] + ) + ) Review Comment: **Suggestion:** This coerces any configured `login_rate_limit` value to a string, which turns invalid values like `None` into the literal string `"None"` and can break Flask-Limiter parsing at request time (causing endpoint failures instead of a controlled fallback). Validate the value and fall back to the default when it is missing or malformed instead of unconditional `str(...)` coercion. [logic error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Password change endpoint 500s when login_rate_limit misconfigured. - ⚠️ Misconfigured limiter string blocks self-service password changes. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Enable request rate limiting so the password-change endpoint uses Flask-Limiter by setting `RATELIMIT_ENABLED = True` as defined in `superset/config.py:12-15`, and ensure a `limiter` instance is attached to `security_manager` (checked in `_rate_limit_me_password_change` at `superset/views/users/api.py:82-86`). 2. Configure an invalid AUTH_DB login rate limit by setting `app.config["AUTH_DB_CONFIG"]["login_rate_limit"] = None` (or another non-string/invalid object); `get_merged_auth_db_config` in `superset/utils/auth_db_password.py:104-115` merges this value without validating the `login_rate_limit` field. 3. Issue a `PUT /api/v1/me/password` request, which is handled by `CurrentUserRestApi.update_my_password` decorated with `@_rate_limit_me_password_change` at `superset/views/users/api.py:310-319`; inside the wrapper, `limiter.limit(get_auth_db_login_rate_limit_string(), key_func=_me_password_rate_limit_key, methods=["PUT"])` is called at `superset/views/users/api.py:28-32`. 4. `get_auth_db_login_rate_limit_string` at `superset/utils/auth_db_password.py:118-128` coerces the invalid `login_rate_limit` value to the literal string `"None"` via `str(...)`; when Flask-Limiter attempts to parse this string as a rate-limit expression, it raises an exception, causing the password-change request to fail with an internal error instead of applying a safe default limit or allowing the request. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=1aae2ec480114ca191b86912761f674d&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=1aae2ec480114ca191b86912761f674d&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/utils/auth_db_password.py **Line:** 124:128 **Comment:** *Logic Error: This coerces any configured `login_rate_limit` value to a string, which turns invalid values like `None` into the literal string `"None"` and can break Flask-Limiter parsing at request time (causing endpoint failures instead of a controlled fallback). Validate the value and fall back to the default when it is missing or malformed instead of unconditional `str(...)` coercion. 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%2F39469&comment_hash=453a9edf52035629c05e0400cac6c27deb8f4b10fc0acea18d0229289fcea865&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39469&comment_hash=453a9edf52035629c05e0400cac6c27deb8f4b10fc0acea18d0229289fcea865&reaction=dislike'>👎</a> ########## superset/security/manager.py: ########## @@ -4799,6 +4844,39 @@ def is_admin(self) -> bool: role.name for role in self.get_user_roles() ] + def auth_user_db(self, username: str, password: str) -> User | None: + """ + Authenticate a database user, verifying bcrypt/argon2 and legacy hashes. + """ + if username is None or username == "": + return None + first_user = self.get_first_user() + user = self.find_user(username=username) + if user is None: + user = self.find_user(email=username) + else: + # Balance failure and success + _ = self.find_user(email=username) + if user is None or (not user.is_active): + # Balance failure and success + check_password_hash( + current_app.config.get( + "AUTH_DB_FAKE_PASSWORD_HASH_CHECK", + DEFAULT_AUTH_DB_FAKE_PASSWORD_HASH_CHECK, + ), + "password", + ) Review Comment: **Suggestion:** The fake password check for unknown/inactive users always uses a Werkzeug PBKDF2 hash, while real users are now verified with bcrypt/argon2 via `verify_auth_db_password`; this creates a measurable timing difference between “user exists” and “user does not exist” paths and reintroduces username-enumeration risk. Use a fake hash generated with the same configured `AUTH_DB` algorithm (or route both paths through the same verifier) so failed-login timing stays consistent. [security] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ AUTH_DB login exposes username existence via timing side-channel. - ⚠️ Facilitates remote enumeration of valid AUTH_DB user accounts. - ⚠️ Undermines protection provided by fake password hash checks. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Observe how the security manager is wired into Superset: `superset/initialization/__init__.py:1209-1218` sets `appbuilder.security_manager_class = SupersetSecurityManager`, and `SupersetSecurityManager.register_views` in `superset/security/manager.py:4880-4887` registers `SupersetAuthView` from `superset/views/auth.py:33-42` as the `/login` view, so database logins ultimately authenticate through this manager. 2. Inspect `SupersetSecurityManager.auth_user_db` in `superset/security/manager.py:4847-4879`: when `user is None or (not user.is_active)` at line 4861, the code executes the fake password check at lines 4863-4868, calling `werkzeug.security.check_password_hash` with `current_app.config["AUTH_DB_FAKE_PASSWORD_HASH_CHECK"]` (falling back to `DEFAULT_AUTH_DB_FAKE_PASSWORD_HASH_CHECK`, a PBKDF2 hash defined at lines 125-132); when a user exists, line 4874 instead calls `verify_auth_db_password(user.password, password)`. 3. Inspect the real verifier and password algorithm defaults: `verify_auth_db_password` in `superset/utils/auth_db_password_hash.py:72-103` uses bcrypt (`bcrypt.checkpw`) when the stored hash matches the bcrypt format and argon2 (`argon2.PasswordHasher.verify`) when it starts with `"$argon2"`, only falling back to Werkzeug `check_password_hash` for legacy hashes; `superset/utils/auth_db_password.py:28-37` and `144-166` show that `AUTH_DB_CONFIG["password_hash_algorithm"]` defaults to `"bcrypt"`, so newly created AUTH_DB users will typically have bcrypt hashes. 4. Run Superset with `AUTH_TYPE = AUTH_DB` and default `AUTH_DB_CONFIG`, create an active AUTH_DB user `alice` (whose password hash will be bcrypt by default), then from an HTTP client issue repeated login attempts: (a) POST to `/login` as `alice` with an incorrect password, which drives the login stack to call `auth_user_db` and execute the bcrypt/argon2 verification path via `verify_auth_db_password`; (b) POST to `/login` with a non-existent username such as `ghost` and any password, which drives `auth_user_db` into the `user is None` branch and executes only the PBKDF2 fake hash check at `superset/security/manager.py:4863-4868`. Measuring average response times for case (a) vs case (b) over many requests will reveal a timing difference attributable to the different hash algorithms/parameters on these two failure paths, enabling remote username enumeration despite the intended fake-check mitigation. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=62579314660542fc88f5b19f8153b83a&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=62579314660542fc88f5b19f8153b83a&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/manager.py **Line:** 4863:4868 **Comment:** *Security: The fake password check for unknown/inactive users always uses a Werkzeug PBKDF2 hash, while real users are now verified with bcrypt/argon2 via `verify_auth_db_password`; this creates a measurable timing difference between “user exists” and “user does not exist” paths and reintroduces username-enumeration risk. Use a fake hash generated with the same configured `AUTH_DB` algorithm (or route both paths through the same verifier) so failed-login timing stays consistent. 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%2F39469&comment_hash=743abf14a41e927a7d0d8328854a00ffccb60a125bd204b54d95b717c2175222&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39469&comment_hash=743abf14a41e927a7d0d8328854a00ffccb60a125bd204b54d95b717c2175222&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]
