codeant-ai-for-open-source[bot] commented on code in PR #39469: URL: https://github.com/apache/superset/pull/39469#discussion_r3540985965
########## superset/utils/auth_db_password_hash.py: ########## @@ -0,0 +1,104 @@ +# 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. +"""Hash and verify AUTH_DB passwords using bcrypt or argon2.""" + +from __future__ import annotations + +import re +from re import Pattern + +import bcrypt +from argon2 import PasswordHasher +from argon2.exceptions import Argon2Error +from werkzeug.security import check_password_hash + +from superset.utils.auth_db_password import ( + BCRYPT_MAX_PASSWORD_BYTES, + get_auth_db_password_hash_algorithm, +) + +_BCRYPT_HASH_RE: Pattern[str] = re.compile(r"^\$2[aby]\$\d{2}\$") +_ARGON2_HASH_PREFIX: str = "$argon2" + +_argon2_hasher: PasswordHasher = PasswordHasher() + + +def is_bcrypt_password_hash(password_hash: str) -> bool: + """Return True when ``password_hash`` uses the bcrypt wire format.""" + return bool(_BCRYPT_HASH_RE.match(password_hash)) + + +def is_argon2_password_hash(password_hash: str) -> bool: + """Return True when ``password_hash`` uses the argon2 wire format.""" + return password_hash.startswith(_ARGON2_HASH_PREFIX) + + +def hash_auth_db_password(password: str, algorithm: str | None = None) -> str: + """ + Hash a plaintext password for AUTH_DB storage. + + Uses ``AUTH_DB_CONFIG["password_hash_algorithm"]`` when ``algorithm`` is omitted. + """ + resolved: str = algorithm or get_auth_db_password_hash_algorithm() + if resolved == "argon2": + return _argon2_hasher.hash(password) + if resolved == "bcrypt": + try: + encoded: bytes = password.encode("utf-8") + except UnicodeEncodeError as exc: + raise ValueError("Password cannot be encoded as UTF-8.") from exc + if len(encoded) > BCRYPT_MAX_PASSWORD_BYTES: + raise ValueError( + f"Password exceeds bcrypt's {BCRYPT_MAX_PASSWORD_BYTES}-byte limit." + ) + return bcrypt.hashpw(encoded, bcrypt.gensalt()).decode("utf-8") + raise ValueError(f"Unsupported AUTH_DB hash algorithm: {resolved}") Review Comment: **Suggestion:** The explicit `algorithm` argument is used verbatim, unlike config-derived values which are normalized in `get_auth_db_password_hash_algorithm`; passing values like `"BCRYPT"` or `" argon2 "` will incorrectly raise `ValueError` at runtime. Normalize `algorithm` with `strip().lower()` before comparison so direct callers get the same contract as config-based resolution. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ Direct hash_auth_db_password callers passing uppercase algorithm crash. - ⚠️ Inconsistent behavior versus AUTH_DB_CONFIG normalization causes confusion. - ⚠️ Future password utilities relying on explicit algorithms become fragile. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Locate the hash helper `hash_auth_db_password` in `superset/utils/auth_db_password_hash.py:50-69`, which accepts an optional `algorithm` parameter and sets `resolved: str = algorithm or get_auth_db_password_hash_algorithm()`. 2. Inspect the configuration resolver `get_auth_db_password_hash_algorithm` in `superset/utils/auth_db_password.py:15-37`, which normalizes config values with `algorithm = str(raw_algorithm).strip().lower()` before validating against `_SUPPORTED_HASH_ALGORITHMS`. 3. Note that `hash_auth_db_password` does not normalize its explicit `algorithm` argument; it only compares `resolved` directly to `"argon2"` and `"bcrypt"` (lines 57-59 in `auth_db_password_hash.py`). 4. In any calling code (for example a new helper or script) invoke `hash_auth_db_password("secret", "BCRYPT")` or `hash_auth_db_password("secret", " argon2 ")`; since `resolved` becomes `"BCRYPT"` / `" argon2 "`, neither `if resolved == "argon2"` nor `if resolved == "bcrypt"` matches, and the function raises `ValueError("Unsupported AUTH_DB hash algorithm: BCRYPT")` at line 69 instead of hashing successfully, unlike the normalized config-driven path. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=b3a1c4f9faf14977be57d53b87ca4e72&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=b3a1c4f9faf14977be57d53b87ca4e72&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_hash.py **Line:** 56:69 **Comment:** *Api Mismatch: The explicit `algorithm` argument is used verbatim, unlike config-derived values which are normalized in `get_auth_db_password_hash_algorithm`; passing values like `"BCRYPT"` or `" argon2 "` will incorrectly raise `ValueError` at runtime. Normalize `algorithm` with `strip().lower()` before comparison so direct callers get the same contract as config-based resolution. 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=e915c54b94a2adff98a69feb02e151e4891b46b26eb8970e43b3454cb630b9ca&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39469&comment_hash=e915c54b94a2adff98a69feb02e151e4891b46b26eb8970e43b3454cb630b9ca&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]
