codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3509781698


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +224,99 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True
+    oauth2_exception = CustomSnowflakeAuthError
+
+    @classmethod
+    def is_oauth2_enabled(cls) -> bool:
+        """
+        Return whether OAuth2 authentication is enabled.
+        """
+
+        # When alerts or reports connect to the database in the background,
+        # OAuth2 authentication fails; therefore, OAuth2 authentication is 
disabled
+        # for background execution.
+        if not has_request_context():
+            return False
+
+        return (
+            cls.supports_oauth2
+            and cls.engine_name in app.config["DATABASE_OAUTH2_CLIENTS"]
+        )
+
+    @classmethod
+    def get_oauth2_config(cls) -> OAuth2ClientConfig | None:
+        """
+        Build the DB engine spec level OAuth2 client config.
+        """
+        if not cls.is_oauth2_enabled():
+            return None
+
+        return super().get_oauth2_config()
+
+    @classmethod
+    def impersonate_user(
+        cls,
+        database: Database,
+        username: str | None,
+        user_token: str | None,
+        url: URL,
+        engine_kwargs: dict[str, Any],
+    ) -> tuple[URL, dict[str, Any]]:
+        """
+        Modify URL and/or engine kwargs to impersonate a different user.
+        """
+        connect_args = engine_kwargs.setdefault("connect_args", {})
+
+        # When test_connection is executed (i.e., when 
validate_default_parameters is
+        # set to True in connect_args), authentication via OAuth is not 
performed.
+        if (
+            not connect_args.get("validate_default_parameters", False)
+            and cls.is_oauth2_enabled()
+        ):
+            url = url.update_query_dict({"authenticator": "oauth"})
+            connect_args["authenticator"] = "oauth"
+
+        if user_token and cls.is_oauth2_enabled():
+            if username is not None:
+                user = security_manager.find_user(username=username)
+                if user and user.email:
+                    if is_feature_enabled("IMPERSONATE_WITH_EMAIL_PREFIX"):
+                        url = url.set(username=user.email.split("@")[0])
+                    else:
+                        url = url.set(username=user.email)
+
+            url = url.update_query_dict({"token": user_token})
+

Review Comment:
   **Suggestion:** The token injection path does not check 
`validate_default_parameters`, so connection tests can still append an OAuth 
token even though OAuth auth was intentionally disabled for test-connection 
flows. If a user already has a stored OAuth token, test-connection may send 
mixed auth parameters (key-pair/password plus OAuth token) and fail 
unexpectedly. Gate token/username OAuth URL mutations behind the same 
`validate_default_parameters` condition used for setting the OAuth 
authenticator. [incorrect condition logic]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Snowflake connection tests may fail when OAuth tokens exist.
   - ⚠️ Mixed-auth parameters sent during validate/test workflows.
   - ⚠️ Admins see confusing failures testing OAuth-enabled Snowflake DBs.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Configure a Snowflake database with OAuth2 enabled and impersonation 
turned on so
   `Database.is_oauth2_enabled()` returns True 
(`superset/models/core.py:1356-1375`) and
   `SnowflakeEngineSpec.is_oauth2_enabled()` is True in a request context
   (`superset/db_engine_specs/snowflake.py:231-246`); complete an OAuth flow so 
a row exists
   in `DatabaseUserOAuth2Tokens` and `get_oauth2_access_token()` returns a 
non-empty token
   (`superset/utils/oauth2.py:88-37`).
   
   2. From the UI or API, trigger a connection validation or test (e.g.
   `/api/v1/database/test_connection`), which invokes
   `DatabaseDAO.build_db_for_connection_test()` with `impersonate_user` 
possibly True, then
   calls `database.set_sqlalchemy_uri()` followed by
   `database.db_engine_spec.mutate_db_for_connection_test(database)`
   (`superset/commands/database/test_connection.py:124-15` and
   `superset/commands/database/validate.py:95-14`), which sets
   `connect_args["validate_default_parameters"] = True` in `database.extra`
   (`superset/db_engine_specs/snowflake.py:424-18`).
   
   3. During the test, `database.get_sqla_engine()` calls `_get_sqla_engine()`
   (`superset/models/core.py:531-60`), which builds `engine_kwargs` from
   `database.get_extra()`, preserving 
`connect_args["validate_default_parameters"] = True`,
   obtains `access_token` via `get_oauth2_access_token()` 
(`superset/models/core.py:37-47`),
   and because `database.impersonate_user` is True, passes `effective_username`,
   `access_token` and `engine_kwargs` into 
`SnowflakeEngineSpec.impersonate_user()`
   (`superset/models/core.py:51-58`).
   
   4. Inside `SnowflakeEngineSpec.impersonate_user()`
   (`superset/db_engine_specs/snowflake.py:258-35`), the first `if` block 
correctly avoids
   setting `authenticator="oauth"` when 
`connect_args["validate_default_parameters"]` is
   True, but the later block at lines 282-291 (`if user_token and 
cls.is_oauth2_enabled():
   ... url = url.update_query_dict({"token": user_token})`) still injects the 
OAuth token and
   may rewrite the username, so the connection test is executed with mixed auth 
parameters
   (key-pair/password plus `token=` query param) even though OAuth usage was 
meant to be
   disabled for validation, potentially causing confusing or failing connection 
tests.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=0945c8e5c2d64a149eaddb97c5c6a850&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=0945c8e5c2d64a149eaddb97c5c6a850&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/db_engine_specs/snowflake.py
   **Line:** 282:291
   **Comment:**
        *Incorrect Condition Logic: The token injection path does not check 
`validate_default_parameters`, so connection tests can still append an OAuth 
token even though OAuth auth was intentionally disabled for test-connection 
flows. If a user already has a stored OAuth token, test-connection may send 
mixed auth parameters (key-pair/password plus OAuth token) and fail 
unexpectedly. Gate token/username OAuth URL mutations behind the same 
`validate_default_parameters` condition used for setting the OAuth 
authenticator.
   
   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%2F36856&comment_hash=c7e0577f36bc81697e78ebe2f59bbe84bcd615c7d94185a6eb3e1541974ad1a0&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=c7e0577f36bc81697e78ebe2f59bbe84bcd615c7d94185a6eb3e1541974ad1a0&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]

Reply via email to