Copilot commented on code in PR #38229:
URL: https://github.com/apache/superset/pull/38229#discussion_r2885457362


##########
superset/initialization/__init__.py:
##########
@@ -716,6 +717,10 @@ def check_and_warn_database_connection(self) -> None:
         except Exception:
             db_uri = self.database_uri
             safe_uri = make_url_safe(db_uri) if db_uri else "Not configured"
+
+            if isinstance(safe_uri, URL):
+                safe_uri = safe_uri.render_as_string(hide_password=True)
+

Review Comment:
   `check_and_warn_database_connection` can raise `DatabaseInvalidError` when 
`self.database_uri` is malformed because `make_url_safe(db_uri)` is called 
inside the exception handler without its own try/except. This can prevent the 
intended warning from being printed and can crash startup error handling. 
Consider catching `DatabaseInvalidError` (and using a safe fallback like 
"<invalid database URI>") before printing, similar to the CLI path.



##########
superset/cli/test_db.py:
##########
@@ -181,7 +182,13 @@ def collect_connection_info(
     """
     Collect ``engine_kwargs`` if needed.
     """
-    console.print(f"[green]SQLAlchemy URI: [bold]{sqlalchemy_uri}")
+    try:
+        safe_uri = make_url_safe(str(sqlalchemy_uri)).render_as_string(
+            hide_password=True
+        )
+    except (ArgumentError, DatabaseInvalidError):
+        safe_uri = "<invalid database URI>"

Review Comment:
   `make_url_safe()` already converts URL parsing failures into 
`DatabaseInvalidError`, so `ArgumentError` is unlikely to be raised from this 
block (and `sqlalchemy_uri` is coerced to `str`). Consider dropping the 
`ArgumentError` import/except and just handling `DatabaseInvalidError` to keep 
the error handling accurate.



##########
tests/unit_tests/cli/test_db_test.py:
##########
@@ -0,0 +1,74 @@
+# 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 patch
+
+from rich.console import Console
+
+from superset.cli.test_db import collect_connection_info
+from superset.commands.database.exceptions import DatabaseInvalidError
+
+
+def test_collect_connection_info_masking():
+    """Test that passwords are masked in CLI output."""
+    console = Console()
+    uri = "postgresql://user:pass@host/db"
+
+    with patch("builtins.input", return_value="n"):
+        # We need to mock sys.stdin.read because collect_connection_info might 
read it
+        with patch("sys.stdin.read", return_value="{}"):
+            with console.capture() as capture:
+                collect_connection_info(console, uri)
+
+            output = capture.get()
+            assert "user:pass@" not in output
+            assert "***" in output
+            assert "host" in output
+
+
+def test_collect_connection_info_malformed_uri():
+    """Test that malformed URIs are handled gracefully in CLI output."""
+    console = Console()
+    uri = "not-a-valid-uri"
+
+    with patch("builtins.input", return_value="n"):
+        with console.capture() as capture:
+            # We expect an exception later in collect_connection_info
+            # but the print happens first
+            try:
+                collect_connection_info(console, uri)
+            except Exception:  # noqa: S110
+                pass
+
+        output = capture.get()
+        assert "<invalid database URI>" in output

Review Comment:
   This test swallows all exceptions from `collect_connection_info` and will 
still pass as long as the output contains the placeholder, which can hide real 
regressions. Since `collect_connection_info` now handles malformed URIs and 
should not raise here, remove the broad try/except and assert on the returned 
value (e.g., `{}`) in addition to the output.
   ```suggestion
               info = collect_connection_info(console, uri)
   
           output = capture.get()
           assert "<invalid database URI>" in output
           assert info == {}
   ```



##########
superset/commands/database/test_connection.py:
##########
@@ -143,6 +144,12 @@ def run(  # noqa: C901
                 try:
                     alive = ping(engine)
                 except SupersetTimeoutException as ex:
+                    try:
+                        safe_uri = make_url_safe(
+                            str(database.sqlalchemy_uri)
+                        ).render_as_string(hide_password=True)
+                    except (ArgumentError, DatabaseInvalidError):
+                        safe_uri = "<invalid database URI>"

Review Comment:
   `make_url_safe()` wraps SQLAlchemy parsing errors and raises 
`DatabaseInvalidError`, so `ArgumentError` should not be reachable here 
(especially since the input is coerced to `str`). Removing the `ArgumentError` 
import/except would simplify the code and avoid implying a code path that 
cannot occur.



-- 
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]

Reply via email to