You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "htamakos (via GitHub)" <gi...@apache.org> on 2025/12/29 15:12:14 UTC

[PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

htamakos opened a new pull request, #36856:
URL: https://github.com/apache/superset/pull/36856

   <!---
   Please write the PR title following the conventions at https://www.conventionalcommits.org/en/v1.0.0/
   Example:
   fix(dashboard): load charts correctly
   -->
   
   ### SUMMARY
   <!--- Describe the change below, including rationale and design decisions -->
   
   This PR adds OAuth2 support for user impersonation when connecting to Snowflake.
   
   Specifically, it enables OAuth-based authentication for Snowflake connections while ensuring that OAuth is not used during test_connection execution, where validate_default_parameters=True is set in connect_args. This behavior is intentional to avoid authentication failures during connection validation.
   
   The implementation is designed to be backward-compatible with existing authentication methods and does not alter the default behavior unless OAuth-related parameters are explicitly configured.
   
   ### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
   <!--- Skip this if not applicable -->
   
   <img width="1464" height="827" alt="image" src="https://github.com/user-attachments/assets/57636ee4-4106-4a78-87ce-37a0f2efcbdf" />
   <img width="1468" height="826" alt="image" src="https://github.com/user-attachments/assets/3ac1e853-a570-431f-b91b-2e9054dc8b36" />
   <img width="1454" height="814" alt="image" src="https://github.com/user-attachments/assets/f520e418-b70d-48a0-a7dd-b8d5b6b996c0" />
   
   
   ### TESTING INSTRUCTIONS
   <!--- Required! What steps can be taken to manually verify the changes? -->
   
   1. Set up OAuth integration in Snowflake
   
   Create a Snowflake security integration for OAuth:
   
   ```sql
   CREATE SECURITY INTEGRATION test_superset
       TYPE = OAUTH
       ENABLED = TRUE
       OAUTH_CLIENT = CUSTOM
       OAUTH_CLIENT_TYPE = 'CONFIDENTIAL'
       OAUTH_USE_SECONDARY_ROLES = 'IMPLICIT'
       OAUTH_ALLOW_NON_TLS_REDIRECT_URI = TRUE
       OAUTH_REDIRECT_URI = 'http://localhost:8088/api/v1/database/oauth2/';
   ```
   
   Retrieve the client_id and client_secret generated for this integration.
   
   2. Configure OAuth2 settings in superset_config.py
   
   Add the Snowflake OAuth2 configuration and enable the IMPERSONATE_WITH_EMAIL_PREFIX feature flag:
   
   ```python
   DATABASE_OAUTH2_CLIENTS = {
       "Snowflake": {
           "id": "<client_id from test_superset integration>",
           "secret": "<client_secret from test_superset integration>",
           "scope": " ".join(
               [
                   "refresh_token",
               ],
           ),
           "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
           "authorization_request_uri": "https://<snowflake account>.snowflakecomputing.com/oauth/authorize",
           "token_request_uri": "https://<snowflake account>.snowflakecomputing.com/oauth/token-request",
       },
   }
   
   DATABASE_OAUTH2_JWT_ALGORITHM = "HS256"
   DATABASE_OAUTH2_REDIRECT_URI = "http://localhost:8088/api/v1/database/oauth2/"
   DATABASE_OAUTH2_TIMEOUT = timedelta(seconds=30)
   
   FEATURE_FLAGS = {"IMPERSONATE_WITH_EMAIL_PREFIX": True}
   ```
   
   Restart Superset to apply the configuration.
   
   3. Configure the database in the Superset UI
   
   In Data โ†’ Databases, create or edit a Snowflake database with the following settings:
   
   - Key Pair Authentication
   - Impersonate user: true
   
   Save the database configuration.
   
   4. Verification
   
   - Execute queries as a logged-in user and confirm that authentication is performed via OAuth2 with user impersonation.
   - Run Test Connection for the database and verify that:
     - The connection test succeeds.
     - OAuth authentication is not attempted during test_connection.
   
   ### ADDITIONAL INFORMATION
   <!--- Check any relevant boxes with "x" -->
   <!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->
   - [ ] Has associated issue: https://github.com/apache/superset/issues/20300
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
     - [ ] Migration is atomic, supports rollback & is backwards-compatible
     - [ ] Confirm DB migration upgrade and downgrade tested
     - [ ] Runtime estimates and downtime expectations provided
   - [ ] Introduces new feature or API
   - [ ] Removes existing feature or API
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564855626


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +242,105 @@ 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: dict[str, Any] = 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 database.is_oauth2_enabled()
+        ):

Review Comment:
   **Suggestion:** The OAuth enablement gate here relies on `database.is_oauth2_enabled()`, which still returns true for database-level OAuth client config even without a request/user context. In background executions (alerts/reports), this makes Snowflake switch to OAuth auth without a user token, causing connection failures instead of the intended non-OAuth fallback. Add an explicit request/user-context guard in this condition before enabling OAuth impersonation. [incorrect condition logic]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ Background Snowflake connections use OAuth without user token.
   - โŒ Scheduled exports/commands can fail authenticating to Snowflake.
   - โš ๏ธ Alerts/reports against Snowflake risk intermittent auth failures.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Configure a Snowflake database with OAuth2 client info stored in `encrypted_extra`, so
   `Database.get_oauth2_config()` in `superset/models/core.py:23-31` returns a non-None
   config and `Database.is_oauth2_enabled()` at `superset/models/core.py:6-21` evaluates to
   True.
   
   2. Enable user impersonation on that database (`database.impersonate_user = True`), so
   `Database._get_sqla_engine()` in `superset/models/core.py:15-22` will call
   `self.db_engine_spec.impersonate_user(...)` when building engines.
   
   3. Execute code that uses `database.get_sqla_engine()` outside a Flask request context (no
   `g.user`), for example via the streaming export command at
   `superset/commands/streaming_export/base.py:226` which calls
   `merged_database.get_sqla_engine(...)` to run SQL against Snowflake.
   
   4. In `_get_sqla_engine()` (`superset/models/core.py:42-58`), `oauth2_config =
   self.get_oauth2_config()` succeeds but `access_token` is computed only when
   `oauth2_config` and `g.user.id` are present, so in this background context `access_token`
   (passed as `user_token`) is None. `impersonate_user()` at
   `superset/db_engine_specs/snowflake.py:31-51` then evaluates `if (not
   connect_args.get("validate_default_parameters", False) and database.is_oauth2_enabled())`
   true because `database.is_oauth2_enabled()` uses DB-level config without checking
   `has_request_context()`. The method sets `authenticator="oauth"` on the URL and
   `connect_args` but, since `user_token` is None, does not add a `token` query parameter.
   Subsequent engine creation in `_get_sqla_engine()` (`create_engine(sqlalchemy_url,
   **engine_kwargs)` at `superset/models/core.py:105-107`) attempts a Snowflake OAuth
   connection with no token, leading to authentication failures instead of the intended
   non-OAuth fallback for background execution.
   ```
   </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=f3c92f600fa8483da98764acae98c438&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=f3c92f600fa8483da98764acae98c438&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:** 292:295
   **Comment:**
   	*Incorrect Condition Logic: The OAuth enablement gate here relies on `database.is_oauth2_enabled()`, which still returns true for database-level OAuth client config even without a request/user context. In background executions (alerts/reports), this makes Snowflake switch to OAuth auth without a user token, causing connection failures instead of the intended non-OAuth fallback. Add an explicit request/user-context guard in this condition before enabling OAuth impersonation.
   
   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=ec8839461aae769d563192d08f20dc110e71249a2671dbfef07c96f5df837730&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=ec8839461aae769d563192d08f20dc110e71249a2671dbfef07c96f5df837730&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4967133493

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5209395048

   Turns out it wasn't a flake. fetch_data only sets g.bq_memory_limited when has_request_context() is true, which never holds in unit tests, so the assertions were failing deterministically. Patched that in the test and all 44 in test_bigquery.py pass now. Pushed.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3478666691


##########
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"]
+        )

Review Comment:
   **Suggestion:** The OAuth2 enablement check only looks at `DATABASE_OAUTH2_CLIENTS`, but Snowflake OAuth2 can also be configured per-database in encrypted extra. This makes OAuth2 appear configured (token retrieval path runs) while `impersonate_user` still treats it as disabled, so OAuth authentication is never applied for database-level client configs. Use a database-aware check (or pass `database.is_oauth2_enabled()` into this flow) instead of a class-level global-config-only gate. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ Snowflake OAuth per-database config fails to apply.
   - โš ๏ธ User impersonation tokens retrieved but never used.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Configure a Snowflake Database with per-database OAuth2 client info in
   `encrypted_extra["oauth2_client_info"]` (parsed in `Database.get_oauth2_config()` at
   `superset/models/core.py:33-41`) and do NOT add `"Snowflake"` to
   `app.config["DATABASE_OAUTH2_CLIENTS"]`.
   
   2. Observe `Database.is_oauth2_enabled()` at `superset/models/core.py:7-22` returns True
   because `get_oauth2_config()` finds the per-database config, while
   `SnowflakeEngineSpec.is_oauth2_enabled()` at
   `superset/db_engine_specs/snowflake.py:231-246` returns False (it only checks
   `DATABASE_OAUTH2_CLIENTS`).
   
   3. Run an interactive query (SQL Lab/dashboard) so `Database.get_sqla_engine()` at
   `superset/models/core.py:10-88` calls `_get_sqla_engine()`; `_get_sqla_engine()` at
   `superset/models/core.py:89-132` retrieves an OAuth2 access token via
   `get_oauth2_access_token()` when a token exists and then calls
   `self.db_engine_spec.impersonate_user(...)` at `superset/models/core.py:136-140`.
   
   4. In `SnowflakeEngineSpec.impersonate_user()` at
   `superset/db_engine_specs/snowflake.py:259-293`, both the authenticator switch and token
   injection are gated on `cls.is_oauth2_enabled()`, so for databases configured only via
   `encrypted_extra` the OAuth authenticator and `token` query parameter are never applied
   even though tokens are present, resulting in connections that continue using non-OAuth
   authentication.
   ```
   </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=945734d7fb9846ee99e4af2976d63b3c&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=945734d7fb9846ee99e4af2976d63b3c&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:** 243:246
   **Comment:**
   	*Api Mismatch: The OAuth2 enablement check only looks at `DATABASE_OAUTH2_CLIENTS`, but Snowflake OAuth2 can also be configured per-database in encrypted extra. This makes OAuth2 appear configured (token retrieval path runs) while `impersonate_user` still treats it as disabled, so OAuth authentication is never applied for database-level client configs. Use a database-aware check (or pass `database.is_oauth2_enabled()` into this flow) instead of a class-level global-config-only gate.
   
   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=4cb0ef6f25361dff6b802619b1e58ee6105fb04ec310a9e86de86d04158ecb6f&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=4cb0ef6f25361dff6b802619b1e58ee6105fb04ec310a9e86de86d04158ecb6f&reaction=dislike'>๐Ÿ‘Ž</a>



##########
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})
+
+        return url, engine_kwargs
+
+    @classmethod
+    def get_oauth2_authorization_uri(
+        cls,
+        config: OAuth2ClientConfig,
+        state: OAuth2State,
+        code_verifier: str | None = None, # pylint: disable=unused-argument
+    ) -> str:
+        """
+        Return URI for initial OAuth2 request.
+        """
+        uri = config["authorization_request_uri"]
+        # When calling the Snowflake OAuth authorization endpoint for a custom client,
+        # specify only the query parameters documented in the URL below.
+        # Adding unsupported parameters
+        # (e.g., `prompt` as used in BaseEngineSpec.get_oauth2_authorization_uri)
+        # will cause an error.
+        # https://docs.snowflake.com/user-guide/oauth-custom#query-parameters
+        params = {
+            "scope": config["scope"],
+            "response_type": "code",
+            "state": encode_oauth2_state(state),
+            "redirect_uri": config["redirect_uri"],
+            "client_id": config["id"],
+        }
+        return parse.urljoin(uri, "?" + parse.urlencode(params))

Review Comment:
   **Suggestion:** The authorization URL override ignores `code_verifier` and omits PKCE `code_challenge`, but the shared callback flow still forwards `code_verifier` to token exchange. This creates a PKCE contract mismatch where token exchange may fail because the authorization request did not include matching PKCE parameters. Either include PKCE challenge parameters here or override token exchange to avoid sending `code_verifier` for Snowflake. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ Snowflake OAuth flow may fail due to PKCE mismatch.
   - โš ๏ธ Users may be unable to authorize Snowflake access.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Start an OAuth2 flow for a Snowflake database (e.g., from SQL Lab) so
   `Database.get_sqla_engine()` at `superset/models/core.py:52-61` runs inside
   `check_for_oauth2()` (`superset/utils/oauth2.py:11-20`); when a Snowflake-specific OAuth
   error is raised, `database.db_engine_spec.start_oauth2_dance(database)` is invoked via
   `BaseEngineSpec.needs_oauth2()` at `superset/db_engine_specs/base.py:2195-2202`.
   
   2. `BaseEngineSpec.start_oauth2_dance()` at `superset/db_engine_specs/base.py:11-83`
   generates a PKCE `code_verifier`, stores it in the KV store, builds an `OAuth2State`, and
   then calls `cls.get_oauth2_authorization_uri(oauth2_config, state,
   code_verifier=code_verifier)`.
   
   3. For Snowflake, the override `SnowflakeEngineSpec.get_oauth2_authorization_uri()` at
   `superset/db_engine_specs/snowflake.py:295-318` ignores the `code_verifier` argument
   (marked `# pylint: disable=unused-argument`) and builds the authorization URL without
   `code_challenge` or `code_challenge_method`, even though PKCE was initiated upstream.
   
   4. After the user authorizes, the callback in `commands/database/oauth2.py:17-39` loads
   `code_verifier` from the KV store and passes it to `BaseEngineSpec.get_oauth2_token()` at
   `superset/db_engine_specs/base.py:31-57`, which unconditionally includes `code_verifier`
   in the token request body; this creates a mismatch where the token request uses PKCE
   parameters but the authorization request did not supply a matching challenge, risking
   token exchange failures with Snowflake's OAuth provider.
   ```
   </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=d1d20cfdee42406c99816f3550194d98&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=d1d20cfdee42406c99816f3550194d98&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:** 295:318
   **Comment:**
   	*Api Mismatch: The authorization URL override ignores `code_verifier` and omits PKCE `code_challenge`, but the shared callback flow still forwards `code_verifier` to token exchange. This creates a PKCE contract mismatch where token exchange may fail because the authorization request did not include matching PKCE parameters. Either include PKCE challenge parameters here or override token exchange to avoid sending `code_verifier` for Snowflake.
   
   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=48a24dbfd6c37548ded1940d945e240abd13166417cd325c3f22651da3a296f2&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=48a24dbfd6c37548ded1940d945e240abd13166417cd325c3f22651da3a296f2&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3699936790

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4921723130

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3686029936


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -440,6 +605,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connect_args: dict[str, Any] = params.get("connect_args") or {}
+        if connect_args.get("authenticator") == "oauth":
+            return

Review Comment:
   โœ… **Customized review instruction saved!**
   
   **Instruction:**
   > When reviewing Snowflake authentication parameter loading, account for impersonate_user setting connect_args["authenticator"] to "oauth" before encrypted-extra loading; do not require this function to inspect the SQLAlchemy URL query string.
   
   **Applied to:**
     - `superset/db_engine_specs/snowflake.py`
   
   ---
   ๐Ÿ’ก *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5185814142

   Only failing check is unit-tests-required, and that's red on BigQuery memory-limit assertions, nothing to do with the Snowflake OAuth changes here. Rerunning to confirm before merging โ€” already approved otherwise, and the CodeAnt threads all look worked through.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3651457507


##########
superset-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx:
##########
@@ -522,7 +522,7 @@ const ExtraOptions = ({
                     onChange={onInputChange}
                   >
                     {t(
-                      'Impersonate logged in user (Presto, Trino, Drill, Hive, and Google Sheets)',
+                      'Impersonate logged in user (Presto, Trino, Drill, Hive, Snowflake and Google Sheets)',

Review Comment:
   โœ… **Customized review instruction saved!**
   
   **Instruction:**
   > Do not flag caching or cache-key security issues for tooltip or label-only changes; review those concerns in the caching implementation instead.
   
   **Applied to:**
     - `superset-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx`
   
   ---
   ๐Ÿ’ก *To manage or update this instruction, visit: [CodeAnt AI Settings](https://app.codeant.ai/org/settings/learnings)*



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5051220596

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5210671051

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3725354564

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/36856?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `50.00000%` with `26 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 48.53%. Comparing base ([`c026ae2`](https://app.codecov.io/gh/apache/superset/commit/c026ae2ce712126fd009681b36dfd47124567f0b?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`7a210c6`](https://app.codecov.io/gh/apache/superset/commit/7a210c66b82b5e989d7891173968dca00ccbbe5a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   :warning: Report is 72 commits behind head on master.
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/36856?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/db\_engine\_specs/snowflake.py](https://app.codecov.io/gh/apache/superset/pull/36856?src=pr&el=tree&filepath=superset%2Fdb_engine_specs%2Fsnowflake.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvZGJfZW5naW5lX3NwZWNzL3Nub3dmbGFrZS5weQ==) | 50.00% | [26 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/36856?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@             Coverage Diff             @@
   ##           master   #36856       +/-   ##
   ===========================================
   + Coverage        0   48.53%   +48.53%     
   ===========================================
     Files           0      639      +639     
     Lines           0    47652    +47652     
     Branches        0     5203     +5203     
   ===========================================
   + Hits            0    23128    +23128     
   - Misses          0    23869    +23869     
   - Partials        0      655      +655     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/36856/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage ฮ” | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/36856/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `43.13% <50.00%> (?)` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/36856/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `46.73% <50.00%> (?)` | |
   | [python](https://app.codecov.io/gh/apache/superset/pull/36856/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `48.53% <50.00%> (?)` | |
   | [unit](https://app.codecov.io/gh/apache/superset/pull/36856/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `100.00% <รธ> (?)` | |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/36856?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3573311931


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,61 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        """
+        Match Snowflake's invalid/expired OAuth token error, whether it arrives
+        wrapped by SQLAlchemy (e.g. ``Engine``-based execution) or as the raw
+        DBAPI exception โ€” ``BaseEngineSpec.execute()`` runs against a bare
+        cursor and never wraps it, so both shapes must be handled here.
+        """
+        orig: object = instance
+        if isinstance(instance, SqlalchemyDatabaseError):
+            orig = cast(SqlalchemyDatabaseError, instance).orig
+
+        return isinstance(orig, DatabaseError) and "Invalid OAuth access token" in str(
+            orig
+        )

Review Comment:
   **Suggestion:** Storing the OAuth access token in the SQLAlchemy URL makes the engine cache key token-dependent (the cache key includes `str(sqlalchemy_url)`), so token refreshes create new cached engines indefinitely and can cause unbounded engine/pool growth. Keep the URL stable and pass the token via connection arguments (or otherwise exclude it from engine cache key material) so refreshed tokens do not create new engine cache entries. [cache]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ SQL Lab queries create new engines on each token refresh.
   - โŒ Dashboard queries against Snowflake grow engine cache unbounded.
   - โš ๏ธ Background jobs using Snowflake OAuth may exhaust process memory.
   - โš ๏ธ Connection pooling becomes ineffective due to fragmented engine cache.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Configure a Snowflake database in Superset using `SnowflakeEngineSpec` (class at
   `superset/db_engine_specs/snowflake.py:135`) with `impersonate_user=True` and an OAuth2
   client so that `database.is_oauth2_enabled()` returns True for this database.
   
   2. From SQL Lab, run a query against this Snowflake database so that
   `query.database.get_sqla_engine()` is invoked (call site `superset/sql_lab.py:23-27`),
   which enters `Database.get_sqla_engine()` at `superset/models/core.py:455`.
   
   3. Inside `Database.get_sqla_engine()`, `_get_sqla_engine()` is called (definition around
   `superset/models/core.py:654`), which computes an `access_token` via
   `get_oauth2_access_token(...)` and then, when `self.impersonate_user` is True, calls
   `self.db_engine_spec.impersonate_user(...)` (lines `superset/models/core.py:22-29` in the
   second snippet), passing `sqlalchemy_url` and `engine_kwargs`.
   
   4. In `SnowflakeEngineSpec.impersonate_user()` (method at
   `superset/db_engine_specs/snowflake.py:58-99`), when `user_token` is present and OAuth2 is
   enabled, the URL is mutated to include the token: `url = url.update_query_dict({"token":
   user_token})` (line 97), and both the modified `url` and `engine_kwargs` (with
   `connect_args["authenticator"] = "oauth"`) are returned.
   
   5. Back in `_get_sqla_engine()`, the per-process engine cache key is computed as
   `(self.id, str(sqlalchemy_url), repr(sorted(engine_kwargs.items())))` (cache-key
   construction around `superset/models/core.py:616-621`), so the stringified URLโ€”including
   its `token` query parameterโ€”is part of the cache key.
   
   6. When the OAuth access token is refreshed (for the same user or for different users),
   `SnowflakeEngineSpec.impersonate_user()` again executes `url.update_query_dict({"token":
   user_token})` with the new token value, changing `str(sqlalchemy_url)` while `self.id` and
   most `engine_kwargs` stay the same.
   
   7. Because `str(sqlalchemy_url)` changes on every token refresh, `_ENGINE_CACHE` in
   `superset/models/core.py` treats each token value as a distinct entry, calls
   `create_engine(sqlalchemy_url, **engine_kwargs)` for each new token, and stores the new
   engine without ever evicting the old one, leading to unbounded growth of cached engines
   for a single Snowflake database under normal interactive query activity.
   ```
   </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=c1baa1b396cc447cbf9078f8a4f9e1fa&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=c1baa1b396cc447cbf9078f8a4f9e1fa&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:** 97:97
   **Comment:**
   	*Cache: Storing the OAuth access token in the SQLAlchemy URL makes the engine cache key token-dependent (the cache key includes `str(sqlalchemy_url)`), so token refreshes create new cached engines indefinitely and can cause unbounded engine/pool growth. Keep the URL stable and pass the token via connection arguments (or otherwise exclude it from engine cache key material) so refreshed tokens do not create new engine cache entries.
   
   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=a1be5120c4dfc07eda519aed281de566afddcaacda64ee0f56853c2b146c26d9&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=a1be5120c4dfc07eda519aed281de566afddcaacda64ee0f56853c2b146c26d9&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4961557815

   Running CI, but noting the last review comment flagged as "critical"


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564846770


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +242,105 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True
+    oauth2_exception = CustomSnowflakeAuthError

Review Comment:
   **Suggestion:** Annotate this new class attribute with an explicit type so the OAuth exception contract is type-safe and compliant with the required type-hint rule. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This newly added class attribute is assigned without an explicit type hint even though it can be annotated. The rule requires type hints on relevant variables in modified Python code, so this is a real violation.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=36ea55db3e1d41d59f7dd5cbd8b5ea13&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=36ea55db3e1d41d59f7dd5cbd8b5ea13&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:** 247:247
   **Comment:**
   	*Custom Rule: Annotate this new class attribute with an explicit type so the OAuth exception contract is type-safe and compliant with the required type-hint rule.
   
   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=0796ce85abc86ad45e0c42f5590dc6ea9477b2c6d30c22ed162166c745d74dad&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=0796ce85abc86ad45e0c42f5590dc6ea9477b2c6d30c22ed162166c745d74dad&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +242,105 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True

Review Comment:
   **Suggestion:** Add an explicit type annotation for this new class-level flag to satisfy the type-hint requirement for newly introduced relevant variables. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This new class-level flag is a relevant variable that can be annotated, and it is introduced without an explicit type hint. That matches the type-hint rule for modified Python code.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=b817f9de9874425b8464fd6b5bf8ee86&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=b817f9de9874425b8464fd6b5bf8ee86&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:** 246:246
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this new class-level flag to satisfy the type-hint requirement for newly introduced relevant variables.
   
   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=bfd48b83b86367bcd69abe403f604486f2645e3e977a5129f3debae6b1314e9d&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=bfd48b83b86367bcd69abe403f604486f2645e3e977a5129f3debae6b1314e9d&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database = Database(sqlalchemy_uri="snowflake://abc")
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.SnowflakeEngineSpec.is_oauth2_enabled",
+        return_value=True,
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={
+            "connect_args": {
+                "validate_default_parameters": True,
+            },
+        },
+    ) == (
+        make_url("snowflake://user:pass@account/database_name/default"),
+        {"connect_args": {"validate_default_parameters": True}},
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://user:pass@account/database_name/default?authenticator=oauth"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.is_feature_enabled",
+        return_value=True,
+    )
+
+    mocker.patch(
+        "superset.security_manager.find_user",
+        return_value=mocker.MagicMock(email="impersonated_user@example.com"),
+    )
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username="impersonated_user",
+        user_token="test_token",  # noqa: S106
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://impersonated_user:pass@account/database_name/default?authenticator=oauth&token=test_token"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+
+def test_custom_snowflake_auth_error_matches_raw_dbapi_exception() -> None:
+    """
+    `BaseEngineSpec.execute()` runs against a bare DBAPI cursor, so the
+    exception it sees is the raw Snowflake error, never wrapped by
+    SQLAlchemy. `CustomSnowflakeAuthError` must still recognize it so the
+    OAuth2 re-auth dance triggers for SQL Lab queries.
+    """
+    from superset.db_engine_specs.snowflake import (
+        CustomSnowflakeAuthError,
+        DatabaseError,
+    )
+
+    raw_error = DatabaseError("250001: Invalid OAuth access token.")

Review Comment:
   **Suggestion:** Annotate this local exception instance with its concrete type to align with the rule requiring type hints on relevant variables. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This new local variable is a concrete exception instance and is left untyped in the added code, which matches the rule requiring type hints on relevant variables.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=30742b3d58a142159c2c1996de6951c5&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=30742b3d58a142159c2c1996de6951c5&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/db_engine_specs/test_snowflake.py
   **Line:** 575:575
   **Comment:**
   	*Custom Rule: Annotate this local exception instance with its concrete type to align with the rule requiring type hints on relevant variables.
   
   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=39aee2f14226ba27147e562a4669980effe7ebc03d6a0e0cb7d9accd812846b0&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=39aee2f14226ba27147e562a4669980effe7ebc03d6a0e0cb7d9accd812846b0&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database = Database(sqlalchemy_uri="snowflake://abc")
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.SnowflakeEngineSpec.is_oauth2_enabled",
+        return_value=True,
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={
+            "connect_args": {
+                "validate_default_parameters": True,
+            },
+        },
+    ) == (
+        make_url("snowflake://user:pass@account/database_name/default"),
+        {"connect_args": {"validate_default_parameters": True}},
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://user:pass@account/database_name/default?authenticator=oauth"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.is_feature_enabled",
+        return_value=True,
+    )
+
+    mocker.patch(
+        "superset.security_manager.find_user",
+        return_value=mocker.MagicMock(email="impersonated_user@example.com"),
+    )
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username="impersonated_user",
+        user_token="test_token",  # noqa: S106
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://impersonated_user:pass@account/database_name/default?authenticator=oauth&token=test_token"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+
+def test_custom_snowflake_auth_error_matches_raw_dbapi_exception() -> None:
+    """
+    `BaseEngineSpec.execute()` runs against a bare DBAPI cursor, so the
+    exception it sees is the raw Snowflake error, never wrapped by
+    SQLAlchemy. `CustomSnowflakeAuthError` must still recognize it so the
+    OAuth2 re-auth dance triggers for SQL Lab queries.
+    """
+    from superset.db_engine_specs.snowflake import (
+        CustomSnowflakeAuthError,
+        DatabaseError,
+    )
+
+    raw_error = DatabaseError("250001: Invalid OAuth access token.")
+    assert isinstance(raw_error, CustomSnowflakeAuthError)
+
+
+def test_custom_snowflake_auth_error_matches_sqlalchemy_wrapped_exception() -> None:
+    """
+    Some call sites execute through SQLAlchemy's `Engine`, which wraps the
+    original DBAPI exception in `sqlalchemy.exc.DatabaseError.orig`.
+    `CustomSnowflakeAuthError` must keep matching this shape too.
+    """
+    from sqlalchemy.exc import DatabaseError as SqlalchemyDatabaseError
+
+    from superset.db_engine_specs.snowflake import (
+        CustomSnowflakeAuthError,
+        DatabaseError,
+    )
+
+    wrapped_error = SqlalchemyDatabaseError(
+        statement="SELECT 1",
+        params=None,
+        orig=DatabaseError("250001: Invalid OAuth access token."),
+    )

Review Comment:
   **Suggestion:** Add an explicit type annotation for this wrapped SQLAlchemy error variable to meet the mandatory typing requirement. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This added local variable is also unannotated even though it is a concrete exception object, so it satisfies the custom typing ruleโ€™s criteria for a missing type hint.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=f69971e5b7d14a4981309c5c688fa35e&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=f69971e5b7d14a4981309c5c688fa35e&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/db_engine_specs/test_snowflake.py
   **Line:** 592:596
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this wrapped SQLAlchemy error variable to meet the mandatory typing requirement.
   
   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=5be3596aedc04a0e91f3bf55ee50ac31eef36dbf36d26ec938561203ae4a2eaf&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=5be3596aedc04a0e91f3bf55ee50ac31eef36dbf36d26ec938561203ae4a2eaf&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")

Review Comment:
   **Suggestion:** Add an explicit type annotation for this mocked request client variable to comply with the required typing rule for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This is new Python code that introduces a local variable without a type hint, and the rule explicitly requires type hints for relevant variables that can be annotated.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=60dcc0c3e040499682897d9de8c412c7&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=60dcc0c3e040499682897d9de8c412c7&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/db_engine_specs/test_snowflake.py
   **Line:** 469:469
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this mocked request client variable to comply with the required typing rule for relevant variables.
   
   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=49c47b1f5404d125f4a4014d8257684b9b15cf3d8c098d87185113842c1c9890&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=49c47b1f5404d125f4a4014d8257684b9b15cf3d8c098d87185113842c1c9890&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database = Database(sqlalchemy_uri="snowflake://abc")

Review Comment:
   **Suggestion:** Add a type annotation to this local database object so the new code satisfies the type-hint requirement for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This modified test adds a new local variable without an annotation. Since the variable is a concrete `Database` instance, it can be type-annotated and falls under the typing rule.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=ac262725827b4142807fcb0f95532a9e&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=ac262725827b4142807fcb0f95532a9e&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/db_engine_specs/test_snowflake.py
   **Line:** 505:505
   **Comment:**
   	*Custom Rule: Add a type annotation to this local database object so the new code satisfies the type-hint requirement for relevant variables.
   
   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=a8cba63764709e32aa4c815f5cc8a58d1d689529c10d706b30f0e2bde40a81ee&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=a8cba63764709e32aa4c815f5cc8a58d1d689529c10d706b30f0e2bde40a81ee&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3509766654


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +224,99 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True

Review Comment:
   **Suggestion:** Add an explicit type annotation to this new class attribute so its boolean intent is declared. [custom_rule]
   
   **Severity Level:** Minor โš ๏ธ
   <details>
   <summary><b>Why it matters? ๐Ÿค” </b></summary>
   
   This is a newly introduced class attribute that represents a boolean setting, and it is not type annotated. That matches the type-hint rule for newly added Python variables that can be annotated.
   </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=b675211c267b4bf882893727f0549072&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=b675211c267b4bf882893727f0549072&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:** 227:228
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to this new class attribute so its boolean intent is declared.
   
   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=787f63331bc887cea7c30a7f188ea5e541026e00b89e64866ea9a164da0afa4c&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=787f63331bc887cea7c30a7f188ea5e541026e00b89e64866ea9a164da0afa4c&reaction=dislike'>๐Ÿ‘Ž</a>



##########
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", {})

Review Comment:
   **Suggestion:** Annotate this newly introduced local variable with its dictionary type to satisfy type-hint requirements for relevant variables. [custom_rule]
   
   **Severity Level:** Minor โš ๏ธ
   <details>
   <summary><b>Why it matters? ๐Ÿค” </b></summary>
   
   This newly added local variable is a dictionary-like container and is not annotated, even though the function signature uses typed parameters. That is a real omission under the type-hint rule.
   </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=7cfe5918d29040579b0ce77a587a4f32&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=7cfe5918d29040579b0ce77a587a4f32&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:** 270:270
   **Comment:**
   	*Custom Rule: Annotate this newly introduced local variable with its dictionary type to satisfy type-hint requirements for relevant variables.
   
   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=a7171cf206af1ed1869a39b2398f9ad64981c722b2409bc3095ff5522e7df93b&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=a7171cf206af1ed1869a39b2398f9ad64981c722b2409bc3095ff5522e7df93b&reaction=dislike'>๐Ÿ‘Ž</a>



##########
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})
+
+        return url, engine_kwargs
+
+    @classmethod
+    def get_oauth2_authorization_uri(
+        cls,
+        config: OAuth2ClientConfig,
+        state: OAuth2State,
+        code_verifier: str | None = None,  # pylint: disable=unused-argument
+    ) -> str:
+        """
+        Return URI for initial OAuth2 request.
+        """
+        uri = config["authorization_request_uri"]
+        # When calling the Snowflake OAuth authorization endpoint for a custom client,
+        # specify only the query parameters documented in the URL below.
+        # Adding unsupported parameters
+        # (e.g., `prompt` as used in BaseEngineSpec.get_oauth2_authorization_uri)
+        # will cause an error.
+        # https://docs.snowflake.com/user-guide/oauth-custom#query-parameters
+        params = {
+            "scope": config["scope"],
+            "response_type": "code",
+            "state": encode_oauth2_state(state),
+            "redirect_uri": config["redirect_uri"],
+            "client_id": config["id"],
+        }

Review Comment:
   **Suggestion:** Add an explicit type annotation to this new local mapping variable so its key/value types are clear. [custom_rule]
   
   **Severity Level:** Minor โš ๏ธ
   <details>
   <summary><b>Why it matters? ๐Ÿค” </b></summary>
   
   This is a newly introduced local dictionary with no type annotation. It is a relevant variable that can be annotated, so it matches the type-hint rule.
   </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=3f5693a96fbd4498becddc2510031f97&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=3f5693a96fbd4498becddc2510031f97&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:** 311:317
   **Comment:**
   	*Custom Rule: Add an explicit type annotation to this new local mapping variable so its key/value types are clear.
   
   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=216f147fdb2ee8ff809eb69d4345a3d041b2879af7655a3e688c04b300dd7281&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=216f147fdb2ee8ff809eb69d4345a3d041b2879af7655a3e688c04b300dd7281&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4861232235

   @htamakos would you ming scoping out the bot review comments to see if they're worth addressing?


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "htamakos (via GitHub)" <gi...@apache.org>.
htamakos commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5406526809

   @rusackas 
   Glad the PR is merged! Thanks a ton for all your help!


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r2651188849


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -135,6 +161,71 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True
+    oauth2_exception = CustomSnowflakeAuthError
+
+    @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:
+            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})
+
+        return url, engine_kwargs
+
+    @classmethod
+    def get_oauth2_authorization_uri(
+        cls,
+        config: OAuth2ClientConfig,
+        state: OAuth2State,
+    ) -> str:
+        """
+        Return URI for initial OAuth2 request.
+        """
+        uri = config["authorization_request_uri"]
+        # When calling the Snowflake OAuth authorization endpoint for a custom client,
+        # specify only the query parameters documented in the URL below.
+        # Adding unsupported parameters
+        # (e.g., `prompt` as used in BaseEngineSpec.get_oauth2_authorization_uri)
+        # will cause an error.
+        # https://docs.snowflake.com/user-guide/oauth-custom#query-parameters
+        params = {
+            "scope": config["scope"],
+            "response_type": "code",
+            "state": encode_oauth2_state(state),
+            "redirect_uri": config["redirect_uri"],
+            "client_id": config["id"],
+        }
+        return parse.urljoin(uri, "?" + parse.urlencode(params))

Review Comment:
   **Suggestion:** Bug in building the authorization URI: using urllib.parse.urljoin with a query string will drop the path portion of `authorization_request_uri` (urljoin treats a leading '?' as a network-location relative URL), causing the OAuth2 authorization endpoint path to be removed and resulting in invalid URIs. Construct the URL by parsing and updating the query component to preserve the original path. [logic error]
   
   **Severity Level:** Minor โš ๏ธ
   ```suggestion
           # Build the URL by updating the query component to preserve the original path.
           parsed = parse.urlparse(uri)
           existing_qs = dict(parse.parse_qsl(parsed.query, keep_blank_values=True))
           existing_qs.update(params)
           new_qs = parse.urlencode(existing_qs)
           return parse.urlunparse(parsed._replace(query=new_qs))
   ```
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This is a real logic bug: urllib.parse.urljoin(uri, '?...') can replace the path component and yield an authorization endpoint with the wrong path (or no path) depending on the base URI, producing invalid OAuth2 redirects. The proposed change to parse the URI and update its query component preserves the original path and merges params correctly. This directly fixes a correctness issue visible in the PR.
   </details>
   <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:** 227:227
   **Comment:**
   	*Logic Error: Bug in building the authorization URI: using urllib.parse.urljoin with a query string will drop the path portion of `authorization_request_uri` (urljoin treats a leading '?' as a network-location relative URL), causing the OAuth2 authorization endpoint path to be removed and resulting in invalid URIs. Construct the URL by parsing and updating the query component to preserve the original path.
   
   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.
   ```
   </details>



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -33,19 +33,45 @@
 from sqlalchemy import types
 from sqlalchemy.engine.reflection import Inspector
 from sqlalchemy.engine.url import URL
+from sqlalchemy.exc import DatabaseError as SqlalchemyDatabaseError
 
+from superset import is_feature_enabled, security_manager
 from superset.constants import TimeGrain
 from superset.databases.utils import make_url_safe
 from superset.db_engine_specs.base import BaseEngineSpec, BasicPropertiesType
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    DatabaseError = Exception

Review Comment:
   **Suggestion:** Overly-broad fallback when the snowflake connector is not installed: assigning `DatabaseError = Exception` will make the custom exception matcher treat many unrelated exceptions as Snowflake errors (since almost anything is an Exception). Use a distinct sentinel exception class to avoid false-positive matches when Snowflake isn't available. [possible bug]
   
   **Severity Level:** Critical ๐Ÿšจ
   ```suggestion
       # Use a distinct sentinel type when snowflake is not installed to avoid
       # matching unrelated exception types (using `Exception` would be too broad).
       class _SnowflakeDatabaseError(Exception):
           """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
           pass
       DatabaseError = _SnowflakeDatabaseError
   ```
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   Assigning DatabaseError = Exception when the snowflake package is absent will make isinstance(..., DatabaseError) match basically any Exception, producing false positives in the custom exception meta-class logic. Defining a distinct sentinel exception type avoids accidental matches while keeping runtime behavior when the connector is missing.
   </details>
   <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:** 59:59
   **Comment:**
   	*Possible Bug: Overly-broad fallback when the snowflake connector is not installed: assigning `DatabaseError = Exception` will make the custom exception matcher treat many unrelated exceptions as Snowflake errors (since almost anything is an Exception). Use a distinct sentinel exception class to avoid false-positive matches when Snowflake isn't available.
   
   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.
   ```
   </details>



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -377,6 +468,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connects_args = params.get("connect_args", {})
+        if connects_args.get("authenticator") == "oauth":

Review Comment:
   **Suggestion:** Variable name typo and inconsistent handling of connect args: `connects_args` is a misspelling and may be confusing; use `connect_args` consistently so the early check references the same semantics as the rest of the function and avoids accidental logical errors when `params` doesn't contain `connect_args`. [possible bug]
   
   **Severity Level:** Critical ๐Ÿšจ
   ```suggestion
           connect_args = params.get("connect_args") or {}
           if connect_args.get("authenticator") == "oauth":
   ```
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   The code uses a different variable name ("connects_args") here and "connect_args" later, which is confusing and risks maintainability issues. While it doesn't currently introduce a runtime bug (both read from params), normalizing to a single name prevents accidental bugs if the code is modified later and improves readability.
   </details>
   <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:** 479:480
   **Comment:**
   	*Possible Bug: Variable name typo and inconsistent handling of connect args: `connects_args` is a misspelling and may be confusing; use `connect_args` consistently so the early check references the same semantics as the rest of the function and avoids accidental logical errors when `params` doesn't contain `connect_args`.
   
   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.
   ```
   </details>



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,122 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refesh_token",

Review Comment:
   **Suggestion:** Typo in the OAuth2 `scope` value: it's spelled "refesh_token" but should be "refresh_token". This will cause the token request to send the wrong scope and can lead to authentication failures or unexpected token responses. [logic error]
   
   **Severity Level:** Minor โš ๏ธ
   ```suggestion
           "scope": "refresh_token",
   ```
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This is a clear typo in the test fixture ("refesh_token" โ†’ "refresh_token"). Fixing it makes the fixture accurate and avoids confusion or subtle test drift if production code ever marshals the scope through. It's a correctness/readability fix with negligible risk.
   </details>
   <details>
   <summary><b>Prompt for AI Agent ๐Ÿค– </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** tests/unit_tests/db_engine_specs/test_snowflake.py
   **Line:** 452:452
   **Comment:**
   	*Logic Error: Typo in the OAuth2 `scope` value: it's spelled "refesh_token" but should be "refresh_token". This will cause the token request to send the wrong scope and can lead to authentication failures or unexpected token responses.
   
   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.
   ```
   </details>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3696792092

   CodeAnt AI finished reviewing your PR.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3726415886

   ### <span aria-hidden="true">โœ…</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">๐Ÿ”จ</span> Latest commit | 97ddb2739128bcd5b87df82a379392d03e1a89fd |
   |<span aria-hidden="true">๐Ÿ”</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/696042a419af9a00081e000e |
   |<span aria-hidden="true">๐Ÿ˜Ž</span> Deploy Preview | [https://deploy-preview-36856--superset-docs-preview.netlify.app](https://deploy-preview-36856--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">๐Ÿ“ฑ</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTM2ODU2LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.kfQ1inDxUhq23dT602iWCO21p7kxiOvHwBpoMXGl8Ug)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-36856--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "CountryTk (via GitHub)" <gi...@apache.org>.
CountryTk commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4038133049

   Hi @betodealmeida, any chance this could be reviewed & merged?


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3565173810


##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database = Database(sqlalchemy_uri="snowflake://abc")
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.SnowflakeEngineSpec.is_oauth2_enabled",
+        return_value=True,
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={
+            "connect_args": {
+                "validate_default_parameters": True,
+            },
+        },
+    ) == (
+        make_url("snowflake://user:pass@account/database_name/default"),
+        {"connect_args": {"validate_default_parameters": True}},
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://user:pass@account/database_name/default?authenticator=oauth"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.is_feature_enabled",
+        return_value=True,
+    )
+
+    mocker.patch(
+        "superset.security_manager.find_user",
+        return_value=mocker.MagicMock(email="impersonated_user@example.com"),
+    )
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username="impersonated_user",
+        user_token="test_token",  # noqa: S106
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://impersonated_user:pass@account/database_name/default?authenticator=oauth&token=test_token"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+
+def test_custom_snowflake_auth_error_matches_raw_dbapi_exception() -> None:
+    """
+    `BaseEngineSpec.execute()` runs against a bare DBAPI cursor, so the
+    exception it sees is the raw Snowflake error, never wrapped by
+    SQLAlchemy. `CustomSnowflakeAuthError` must still recognize it so the
+    OAuth2 re-auth dance triggers for SQL Lab queries.
+    """
+    from superset.db_engine_specs.snowflake import (
+        CustomSnowflakeAuthError,
+        DatabaseError,
+    )
+
+    raw_error = DatabaseError("250001: Invalid OAuth access token.")

Review Comment:
   Applied โ€” `raw_error: Exception = DatabaseError(...)` (8ba0c75b39).



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database = Database(sqlalchemy_uri="snowflake://abc")
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.SnowflakeEngineSpec.is_oauth2_enabled",
+        return_value=True,
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={
+            "connect_args": {
+                "validate_default_parameters": True,
+            },
+        },
+    ) == (
+        make_url("snowflake://user:pass@account/database_name/default"),
+        {"connect_args": {"validate_default_parameters": True}},
+    )
+
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username=None,
+        user_token=None,
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://user:pass@account/database_name/default?authenticator=oauth"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.is_feature_enabled",
+        return_value=True,
+    )
+
+    mocker.patch(
+        "superset.security_manager.find_user",
+        return_value=mocker.MagicMock(email="impersonated_user@example.com"),
+    )
+    assert SnowflakeEngineSpec.impersonate_user(
+        database=database,
+        username="impersonated_user",
+        user_token="test_token",  # noqa: S106
+        url=make_url("snowflake://user:pass@account/database_name/default"),
+        engine_kwargs={},
+    ) == (
+        make_url(
+            "snowflake://impersonated_user:pass@account/database_name/default?authenticator=oauth&token=test_token"
+        ),
+        {"connect_args": {"authenticator": "oauth"}},
+    )
+
+
+def test_custom_snowflake_auth_error_matches_raw_dbapi_exception() -> None:
+    """
+    `BaseEngineSpec.execute()` runs against a bare DBAPI cursor, so the
+    exception it sees is the raw Snowflake error, never wrapped by
+    SQLAlchemy. `CustomSnowflakeAuthError` must still recognize it so the
+    OAuth2 re-auth dance triggers for SQL Lab queries.
+    """
+    from superset.db_engine_specs.snowflake import (
+        CustomSnowflakeAuthError,
+        DatabaseError,
+    )
+
+    raw_error = DatabaseError("250001: Invalid OAuth access token.")
+    assert isinstance(raw_error, CustomSnowflakeAuthError)
+
+
+def test_custom_snowflake_auth_error_matches_sqlalchemy_wrapped_exception() -> None:
+    """
+    Some call sites execute through SQLAlchemy's `Engine`, which wraps the
+    original DBAPI exception in `sqlalchemy.exc.DatabaseError.orig`.
+    `CustomSnowflakeAuthError` must keep matching this shape too.
+    """
+    from sqlalchemy.exc import DatabaseError as SqlalchemyDatabaseError
+
+    from superset.db_engine_specs.snowflake import (
+        CustomSnowflakeAuthError,
+        DatabaseError,
+    )
+
+    wrapped_error = SqlalchemyDatabaseError(
+        statement="SELECT 1",
+        params=None,
+        orig=DatabaseError("250001: Invalid OAuth access token."),
+    )

Review Comment:
   Applied โ€” `wrapped_error: SqlalchemyDatabaseError = SqlalchemyDatabaseError(...)` (8ba0c75b39).



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +242,105 @@ 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: dict[str, Any] = 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 database.is_oauth2_enabled()
+        ):

Review Comment:
   Confirmed real, and applied (8ba0c75b39). `database.is_oauth2_enabled()` returns True for a database-level OAuth2 client (`encrypted_extra.oauth2_client_info`) regardless of request context โ€” that path bypasses the app-config-based `has_request_context()` guard in `SnowflakeEngineSpec.is_oauth2_enabled()` entirely (this shared method lives in `superset/models/core.py`, unmodified by this PR, so it's used by other OAuth2-capable engines too). Added an explicit `has_request_context()` check directly in `impersonate_user()` so the background-execution guarantee holds for both config sources. Added a regression test (`test_impersonate_user_outside_request_context`) confirming OAuth doesn't engage outside a request context even when `is_oauth2_enabled()` is mocked to return True โ€” it fails against the pre-fix code (verified locally). Also had to fix `test_impersonate_user` itself, which never actually ran inside a request context before, so it never caught this.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3565313678


##########
superset-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx:
##########
@@ -498,7 +498,7 @@ const ExtraOptions = ({
                     onChange={onInputChange}
                   >
                     {t(
-                      'Impersonate logged in user (Presto, Trino, Drill, Hive, and Google Sheets)',
+                      'Impersonate logged in user (Presto, Trino, Drill, Hive, Snowflake and Google Sheets)',

Review Comment:
   **Suggestion:** The newly expanded label now advertises Snowflake and Google Sheets, but the adjacent help text still only explains Presto/Trino/Hive behavior, which creates a user-facing documentation mismatch and can cause incorrect configuration for the newly listed engines; update the tooltip copy to include the Snowflake/Google Sheets semantics. [comment mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Minor ๐Ÿงน</summary>
   
   ```mdx
   - โš ๏ธ Database connection modal misleads Snowflake impersonation configuration.
   - โš ๏ธ Google Sheets impersonation behavior undocumented in tooltip text.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Open the Database connection modal in the UI and navigate to the "Security" section
   rendered by `ExtraOptions` in
   `superset-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx:13-21` (see hunk
   around lines 450-569).
   
   2. Observe the impersonation checkbox defined at lines 45-53 of the snippet: the label
   uses `t('Impersonate logged in user (Presto, Trino, Drill, Hive, Snowflake and Google
   Sheets)')`, advertising Snowflake and Google Sheets support.
   
   3. Hover over the adjacent `InfoTooltip` at lines 55-62, whose tooltip text only describes
   Presto, Trino, and Hive behavior: it explains execution as the logged-in user for
   Presto/Trino and Hive-specific `hive.server2.enable.doAs`/`hive.server2.proxy.user`
   semantics, without mentioning Snowflake or Google Sheets.
   
   4. This creates a user-facing documentation mismatch: the checkbox label promises behavior
   for Snowflake/Google Sheets added in this PR, but the explanatory text remains limited to
   Presto/Trino/Hive, which can mislead users about how impersonation actually works for the
   newly listed engines.
   ```
   </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=c1c8480578ec47f289cc820fe43f36c9&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=c1c8480578ec47f289cc820fe43f36c9&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-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx
   **Line:** 501:501
   **Comment:**
   	*Comment Mismatch: The newly expanded label now advertises Snowflake and Google Sheets, but the adjacent help text still only explains Presto/Trino/Hive behavior, which creates a user-facing documentation mismatch and can cause incorrect configuration for the newly listed engines; update the tooltip copy to include the Snowflake/Google Sheets semantics.
   
   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=722e4687fcaf7f768b930649af5b257f183ad2d737e81f174e1b018f7d7ddf25&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=722e4687fcaf7f768b930649af5b257f183ad2d737e81f174e1b018f7d7ddf25&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3679374087


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,61 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        """
+        Match Snowflake's invalid/expired OAuth token error, whether it arrives
+        wrapped by SQLAlchemy (e.g. ``Engine``-based execution) or as the raw
+        DBAPI exception โ€” ``BaseEngineSpec.execute()`` runs against a bare
+        cursor and never wraps it, so both shapes must be handled here.
+        """
+        orig: object = instance
+        if isinstance(instance, SqlalchemyDatabaseError):
+            orig = cast(SqlalchemyDatabaseError, instance).orig
+
+        return isinstance(orig, DatabaseError) and "Invalid OAuth access token" in str(
+            orig
+        )
+
+
+class CustomSnowflakeAuthError(DatabaseError, metaclass=CustomSnowflakeAuthErrorMeta):
+    """Snowflake OAuth error type matched via the metaclass above (see note there)."""

Review Comment:
   Confirmed and fixed โ€” `OAuth2TokenRefreshError` (raised by the base `get_oauth2_fresh_token`) isnt a real subclass of `CustomSnowflakeAuthError`, so `except db_engine_spec.oauth2_exception` in `refresh_oauth2_token` never caught it. Added it to `oauth2_exception` as a tuple, plus a regression test.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3651456888


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -192,6 +243,113 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2: bool = True
+    oauth2_exception: type[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"]
+        )

Review Comment:
   `DATABASE_OAUTH2_CLIENTS` has a `{}` default in `config.py`, and this mirrors the base-spec check verbatim, so the index can't `KeyError`.



##########
superset-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx:
##########
@@ -522,7 +522,7 @@ const ExtraOptions = ({
                     onChange={onInputChange}
                   >
                     {t(
-                      'Impersonate logged in user (Presto, Trino, Drill, Hive, and Google Sheets)',
+                      'Impersonate logged in user (Presto, Trino, Drill, Hive, Snowflake and Google Sheets)',

Review Comment:
   This diff is only the impersonation tooltip copy. Google Sheets already does OAuth impersonation the same way, so a caching concern here would predate this PR and lives in the cache-key layer, not this label.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3696783890

   CodeAnt AI is reviewing your PR.
   
   ---
   
   ### Thanks for using CodeAnt! ๐ŸŽ‰
   
   We're free for open-source projects. if you're enjoying it, help us grow by sharing.
   
   [Share on X](https://twitter.com/intent/tweet?text=Just%20tried%20%40CodeAntAI%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A&url=https%3A//codeant.ai) ยท
   [Reddit](https://www.reddit.com/submit?title=Check%20out%20CodeAnt%20for%20automated%20code%20review&text=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A%20https%3A//codeant.ai) ยท
   [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcodeant.ai&mini=true&title=Check%20out%20CodeAnt%20for%20automated%20code%20review&summary=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos)
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4806339974

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4805012184

   <!-- translation-regression-bot -->
   ## โš ๏ธ Translation Regression Detected
   
   A source change in this PR renamed or reworded strings, invalidating existing translations (they are now `#, fuzzy`) in `fi`, `fr`, `it`, `ko`, `th`. Please resolve the affected `.po` files before merging.
   
   _Note: intentionally **deleting** a translatable string is not a regression and is not flagged here โ€” only translations invalidated by a renamed/reworded source string are._
   
   | Language | Fuzzy before | Fuzzy after | New |
   |----------|-------------:|------------:|----:|
   | `fi` | 4815 | 4816 | +1 |
   | `fr` | 1004 | 1014 | +10 |
   | `it` | 1665 | 1667 | +2 |
   | `ko` | 1519 | 1521 | +2 |
   | `th` | 4815 | 4816 | +1 |
   
   ### How to fix
   
   **1. Install dependencies** (if not already set up):
   
   ```bash
   pip install -r superset/translations/requirements.txt
   sudo apt-get install gettext   # or: brew install gettext
   ```
   
   **2. Re-extract strings and sync `.po` files:**
   
   ```bash
   ./scripts/translations/babel_update.sh
   ```
   
   This rewrites `superset/translations/messages.pot` from the current source files and merges the changes into every `.po` file. Strings whose `msgid` changed will be marked `#, fuzzy`.
   
   **3. Resolve the fuzzy entries** in the affected language files (`fi`, `fr`, `it`, `ko`, `th`):
   
   ```bash
   grep -n '#, fuzzy' superset/translations/<lang>/LC_MESSAGES/messages.po
   ```
   
   For each fuzzy entry, either rewrite the `msgstr` to match the new string and remove the `#, fuzzy` line, or clear the `msgstr` to `""` if you cannot provide a translation.
   
   **4. Commit your changes to the `.po` files.**
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4765078312

   Looks solid and CI's lookin' promising, but I'll update the branch to make sure, @htamakos. Thanks for the testing notes, BTW. 
   
   @betodealmeida I think this is more in your wheelhouse, mind taking a look at the Snowflake OAuth bits?


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3679180131


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,61 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        """
+        Match Snowflake's invalid/expired OAuth token error, whether it arrives
+        wrapped by SQLAlchemy (e.g. ``Engine``-based execution) or as the raw
+        DBAPI exception โ€” ``BaseEngineSpec.execute()`` runs against a bare
+        cursor and never wraps it, so both shapes must be handled here.
+        """
+        orig: object = instance
+        if isinstance(instance, SqlalchemyDatabaseError):
+            orig = cast(SqlalchemyDatabaseError, instance).orig
+
+        return isinstance(orig, DatabaseError) and "Invalid OAuth access token" in str(
+            orig
+        )
+
+
+class CustomSnowflakeAuthError(DatabaseError, metaclass=CustomSnowflakeAuthErrorMeta):
+    """Snowflake OAuth error type matched via the metaclass above (see note there)."""

Review Comment:
   **Suggestion:** The custom `oauth2_exception` only matches Snowflake database errors through `__instancecheck__`, but `refresh_oauth2_token` catches this value in an `except` clause. Python exception handlers require actual subclass relationships and do not invoke `__instancecheck__`; consequently, the `OAuth2TokenRefreshError` raised by the shared refresh-token exchange is not caught by this handler, so the revoked token remains stored and the re-authentication flow is not triggered correctly. Include the shared OAuth refresh exception in the Snowflake exception contract, or override the refresh/error handling appropriately. [error handling]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ Revoked Snowflake refresh tokens remain stored.
   - โŒ Re-authentication does not start after refresh failure.
   - โš ๏ธ Subsequent interactive queries repeatedly encounter the stale token.
   ```
   </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=b8cdaf082cc242ef84f8e0c1b7a211ce&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=b8cdaf082cc242ef84f8e0c1b7a211ce&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:** 100:101
   **Comment:**
   	*Error Handling: The custom `oauth2_exception` only matches Snowflake database errors through `__instancecheck__`, but `refresh_oauth2_token` catches this value in an `except` clause. Python exception handlers require actual subclass relationships and do not invoke `__instancecheck__`; consequently, the `OAuth2TokenRefreshError` raised by the shared refresh-token exchange is not caught by this handler, so the revoked token remains stored and the re-authentication flow is not triggered correctly. Include the shared OAuth refresh exception in the Snowflake exception contract, or override the refresh/error handling appropriately.
   
   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=211d1ea0f82a9aa4812e63849b56951e5f29ec2767c313f31be62483990e19ef&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=211d1ea0f82a9aa4812e63849b56951e5f29ec2767c313f31be62483990e19ef&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4949531256

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "sfirke (via GitHub)" <gi...@apache.org>.
sfirke commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5136238525

   This PR has been on an epic journey per my notifications:
   ![Screenshot_20260730-170108.png](https://github.com/user-attachments/assets/5537c277-f25e-4794-85e7-b607e8ab69b0)
   
   Good to see it chugging along!
   
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #36856:
URL: https://github.com/apache/superset/pull/36856


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3696784101

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3699448461

   CodeAnt AI is running Incremental review
   
   ---
   
   ### Thanks for using CodeAnt! ๐ŸŽ‰
   
   We're free for open-source projects. if you're enjoying it, help us grow by sharing.
   
   [Share on X](https://twitter.com/intent/tweet?text=Just%20tried%20%40CodeAntAI%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A&url=https%3A//codeant.ai) ยท
   [Reddit](https://www.reddit.com/submit?title=Check%20out%20CodeAnt%20for%20automated%20code%20review&text=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A%20https%3A//codeant.ai) ยท
   [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcodeant.ai&mini=true&title=Check%20out%20CodeAnt%20for%20automated%20code%20review&summary=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos)
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "betodealmeida (via GitHub)" <gi...@apache.org>.
betodealmeida commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4805070482

   @htamakos you just need this diff to get the tests to pass:
   
   ```diff
   diff --git a/superset/db_engine_specs/snowflake.py b/superset/db_engine_specs/snowflake.py
   index fb0e7d48b6..94dc030023 100644
   --- a/superset/db_engine_specs/snowflake.py
   +++ b/superset/db_engine_specs/snowflake.py
   @@ -296,6 +296,7 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
            cls,
            config: OAuth2ClientConfig,
            state: OAuth2State,
   +        code_verifier: str | None = None,  # pylint: disable=unused-argument
        ) -> str:
            """
            Return URI for initial OAuth2 request.
   ```


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3478651087


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):

Review Comment:
   **Suggestion:** Add a class docstring describing the purpose of this new metaclass and what kind of errors it is intended to match. [custom_rule]
   
   **Severity Level:** Minor โš ๏ธ
   <details>
   <summary><b>Why it matters? ๐Ÿค” </b></summary>
   
   This is a newly added class and it does not include a docstring. The custom rule requires new Python classes to be documented inline, so this is a real violation.
   </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=c1bfbae6ab8c42c2b6554d6bf1959957&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=c1bfbae6ab8c42c2b6554d6bf1959957&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:** 73:73
   **Comment:**
   	*Custom Rule: Add a class docstring describing the purpose of this new metaclass and what kind of errors it is intended to match.
   
   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=ffe0adc475f1c59da35bcf0ccb11dd99fdb686cd68dc24d743f1fa91e9d12111&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=ffe0adc475f1c59da35bcf0ccb11dd99fdb686cd68dc24d743f1fa91e9d12111&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    def __instancecheck__(cls, instance: object) -> bool:
+        return (
+            isinstance(instance, SqlalchemyDatabaseError)
+            and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
+            and "Invalid OAuth access token" in str(instance)
+        )

Review Comment:
   **Suggestion:** Add a method docstring that explains the custom instance-check logic and the conditions required for a positive match. [custom_rule]
   
   **Severity Level:** Minor โš ๏ธ
   <details>
   <summary><b>Why it matters? ๐Ÿค” </b></summary>
   
   This newly added method has no docstring, and the rule requires new Python functions and methods to be documented inline. The omission is a genuine rule violation.
   </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=5f3c23749a60404c9f0d5ab99e01ee96&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=5f3c23749a60404c9f0d5ab99e01ee96&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:** 74:79
   **Comment:**
   	*Custom Rule: Add a method docstring that explains the custom instance-check logic and the conditions required for a positive match.
   
   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=253563670d09cdda15d0d5818a3b95822f8caf95b1f116892d7e08817b87d20b&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=253563670d09cdda15d0d5818a3b95822f8caf95b1f116892d7e08817b87d20b&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    def __instancecheck__(cls, instance: object) -> bool:
+        return (
+            isinstance(instance, SqlalchemyDatabaseError)
+            and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
+            and "Invalid OAuth access token" in str(instance)
+        )
+
+
+class CustomSnowflakeAuthError(DatabaseError, metaclass=CustomSnowflakeAuthErrorMeta):
+    pass

Review Comment:
   **Suggestion:** Add a class docstring clarifying why this custom exception type exists and how it should be used by OAuth error handling. [custom_rule]
   
   **Severity Level:** Minor โš ๏ธ
   <details>
   <summary><b>Why it matters? ๐Ÿค” </b></summary>
   
   This is a newly introduced class with no docstring. Under the custom rule, new Python classes must include docstrings, so the suggestion identifies a real violation.
   </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=737f9a0d70f040dbb342b7df52d0daaa&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=737f9a0d70f040dbb342b7df52d0daaa&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:** 82:83
   **Comment:**
   	*Custom Rule: Add a class docstring clarifying why this custom exception type exists and how it should be used by OAuth error handling.
   
   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=e46b15a6f50faa0b6c98eafbfac53f3a7078c29c3308b1e4058df0d807acf703&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=e46b15a6f50faa0b6c98eafbfac53f3a7078c29c3308b1e4058df0d807acf703&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "htamakos (via GitHub)" <gi...@apache.org>.
htamakos commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4805651752

   @betodealmeida 
   Thanks! I've applied this change and pushed the fix.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "akkbng (via GitHub)" <gi...@apache.org>.
akkbng commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4207216443

   Hey @betodealmeida , are the plans to review this PR?


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3565175351


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,61 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        """
+        Match Snowflake's invalid/expired OAuth token error, whether it arrives
+        wrapped by SQLAlchemy (e.g. ``Engine``-based execution) or as the raw
+        DBAPI exception โ€” ``BaseEngineSpec.execute()`` runs against a bare
+        cursor and never wraps it, so both shapes must be handled here.
+        """
+        orig = instance

Review Comment:
   **Suggestion:** Add an explicit type annotation for this local variable to keep the new metaclass logic fully typed. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   The new local variable `orig` can be annotated here, but it is introduced without a type hint inside the newly added metaclass method. This matches the Python type-hint rule violation.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=82e597dbeddb4f93bbdc9796e6e24020&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=82e597dbeddb4f93bbdc9796e6e24020&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:** 91:91
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this local variable to keep the new metaclass logic 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%2F36856&comment_hash=bb19cef628c6ec65976b806a328c04815eb285a3c8d72ca4e13a71517d165dc0&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=bb19cef628c6ec65976b806a328c04815eb285a3c8d72ca4e13a71517d165dc0&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +440,206 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests: mock.MagicMock = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(app: SupersetApp, mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+
+    Impersonation only applies within a request context (see
+    ``test_impersonate_user_outside_request_context`` below for the
+    background-execution case), so these assertions run inside one.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database: Database = Database(sqlalchemy_uri="snowflake://abc")
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.SnowflakeEngineSpec.is_oauth2_enabled",
+        return_value=True,
+    )
+
+    with app.test_request_context("/some/place/"):
+        assert SnowflakeEngineSpec.impersonate_user(
+            database=database,
+            username=None,
+            user_token=None,
+            url=make_url("snowflake://user:pass@account/database_name/default"),
+            engine_kwargs={
+                "connect_args": {
+                    "validate_default_parameters": True,
+                },
+            },
+        ) == (
+            make_url("snowflake://user:pass@account/database_name/default"),
+            {"connect_args": {"validate_default_parameters": True}},
+        )
+
+        assert SnowflakeEngineSpec.impersonate_user(
+            database=database,
+            username=None,
+            user_token=None,
+            url=make_url("snowflake://user:pass@account/database_name/default"),
+            engine_kwargs={},
+        ) == (
+            make_url(
+                "snowflake://user:pass@account/database_name/default?authenticator=oauth"
+            ),
+            {"connect_args": {"authenticator": "oauth"}},
+        )
+
+        mocker.patch(
+            "superset.db_engine_specs.snowflake.is_feature_enabled",
+            return_value=True,
+        )
+
+        mocker.patch(
+            "superset.security_manager.find_user",
+            return_value=mocker.MagicMock(email="impersonated_user@example.com"),
+        )
+        assert SnowflakeEngineSpec.impersonate_user(
+            database=database,
+            username="impersonated_user",
+            user_token="test_token",  # noqa: S106
+            url=make_url("snowflake://user:pass@account/database_name/default"),
+            engine_kwargs={},
+        ) == (
+            make_url(
+                "snowflake://impersonated_user:pass@account/database_name/default?authenticator=oauth&token=test_token"
+            ),
+            {"connect_args": {"authenticator": "oauth"}},
+        )
+
+
+def test_impersonate_user_outside_request_context(mocker: MockerFixture) -> None:
+    """
+    Background executions (alerts/reports) have no per-user token, so OAuth
+    impersonation must not engage outside a request context โ€” even when
+    ``database.is_oauth2_enabled()`` returns True because of a
+    database-level OAuth2 client config, which (unlike the app-config-based
+    check) isn't itself request-context-aware.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database: Database = Database(sqlalchemy_uri="snowflake://abc")
+    mocker.patch.object(Database, "is_oauth2_enabled", return_value=True)
+
+    url = make_url("snowflake://user:pass@account/database_name/default")

Review Comment:
   **Suggestion:** Add an explicit type annotation for this local URL variable to satisfy the requirement for annotating relevant variables in new Python code. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This is a newly added Python local variable with an obvious concrete type, but it is not annotated. That matches the rule requiring type hints for relevant variables in new or modified Python code.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=05576e2f9ec2443388ec2c65cb717ada&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=05576e2f9ec2443388ec2c65cb717ada&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/db_engine_specs/test_snowflake.py
   **Line:** 583:583
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this local URL variable to satisfy the requirement for annotating relevant variables in new Python code.
   
   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=591960b5d8bd6b78e5e27b75f9f1687570135a7a1d3b72b379270a5fe775cf74&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=591960b5d8bd6b78e5e27b75f9f1687570135a7a1d3b72b379270a5fe775cf74&reaction=dislike'>๐Ÿ‘Ž</a>



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -438,6 +596,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connect_args = params.get("connect_args") or {}

Review Comment:
   **Suggestion:** Add a concrete type annotation for this newly added `connect_args` variable to satisfy the type-hint requirement. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This newly added local variable is assignable to a concrete mapping type and is introduced without an explicit annotation in modified Python code, so it violates the type-hint requirement.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=3ce1ee70e33140508ba9fdd7d2bad72f&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=3ce1ee70e33140508ba9fdd7d2bad72f&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:** 607:607
   **Comment:**
   	*Custom Rule: Add a concrete type annotation for this newly added `connect_args` variable to satisfy the type-hint requirement.
   
   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=4eaf5d14d77fc705906e0e2e2619631dd58f0247c76951892e33a6640b0744ad&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=4eaf5d14d77fc705906e0e2e2619631dd58f0247c76951892e33a6640b0744ad&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3548342286


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError

Review Comment:
   **Suggestion:** Add a type annotation to this newly assigned module-level fallback symbol to make the intended type explicit. [custom_rule]
   
   **Severity Level:** Minor โš ๏ธ
   <details>
   <summary><b>Why it matters? ๐Ÿค” </b></summary>
   
   The fallback module-level symbol is newly introduced and assigned without a type annotation. Since it is a relevant variable that can be annotated, this is a real type-hint omission.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=496d9618c373451d8ff56655ac22e475&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=496d9618c373451d8ff56655ac22e475&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:** 69:70
   **Comment:**
   	*Custom Rule: Add a type annotation to this newly assigned module-level fallback symbol to make the intended type explicit.
   
   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=171bf9759028361c2bea00ff0bc6236bab0a1edf1a6aca495d95078bdeb7e5d9&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=171bf9759028361c2bea00ff0bc6236bab0a1edf1a6aca495d95078bdeb7e5d9&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5039662862

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3699639542

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3651356811


##########
superset-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx:
##########
@@ -522,7 +522,7 @@ const ExtraOptions = ({
                     onChange={onInputChange}
                   >
                     {t(
-                      'Impersonate logged in user (Presto, Trino, Drill, Hive, and Google Sheets)',
+                      'Impersonate logged in user (Presto, Trino, Drill, Hive, Snowflake and Google Sheets)',

Review Comment:
   **Suggestion:** The UI now advertises Snowflake OAuth impersonation, but this change does not disable the per-user caching option for OAuth-enabled connections. Leaving that option selectable allows users to configure a shared cache for credentials that must remain user-scoped, potentially reusing one user's connection for another user. [security]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ SQL Lab results may cross user boundaries.
   - โŒ Dashboard results may expose another user's data.
   - โš ๏ธ Snowflake OAuth authorization becomes ineffective for cached queries.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. In the database configuration UI, enable the `impersonate_user` checkbox rendered by
   `ExtraOptions.tsx:517-526`, configure Snowflake OAuth, and leave the existing
   username-aware caching option disabled.
   
   2. Log in as user A and execute a query from SQL Lab; the Snowflake connection path
   invokes `SnowflakeEngineSpec.impersonate_user()` at
   `superset/db_engine_specs/snowflake.py:278-319`, which enables OAuth and attaches user A's
   token.
   
   3. Execute the same query as user B through the SQL Lab or dashboard query path while
   result caching is enabled.
   
   4. Because the database remains configured for shared caching rather than user-specific
   caching, the identical cache key can return user A's cached result to user B instead of
   executing with user B's OAuth identity.
   ```
   </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=dc52940c2bc049b6af7028888548fa8d&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=dc52940c2bc049b6af7028888548fa8d&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-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx
   **Line:** 525:525
   **Comment:**
   	*Security: The UI now advertises Snowflake OAuth impersonation, but this change does not disable the per-user caching option for OAuth-enabled connections. Leaving that option selectable allows users to configure a shared cache for credentials that must remain user-scoped, potentially reusing one user's connection for another user.
   
   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=68d161fe6a9068153c9e123953acbf809990b35746b0f58e94e8833c2c47d5c5&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=68d161fe6a9068153c9e123953acbf809990b35746b0f58e94e8833c2c47d5c5&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3632448306


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -192,6 +243,113 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2: bool = True
+    oauth2_exception: type[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"]
+        )

Review Comment:
   **Suggestion:** This direct config indexing can raise a runtime KeyError when the OAuth client map is not defined in config, causing Snowflake auth checks to fail unexpectedly. Use a safe lookup with a default empty mapping to avoid breaking connection setup. [possible bug]
   
   <details>
   <summary><b>Severity Level:</b> Major โš ๏ธ</summary>
   
   ```mdx
   - โŒ Snowflake OAuth checks crash if config key missing.
   - โš ๏ธ Database connection setup fails for misconfigured deployments.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Start a Superset instance where the Flask app configuration does not define
   `DATABASE_OAUTH2_CLIENTS` (for example, a custom config predating this OAuth feature or
   one that accidentally omits the key).
   
   2. Trigger any code path that evaluates Snowflake OAuth support, such as calling
   `SnowflakeEngineSpec.get_oauth2_config()` (defined at
   `superset/db_engine_specs/snowflake.py:268-275`), which internally calls
   `SnowflakeEngineSpec.is_oauth2_enabled()` at lines 250-265.
   
   3. When `SnowflakeEngineSpec.is_oauth2_enabled()` executes at
   `superset/db_engine_specs/snowflake.py:262-265`, it evaluates `cls.supports_oauth2 and
   cls.engine_name in app.config["DATABASE_OAUTH2_CLIENTS"]`.
   
   4. Because `DATABASE_OAUTH2_CLIENTS` is missing from `app.config`, the direct indexing at
   line 264 raises a `KeyError`, causing the OAuth enablement check and any calling
   connection-setup logic to fail with an unhandled exception rather than cleanly falling
   back to non-OAuth authentication.
   ```
   </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=7fc9bdd3eb974f3eaf8f82b23a3c65dd&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=7fc9bdd3eb974f3eaf8f82b23a3c65dd&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:** 262:265
   **Comment:**
   	*Possible Bug: This direct config indexing can raise a runtime KeyError when the OAuth client map is not defined in config, causing Snowflake auth checks to fail unexpectedly. Use a safe lookup with a default empty mapping to avoid breaking connection setup.
   
   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=2b90a2c20802fcb3edad49155a212ad760ae42aa65d9a58225a358700df997de&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=2b90a2c20802fcb3edad49155a212ad760ae42aa65d9a58225a358700df997de&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3846884066


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -192,6 +244,119 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support

Review Comment:
   Good catch, fixed. Registered `$.oauth2_client_info.secret` in `encrypted_extra_sensitive_fields`, matching gsheets/trino. Added a regression test asserting the secret is masked in `masked_encrypted_extra`.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -192,6 +244,119 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2: bool = True
+    # `CustomSnowflakeAuthError` is only matched via `isinstance()` (see the
+    # metaclass docstring above), so it's paired with `OAuth2TokenRefreshError`
+    # (a real subclass) to keep `refresh_oauth2_token`'s `except` clause working.
+    oauth2_exception: type[Exception] | tuple[type[Exception], ...] = (
+        CustomSnowflakeAuthError,
+        OAuth2TokenRefreshError,
+    )
+
+    @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: dict[str, Any] = 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.
+        #
+        # ``database.is_oauth2_enabled()`` returns True for a database-level OAuth2
+        # client (``encrypted_extra.oauth2_client_info``) regardless of request
+        # context, unlike the app-config-based check in ``is_oauth2_enabled()``
+        # above. Background executions (alerts/reports) have no per-user token, so
+        # ``has_request_context()`` must be checked explicitly here too, or OAuth
+        # gets switched on with no token to send.
+        if (
+            not connect_args.get("validate_default_parameters", False)
+            and has_request_context()
+            and database.is_oauth2_enabled()
+        ):
+            url = url.update_query_dict({"authenticator": "oauth"})
+            connect_args["authenticator"] = "oauth"
+
+            if user_token:
+                if username is not None:
+                    user = security_manager.find_user(username=username)

Review Comment:
   Good catch, fixed. `impersonate_user` no longer calls `find_user` on the value passed in when `IMPERSONATE_WITH_EMAIL_PREFIX` is enabled -- it's already the email prefix by the time it gets here, so re-deriving it as a login was silently failing whenever the two differ. Uses the given value directly in that case now; kept the existing login->email lookup for the non-prefix path, where the raw login is what's actually passed in. Added a regression test covering the prefix path and asserting `find_user` isn't called there.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5402522933

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers an incremental AI Review.
   - `/review full` - Manually triggers a full AI Review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3821761878


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -192,6 +244,119 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support

Review Comment:
   This enables Snowflake's database-level OAuth client path, but `encrypted_extra_sensitive_fields` still omits `$.oauth2_client_info.secret` while the other specs supporting that path mask it. A database editor can then receive the configured client secret through `masked_encrypted_extra`. Could this register that field as sensitive before enabling the path?



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -192,6 +244,119 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2: bool = True
+    # `CustomSnowflakeAuthError` is only matched via `isinstance()` (see the
+    # metaclass docstring above), so it's paired with `OAuth2TokenRefreshError`
+    # (a real subclass) to keep `refresh_oauth2_token`'s `except` clause working.
+    oauth2_exception: type[Exception] | tuple[type[Exception], ...] = (
+        CustomSnowflakeAuthError,
+        OAuth2TokenRefreshError,
+    )
+
+    @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: dict[str, Any] = 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.
+        #
+        # ``database.is_oauth2_enabled()`` returns True for a database-level OAuth2
+        # client (``encrypted_extra.oauth2_client_info``) regardless of request
+        # context, unlike the app-config-based check in ``is_oauth2_enabled()``
+        # above. Background executions (alerts/reports) have no per-user token, so
+        # ``has_request_context()`` must be checked explicitly here too, or OAuth
+        # gets switched on with no token to send.
+        if (
+            not connect_args.get("validate_default_parameters", False)
+            and has_request_context()
+            and database.is_oauth2_enabled()
+        ):
+            url = url.update_query_dict({"authenticator": "oauth"})
+            connect_args["authenticator"] = "oauth"
+
+            if user_token:
+                if username is not None:
+                    user = security_manager.find_user(username=username)

Review Comment:
   With `IMPERSONATE_WITH_EMAIL_PREFIX` enabled, `Database._get_sqla_engine()` has already converted the effective username to the email prefix before calling this method. Looking that prefix up again as a username fails whenever the login differs from the prefix, leaving the service-account username paired with the user's OAuth token. Could this use the supplied username directly instead of repeating the lookup/mapping?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564846263


##########
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:
   Already addressed โ€” the whole OAuth block in `impersonate_user` (setting the authenticator *and* injecting the token) is now gated behind `not connect_args.get("validate_default_parameters", False)`, so test-connection flows never get mixed auth params.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError

Review Comment:
   Tried this โ€” it actually breaks mypy: `DatabaseError: type[Exception] = _SnowflakeDatabaseError` triggers `error: Name "DatabaseError" already defined (possibly by an import)  [no-redef]`, since the try branch already binds `DatabaseError` via the conditional import. Not applying.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,53 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        return (
+            isinstance(instance, SqlalchemyDatabaseError)
+            and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
+            and "Invalid OAuth access token" in str(instance)
+        )

Review Comment:
   Confirmed real, and applied (08d490e29a). Verified the path: SQL Lab query execution routes through `BaseEngineSpec.execute()`, which calls `cursor.execute(query)` directly on a raw DBAPI cursor (from `Database.get_raw_connection()`) โ€” so the exception it catches is the unwrapped snowflake-connector error, never a `sqlalchemy.exc.DatabaseError`. `__instancecheck__` now checks `.orig` when the instance is SQLAlchemy-wrapped, but falls back to checking the raw exception directly otherwise. Added regression tests covering both shapes plus a negative case; the raw-DBAPI test fails against the pre-fix code (verified by stashing the fix and re-running).



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564845976


##########
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():

Review Comment:
   Already addressed (duplicate of the same finding on an earlier push) โ€” see `impersonate_user`'s `database.is_oauth2_enabled()` gate.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +224,99 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True

Review Comment:
   Not applying โ€” every other boolean class attribute in `SnowflakeEngineSpec` (`supports_dynamic_schema`, `force_column_alias_quotes`, `use_equality_for_boolean_filters`, etc.) is unannotated too; singling out `supports_oauth2` would be inconsistent with the surrounding style, and mypy already infers it fine.



##########
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", {})

Review Comment:
   Applied โ€” `connect_args: dict[str, Any] = engine_kwargs.setdefault(...)` (08d490e29a), matching the same pattern already used in `get_extra_params` in this file.



##########
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})
+
+        return url, engine_kwargs
+
+    @classmethod
+    def get_oauth2_authorization_uri(
+        cls,
+        config: OAuth2ClientConfig,
+        state: OAuth2State,
+        code_verifier: str | None = None,  # pylint: disable=unused-argument
+    ) -> str:
+        """
+        Return URI for initial OAuth2 request.
+        """
+        uri = config["authorization_request_uri"]
+        # When calling the Snowflake OAuth authorization endpoint for a custom client,
+        # specify only the query parameters documented in the URL below.
+        # Adding unsupported parameters
+        # (e.g., `prompt` as used in BaseEngineSpec.get_oauth2_authorization_uri)
+        # will cause an error.
+        # https://docs.snowflake.com/user-guide/oauth-custom#query-parameters
+        params = {
+            "scope": config["scope"],
+            "response_type": "code",
+            "state": encode_oauth2_state(state),
+            "redirect_uri": config["redirect_uri"],
+            "client_id": config["id"],
+        }

Review Comment:
   Applied โ€” `params: dict[str, str] = {...}` (08d490e29a); all of `OAuth2ClientConfig`'s relevant fields are `str`, so this is accurate.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4948693383

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3696789123

   ## Nitpicks ๐Ÿ”
   
   <table>
   <tr><td>๐Ÿ”’&nbsp;<strong>No security issues identified</strong></td></tr>
   <tr><td>โšก&nbsp;<strong>Recommended areas for review</strong><br><br>
   
   - [ ] <a href='https://github.com/apache/superset/pull/36856/files#diff-021730eaa7a0388769fa4bec2a421b292a5aa09002f8f1eb1cbbf2a79b980341R62-R72'><strong>Fragile error detection</strong></a><br>The custom metaclass instance check looks for the literal substring "Invalid OAuth access token" in the stringified exception. This is brittle (case/locale/format differences) and depends on wrapping types. Consider making the detection more robust (inspect the underlying DatabaseError message or error code) and guard against missing attributes.<br>
   
   - [ ] <a href='https://github.com/apache/superset/pull/36856/files#diff-961d1d8e8d0e69cf8bfbd39fa3f497c62c2950a150e558c54760f9ded12316a1R469-R495'><strong>Fragile request assertion</strong></a><br>The test mocks `requests` and asserts the call using `requests.post.assert_called_with(...)`. This is brittle because it doesn't assert the number of calls and could silently pass if multiple calls happen. Also, it couples to exact call signature ordering. Consider asserting call count and inspecting call_args to validate the important pieces (`data` payload and `timeout`) rather than relying on a single equality call.<br>
   
   - [ ] <a href='https://github.com/apache/superset/pull/36856/files#diff-961d1d8e8d0e69cf8bfbd39fa3f497c62c2950a150e558c54760f9ded12316a1R444-R457'><strong>Typo in fixture</strong></a><br>The OAuth2 fixture defines the `scope` value as `"refesh_token"` (misspelling). This may cause tests to pass incorrectly or mask a bug because the code under test might expect the exact `scope` string (e.g., "refresh_token") or validations to succeed/fail differently. Verify intended scope and correct the value.<br>
   
   </td></tr>
   </table>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3486194308


##########
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():

Review Comment:
   **Suggestion:** The OAuth gating in impersonation checks only `cls.is_oauth2_enabled()`, which reads global `DATABASE_OAUTH2_CLIENTS` config and ignores database-level `oauth2_client_info` stored in `encrypted_extra`. As a result, Snowflake connections configured with per-database OAuth2 clients can successfully fetch a user token but never switch the connection to OAuth authenticator, so queries keep using the non-OAuth auth path. Use the passed `database` object (for example `database.is_oauth2_enabled()` / `database.get_oauth2_config()`) for these checks instead of class-level global config. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ Snowflake OAuth2 impersonation never activates for database-level clients.
   - โš ๏ธ User queries run under service identity, breaking impersonation.
   - โš ๏ธ Security audit logs miss correct per-user Snowflake identity.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Configure a Snowflake database object with per-database OAuth2 client info by setting
   `encrypted_extra` to include `oauth2_client_info` so that `Database.get_oauth2_config()`
   in `superset/models/core.py:1333-1352` returns a config, and omit any `Snowflake` entry
   from `app.config["DATABASE_OAUTH2_CLIENTS"]` so that only database-level configuration is
   present.
   
   2. Ensure this Snowflake database has `impersonate_user=True` (column defined at
   `superset/models/core.py:212`) and run a query (for example via SQL Lab), which routes
   through `Database._get_sqla_engine` at `superset/models/core.py:534-589`, where
   `oauth2_config = self.get_oauth2_config()` (line 567) is non-None and
   `get_oauth2_access_token(...)` (lines 569-575) retrieves a user access token from
   `DatabaseUserOAuth2Tokens`.
   
   3. In `_get_sqla_engine`, because `self.impersonate_user` is True (line 581), the code
   calls `self.db_engine_spec.impersonate_user(self, effective_username, access_token,
   sqlalchemy_url, engine_kwargs)` at `superset/models/core.py:581-588`; for Snowflake this
   resolves to `SnowflakeEngineSpec.impersonate_user` implemented in
   `superset/db_engine_specs/snowflake.py:259-292`.
   
   4. Inside `SnowflakeEngineSpec.impersonate_user` (snowflake.py:271-281) both the branch
   that sets `authenticator="oauth"` and the branch that injects the `user_token` into the
   URL are guarded by `cls.is_oauth2_enabled()`, which in
   `SnowflakeEngineSpec.is_oauth2_enabled` (`superset/db_engine_specs/snowflake.py:231-246`)
   only checks `cls.engine_name in app.config["DATABASE_OAUTH2_CLIENTS"]` and ignores the
   databaseโ€™s `oauth2_client_info`; with no global Snowflake entry this returns False, so the
   conditions at lines 274-281 are never entered and the connection continues to use the
   non-OAuth authenticator path even though a per-database OAuth2 client and user token are
   configured.
   ```
   </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=3592a871e4e647839dcf38729bdf45e4&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=3592a871e4e647839dcf38729bdf45e4&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:** 274:281
   **Comment:**
   	*Api Mismatch: The OAuth gating in impersonation checks only `cls.is_oauth2_enabled()`, which reads global `DATABASE_OAUTH2_CLIENTS` config and ignores database-level `oauth2_client_info` stored in `encrypted_extra`. As a result, Snowflake connections configured with per-database OAuth2 clients can successfully fetch a user token but never switch the connection to OAuth authenticator, so queries keep using the non-OAuth auth path. Use the passed `database` object (for example `database.is_oauth2_enabled()` / `database.get_oauth2_config()`) for these checks instead of class-level global config.
   
   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=3325b90023db062cf366463c78eb67abe45df4cecf95d59e97b48b7c0e9b4e71&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=3325b90023db062cf366463c78eb67abe45df4cecf95d59e97b48b7c0e9b4e71&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4819670642

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4766238624

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4861944356

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "htamakos (via GitHub)" <gi...@apache.org>.
htamakos commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4921005325

   @rusackas 
   Following up on this: after addressing the bot's CRITICAL findings, I ran into a failing unit test that took me a while to track down. I've now fixed the issue, and the CI is passing again.
   
   Would you mind taking another look when you have a chance? Thanks


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564844477


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -135,6 +161,71 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True
+    oauth2_exception = CustomSnowflakeAuthError
+
+    @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:
+            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})
+
+        return url, engine_kwargs
+
+    @classmethod
+    def get_oauth2_authorization_uri(
+        cls,
+        config: OAuth2ClientConfig,
+        state: OAuth2State,
+    ) -> str:
+        """
+        Return URI for initial OAuth2 request.
+        """
+        uri = config["authorization_request_uri"]
+        # When calling the Snowflake OAuth authorization endpoint for a custom client,
+        # specify only the query parameters documented in the URL below.
+        # Adding unsupported parameters
+        # (e.g., `prompt` as used in BaseEngineSpec.get_oauth2_authorization_uri)
+        # will cause an error.
+        # https://docs.snowflake.com/user-guide/oauth-custom#query-parameters
+        params = {
+            "scope": config["scope"],
+            "response_type": "code",
+            "state": encode_oauth2_state(state),
+            "redirect_uri": config["redirect_uri"],
+            "client_id": config["id"],
+        }
+        return parse.urljoin(uri, "?" + parse.urlencode(params))

Review Comment:
   Checked this โ€” it's not actually a bug. `urljoin(base, "?query")` follows RFC 3986 ยง5.3: a relative reference consisting only of a query component resolves against the base URI by keeping its path and replacing only the query. Verified in Python directly: `urljoin('https://acct.snowflakecomputing.com/oauth/authorize', '?scope=s&client_id=c')` โ†’ `https://acct.snowflakecomputing.com/oauth/authorize?scope=s&client_id=c` โ€” path preserved, query replaced, exactly as intended. Not applying the suggested rewrite.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -33,19 +33,45 @@
 from sqlalchemy import types
 from sqlalchemy.engine.reflection import Inspector
 from sqlalchemy.engine.url import URL
+from sqlalchemy.exc import DatabaseError as SqlalchemyDatabaseError
 
+from superset import is_feature_enabled, security_manager
 from superset.constants import TimeGrain
 from superset.databases.utils import make_url_safe
 from superset.db_engine_specs.base import BaseEngineSpec, BasicPropertiesType
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    DatabaseError = Exception

Review Comment:
   Already addressed โ€” `CustomSnowflakeAuthErrorMeta` has a class docstring explaining its purpose and the `__instancecheck__`-only caveat.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -377,6 +468,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connects_args = params.get("connect_args", {})
+        if connects_args.get("authenticator") == "oauth":

Review Comment:
   Already addressed โ€” `CustomSnowflakeAuthError` has a one-line docstring pointing to the metaclass for details.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5081797995

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5081435555

   Following up on my own repro hunch, @htamakos: it's not your tests. `test_bigquery.py` and `bigquery.py` are byte-identical to master, none of your added tests sort ahead of bigquery in collection order, and master runs these same five green every time. So it's a pre-existing isolation flake in the suite, not this PR. Re-ran the job to get a clean pass; nothing for you to fix here.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5126390930

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-4963075228

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3726410179

   CodeAnt AI is running Incremental review
   
   ---
   
   ### Thanks for using CodeAnt! ๐ŸŽ‰
   
   We're free for open-source projects. if you're enjoying it, help us grow by sharing.
   
   [Share on X](https://twitter.com/intent/tweet?text=Just%20tried%20%40CodeAntAI%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A&url=https%3A//codeant.ai) ยท
   [Reddit](https://www.reddit.com/submit?title=Check%20out%20CodeAnt%20for%20automated%20code%20review&text=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos.%20Worth%20checking%20out%3A%20https%3A//codeant.ai) ยท
   [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcodeant.ai&mini=true&title=Check%20out%20CodeAnt%20for%20automated%20code%20review&summary=Just%20tried%20CodeAnt%20for%20automated%20code%20review%20and%20I%27m%20impressed%21%20Free%20for%20open%20source%20with%20a%20free%20trial%20for%20private%20repos)
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3697013494

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5041998035

   @htamakos thanks for chasing this! `unit-tests` is still red, and it's the five `test_bigquery.py::test_fetch_data_*` cases rather than your Snowflake code. `mocker.patch("...bigquery.g")` is coming back an `AsyncMock`, so `g.bq_memory_limited` never gets set. Smells like isolation bleed from a leaked context somewhere in the new tests. Can you repro locally?


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3553876048


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    def __instancecheck__(cls, instance: object) -> bool:
+        return (
+            isinstance(instance, SqlalchemyDatabaseError)
+            and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
+            and "Invalid OAuth access token" in str(instance)
+        )
+
+
+class CustomSnowflakeAuthError(DatabaseError, metaclass=CustomSnowflakeAuthErrorMeta):
+    pass

Review Comment:
   Optional, not a blocker: a docstring here documents the matcher and flags that it only fires via `isinstance` (the `needs_oauth2` path) since `except` clauses don't honor `__instancecheck__`. Doubles as a fix for the CodeAnt docstring nits on this block. :)
   
   ```suggestion
   class CustomSnowflakeAuthErrorMeta(type):
       """
       Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
       OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
       ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
   
       This is only honored via ``isinstance()`` (the path used by
       ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
       ``__instancecheck__``, so it must not be relied on for exception catching.
       """
   
       def __instancecheck__(cls, instance: object) -> bool:
           return (
               isinstance(instance, SqlalchemyDatabaseError)
               and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
               and "Invalid OAuth access token" in str(instance)
           )
   
   
   class CustomSnowflakeAuthError(DatabaseError, metaclass=CustomSnowflakeAuthErrorMeta):
       """Snowflake OAuth error type matched via the metaclass above (see note there)."""
   ```
   



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564845633


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    def __instancecheck__(cls, instance: object) -> bool:
+        return (
+            isinstance(instance, SqlalchemyDatabaseError)
+            and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
+            and "Invalid OAuth access token" in str(instance)
+        )

Review Comment:
   Applied โ€” `__instancecheck__` now has a docstring explaining the raw-vs-SQLAlchemy-wrapped matching it does (08d490e29a), added alongside a real fix to what it matches (see the reply on the newer critical-severity comment below on this same method).



##########
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"]
+        )

Review Comment:
   Already addressed โ€” `impersonate_user` gates on `database.is_oauth2_enabled()` (an instance method that checks per-database `encrypted_extra` config first, falling back to the class-level check), not just `cls.is_oauth2_enabled()`. Confirmed by reading `Database.is_oauth2_enabled()` in `superset/models/core.py`, which does exactly this.



##########
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})
+
+        return url, engine_kwargs
+
+    @classmethod
+    def get_oauth2_authorization_uri(
+        cls,
+        config: OAuth2ClientConfig,
+        state: OAuth2State,
+        code_verifier: str | None = None, # pylint: disable=unused-argument
+    ) -> str:
+        """
+        Return URI for initial OAuth2 request.
+        """
+        uri = config["authorization_request_uri"]
+        # When calling the Snowflake OAuth authorization endpoint for a custom client,
+        # specify only the query parameters documented in the URL below.
+        # Adding unsupported parameters
+        # (e.g., `prompt` as used in BaseEngineSpec.get_oauth2_authorization_uri)
+        # will cause an error.
+        # https://docs.snowflake.com/user-guide/oauth-custom#query-parameters
+        params = {
+            "scope": config["scope"],
+            "response_type": "code",
+            "state": encode_oauth2_state(state),
+            "redirect_uri": config["redirect_uri"],
+            "client_id": config["id"],
+        }
+        return parse.urljoin(uri, "?" + parse.urlencode(params))

Review Comment:
   Already addressed โ€” `get_oauth2_authorization_uri` now adds `code_challenge`/`code_challenge_method` when `code_verifier` is provided.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564844566


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -33,19 +33,45 @@
 from sqlalchemy import types
 from sqlalchemy.engine.reflection import Inspector
 from sqlalchemy.engine.url import URL
+from sqlalchemy.exc import DatabaseError as SqlalchemyDatabaseError
 
+from superset import is_feature_enabled, security_manager
 from superset.constants import TimeGrain
 from superset.databases.utils import make_url_safe
 from superset.db_engine_specs.base import BaseEngineSpec, BasicPropertiesType
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    DatabaseError = Exception

Review Comment:
   Already addressed โ€” `CustomSnowflakeAuthErrorMeta` has a class docstring explaining its purpose and the `__instancecheck__`-only caveat.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -377,6 +468,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connects_args = params.get("connect_args", {})
+        if connects_args.get("authenticator") == "oauth":

Review Comment:
   Already addressed โ€” `CustomSnowflakeAuthError` has a one-line docstring pointing to the metaclass for details.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):

Review Comment:
   Already addressed โ€” `CustomSnowflakeAuthErrorMeta` has a class docstring (added in a later push) explaining what it matches and the isinstance()-only caveat.



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,43 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    def __instancecheck__(cls, instance: object) -> bool:
+        return (
+            isinstance(instance, SqlalchemyDatabaseError)
+            and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
+            and "Invalid OAuth access token" in str(instance)
+        )
+
+
+class CustomSnowflakeAuthError(DatabaseError, metaclass=CustomSnowflakeAuthErrorMeta):
+    pass

Review Comment:
   Already addressed โ€” `CustomSnowflakeAuthError` has a one-line docstring pointing to the metaclass for details.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3686026884


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -440,6 +605,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connect_args: dict[str, Any] = params.get("connect_args") or {}
+        if connect_args.get("authenticator") == "oauth":
+            return

Review Comment:
   Codeant's right that this function can't see the URL query string on its own, but it doesn't need to. It only ever runs after `impersonate_user`, which already sets `connect_args["authenticator"] = "oauth"` on the same `engine_kwargs` dict first (see `models/core.py` around line 679). So the guard does catch the case that actually matters here.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5146020056

   Seeing if I can get CI to pass here... would love to see this one wrapped up and off our collective radar ;)


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5196196456

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5405138494

   The epic journey finally concludes!
   
   <img src="https://static.klipy.com/ii/4e7bea9f7a3371424e6c16ebc93252fe/c9/4c/jwXhg8sqzf4JAwWOP6.gif"/>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-3726601647

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3679390639


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -440,6 +605,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connect_args: dict[str, Any] = params.get("connect_args") or {}
+        if connect_args.get("authenticator") == "oauth":
+            return

Review Comment:
   **Suggestion:** The encrypted-extra loader receives only `engine_kwargs`, not the SQLAlchemy URL, so this guard cannot detect `authenticator=oauth` configured in the URI query string. A Snowflake URI using OAuth together with key-pair data in `encrypted_extra` will therefore still load the private key into `connect_args`, producing conflicting authentication parameters and potentially preventing the OAuth connection from being created. Inspect the URL authentication mode before loading encrypted authentication parameters, or normalize the authenticator into the same parameter set first. [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ Explicit Snowflake OAuth connections may fail.
   - โŒ Key-pair credentials can conflict with OAuth authentication.
   - โš ๏ธ Connection validation becomes configuration-dependent.
   ```
   </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=5a708822e8b94299b1bd6707522e8cef&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=5a708822e8b94299b1bd6707522e8cef&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:** 616:618
   **Comment:**
   	*Api Mismatch: The encrypted-extra loader receives only `engine_kwargs`, not the SQLAlchemy URL, so this guard cannot detect `authenticator=oauth` configured in the URI query string. A Snowflake URI using OAuth together with key-pair data in `encrypted_extra` will therefore still load the private key into `connect_args`, producing conflicting authentication parameters and potentially preventing the OAuth connection from being created. Inspect the URL authentication mode before loading encrypted authentication parameters, or normalize the authenticator into the same parameter set first.
   
   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=df4e7a24fd667f2f07bbc7859ec4cf234baf1f2ad9bc0cafc657b9a2338aa649&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=df4e7a24fd667f2f07bbc7859ec4cf234baf1f2ad9bc0cafc657b9a2338aa649&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3679374087


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,61 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        """
+        Match Snowflake's invalid/expired OAuth token error, whether it arrives
+        wrapped by SQLAlchemy (e.g. ``Engine``-based execution) or as the raw
+        DBAPI exception โ€” ``BaseEngineSpec.execute()`` runs against a bare
+        cursor and never wraps it, so both shapes must be handled here.
+        """
+        orig: object = instance
+        if isinstance(instance, SqlalchemyDatabaseError):
+            orig = cast(SqlalchemyDatabaseError, instance).orig
+
+        return isinstance(orig, DatabaseError) and "Invalid OAuth access token" in str(
+            orig
+        )
+
+
+class CustomSnowflakeAuthError(DatabaseError, metaclass=CustomSnowflakeAuthErrorMeta):
+    """Snowflake OAuth error type matched via the metaclass above (see note there)."""

Review Comment:
   Good catch, fixed! `OAuth2TokenRefreshError` isn't actually a subclass of `CustomSnowflakeAuthError`, so `except db_engine_spec.oauth2_exception` in `refresh_oauth2_token` was never catching it. Added it to the tuple, plus a regression test.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3627560873


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,61 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        """
+        Match Snowflake's invalid/expired OAuth token error, whether it arrives
+        wrapped by SQLAlchemy (e.g. ``Engine``-based execution) or as the raw
+        DBAPI exception โ€” ``BaseEngineSpec.execute()`` runs against a bare
+        cursor and never wraps it, so both shapes must be handled here.
+        """
+        orig: object = instance
+        if isinstance(instance, SqlalchemyDatabaseError):
+            orig = cast(SqlalchemyDatabaseError, instance).orig
+
+        return isinstance(orig, DatabaseError) and "Invalid OAuth access token" in str(
+            orig
+        )

Review Comment:
   `connect_args` lives inside `engine_kwargs`, which is also part of the cache key (`repr(sorted(engine_kwargs.items()))`), so moving the token there fragments the cache exactly the same way. That `_ENGINE_CACHE` growth is shared by every OAuth2 spec, not something this PR introduces.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3565173448


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +242,105 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True

Review Comment:
   Applied โ€” `supports_oauth2: bool = True` (8ba0c75b39).



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -191,6 +242,105 @@ class SnowflakeEngineSpec(PostgresBaseEngineSpec):
         ),
     }
 
+    # OAuth 2.0 support
+    supports_oauth2 = True
+    oauth2_exception = CustomSnowflakeAuthError

Review Comment:
   Applied โ€” `oauth2_exception: type[Exception] = CustomSnowflakeAuthError` (8ba0c75b39).



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")

Review Comment:
   Applied โ€” `requests: mock.MagicMock = mocker.patch(...)` (8ba0c75b39).



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +439,177 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database = Database(sqlalchemy_uri="snowflake://abc")

Review Comment:
   Applied โ€” `database: Database = Database(...)` (8ba0c75b39).



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3564726709


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,53 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        return (
+            isinstance(instance, SqlalchemyDatabaseError)
+            and isinstance(cast(SqlalchemyDatabaseError, instance).orig, DatabaseError)
+            and "Invalid OAuth access token" in str(instance)
+        )

Review Comment:
   **Suggestion:** The OAuth error matcher only recognizes SQLAlchemy-wrapped `DatabaseError` instances with `.orig`, but query execution paths use raw DBAPI cursor exceptions as well. When token failures surface as direct Snowflake connector errors, this check returns false and the OAuth re-auth flow is not triggered. Expand the matcher to also handle direct Snowflake DBAPI exceptions (not only SQLAlchemy wrappers). [api mismatch]
   
   <details>
   <summary><b>Severity Level:</b> Critical ๐Ÿšจ</summary>
   
   ```mdx
   - โŒ SQL Lab queries fail after token revocation.
   - โš ๏ธ Dashboards using Snowflake OAuth donโ€™t auto re-auth.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction โœ… </b></summary>
   
   ```mdx
   1. Configure Snowflake OAuth2 for Superset so that `SnowflakeEngineSpec.supports_oauth2`
   is True and a client is registered in `DATABASE_OAUTH2_CLIENTS`, and enable database-level
   OAuth (see `Database.is_oauth2_enabled` and `get_oauth2_config` at
   `superset/models/core.py:1360-1385`). Run an interactive SQL Lab query against this
   Snowflake database (entry point `superset/sql_lab.py:495-513` where
   `database.get_raw_connection` is used).
   
   2. Ensure the user has an OAuth2 access token stored (via the OAuth dance), but the token
   becomes invalid server-side (revoked or otherwise rejected) while still present in
   Superset. The query execution path uses `database.get_raw_connection`
   (`superset/models/core.py:619-49`) and then `execute_sql_with_cursor`
   (`superset/sql/execution/executor.py:96-79`), which internally calls
   `database.db_engine_spec.execute(cursor, stmt_sql, database)` for each statement.
   
   3. Inside `BaseEngineSpec.execute` (`superset/db_engine_specs/base.py:2169-27`),
   `cursor.execute(query)` is invoked directly on the Snowflake DBAPI cursor. When the token
   is invalid, the Snowflake connector raises a raw
   `snowflake.connector.errors.DatabaseError` with a message containing "Invalid OAuth access
   token". The `except Exception as ex` block catches this DBAPI exception and evaluates
   `database.is_oauth2_enabled() and cls.needs_oauth2(ex)`.
   
   4. For Snowflake, `cls.oauth2_exception` is `CustomSnowflakeAuthError`
   (`superset/db_engine_specs/snowflake.py:92-93`), whose metaclass
   `CustomSnowflakeAuthErrorMeta.__instancecheck__` at
   `superset/db_engine_specs/snowflake.py:84-89` returns True only when `instance` is a
   `SqlalchemyDatabaseError` whose `.orig` is `DatabaseError` and whose string contains
   "Invalid OAuth access token`. Since the exception `ex` here is a direct DBAPI
   `DatabaseError`, not a `SqlalchemyDatabaseError`, `isinstance(ex, cls.oauth2_exception)`
   is False, so `BaseEngineSpec.needs_oauth2(ex)`
   (`superset/db_engine_specs/base.py:2195-10`) returns False. As a result, OAuth2 re-auth is
   not triggered; `BaseEngineSpec.execute` falls through to `raise
   cls.get_dbapi_mapped_exception(ex)`, and the user sees a query failure instead of being
   sent through `start_oauth2_dance` to refresh/reauthorize their Snowflake OAuth token.
   ```
   </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=4e7b9437d78c4cb1a912ae12862bd4ef&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=4e7b9437d78c4cb1a912ae12862bd4ef&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:** 85:89
   **Comment:**
   	*Api Mismatch: The OAuth error matcher only recognizes SQLAlchemy-wrapped `DatabaseError` instances with `.orig`, but query execution paths use raw DBAPI cursor exceptions as well. When token failures surface as direct Snowflake connector errors, this check returns false and the OAuth re-auth flow is not triggered. Expand the matcher to also handle direct Snowflake DBAPI exceptions (not only SQLAlchemy wrappers).
   
   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=0201d40c7a7fb692920f1e2748854e3a1953c81650fa770e3b15c96ce7999d7c&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=0201d40c7a7fb692920f1e2748854e3a1953c81650fa770e3b15c96ce7999d7c&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3565305069


##########
superset/db_engine_specs/snowflake.py:
##########
@@ -44,12 +46,61 @@
 from superset.db_engine_specs.postgres import PostgresBaseEngineSpec
 from superset.errors import ErrorLevel, SupersetError, SupersetErrorType
 from superset.models.sql_lab import Query
+from superset.superset_typing import (
+    OAuth2ClientConfig,
+    OAuth2State,
+)
 from superset.utils import json
 from superset.utils.core import get_user_agent, QuerySource
+from superset.utils.oauth2 import encode_oauth2_state, generate_code_challenge
 
 if TYPE_CHECKING:
     from superset.models.core import Database
 
+try:
+    from snowflake.connector.errors import DatabaseError
+except ImportError:
+    # Use a distinct sentinel type when snowflake is not installed to avoid
+    # matching unrelated exception types (using `Exception` would be too broad).
+    class _SnowflakeDatabaseError(Exception):
+        """Sentinel type to stand in for snowflake.connector.errors.DatabaseError."""
+
+        pass
+
+    DatabaseError = _SnowflakeDatabaseError
+
+
+class CustomSnowflakeAuthErrorMeta(type):
+    """
+    Metaclass whose ``__instancecheck__`` matches Snowflake's invalid/expired
+    OAuth access-token error, so ``CustomSnowflakeAuthError`` can be used as the
+    ``oauth2_exception`` that triggers the OAuth2 re-auth dance.
+
+    This is only honored via ``isinstance()`` (the path used by
+    ``BaseEngineSpec.needs_oauth2()``); ``except`` clauses do not call
+    ``__instancecheck__``, so it must not be relied on for exception catching.
+    """
+
+    def __instancecheck__(cls, instance: object) -> bool:
+        """
+        Match Snowflake's invalid/expired OAuth token error, whether it arrives
+        wrapped by SQLAlchemy (e.g. ``Engine``-based execution) or as the raw
+        DBAPI exception โ€” ``BaseEngineSpec.execute()`` runs against a bare
+        cursor and never wraps it, so both shapes must be handled here.
+        """
+        orig = instance

Review Comment:
   Applied โ€” `orig: object = instance` (434074ac72).



##########
superset/db_engine_specs/snowflake.py:
##########
@@ -438,6 +596,18 @@ def update_params_from_encrypted_extra(
         database: "Database",
         params: dict[str, Any],
     ) -> None:
+        # To use OAuth authentication, a database connection must first be created using
+        # another authenticator (typically key-pair authentication)
+        # with โ€œImpersonate logged in userโ€ enabled.
+        # Key-pair authentication is used for connection tests,
+        # while OAuth authentication is used when executing actual queries,
+        # such as in SQL Lab or dashboards.
+        # Therefore, when using OAuth authentication, the key-pair authentication
+        # settings are not loaded, and the connection is established using OAuth only.
+        connect_args = params.get("connect_args") or {}

Review Comment:
   Applied โ€” `connect_args: dict[str, Any] = params.get("connect_args") or {}` (434074ac72).



##########
tests/unit_tests/db_engine_specs/test_snowflake.py:
##########
@@ -438,3 +440,206 @@ def test_unmask_encrypted_extra() -> None:
             },
         }
     )
+
+
+@pytest.fixture
+def oauth2_config() -> OAuth2ClientConfig:
+    """
+    Config for Snowflake OAuth2.
+    """
+    return {
+        "id": "snowflake-oauth2-client-id",
+        "secret": "snowflake-oauth2-client-secret",
+        "scope": "refresh_token",
+        "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+        "authorization_request_uri": "https://snowflake.oauth2.example/oauth/authorize",
+        "token_request_uri": "https://snowflake.oauth2.example/oauth/token-request",
+        "request_content_type": "data",
+    }
+
+
+def test_get_oauth2_token(
+    mocker: MockerFixture,
+    oauth2_config: OAuth2ClientConfig,
+) -> None:
+    """
+    Test `get_oauth2_token`.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+
+    requests: mock.MagicMock = mocker.patch("superset.db_engine_specs.base.requests")
+    requests.post().json.return_value = {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+
+    assert SnowflakeEngineSpec.get_oauth2_token(oauth2_config, "code") == {
+        "access_token": "access-token",
+        "expires_in": 3600,
+        "scope": "scope",
+        "token_type": "Bearer",
+        "refresh_token": "refresh-token",
+    }
+    requests.post.assert_called_with(
+        "https://snowflake.oauth2.example/oauth/token-request",
+        data={
+            "code": "code",
+            "client_id": "snowflake-oauth2-client-id",
+            "client_secret": "snowflake-oauth2-client-secret",
+            "redirect_uri": "http://localhost:8088/api/v1/database/oauth2/",
+            "grant_type": "authorization_code",
+        },
+        timeout=30.0,
+    )
+
+
+def test_impersonate_user(app: SupersetApp, mocker: MockerFixture) -> None:
+    """
+    Test that Snowflake supports user impersonation.
+
+    Impersonation only applies within a request context (see
+    ``test_impersonate_user_outside_request_context`` below for the
+    background-execution case), so these assertions run inside one.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database: Database = Database(sqlalchemy_uri="snowflake://abc")
+
+    mocker.patch(
+        "superset.db_engine_specs.snowflake.SnowflakeEngineSpec.is_oauth2_enabled",
+        return_value=True,
+    )
+
+    with app.test_request_context("/some/place/"):
+        assert SnowflakeEngineSpec.impersonate_user(
+            database=database,
+            username=None,
+            user_token=None,
+            url=make_url("snowflake://user:pass@account/database_name/default"),
+            engine_kwargs={
+                "connect_args": {
+                    "validate_default_parameters": True,
+                },
+            },
+        ) == (
+            make_url("snowflake://user:pass@account/database_name/default"),
+            {"connect_args": {"validate_default_parameters": True}},
+        )
+
+        assert SnowflakeEngineSpec.impersonate_user(
+            database=database,
+            username=None,
+            user_token=None,
+            url=make_url("snowflake://user:pass@account/database_name/default"),
+            engine_kwargs={},
+        ) == (
+            make_url(
+                "snowflake://user:pass@account/database_name/default?authenticator=oauth"
+            ),
+            {"connect_args": {"authenticator": "oauth"}},
+        )
+
+        mocker.patch(
+            "superset.db_engine_specs.snowflake.is_feature_enabled",
+            return_value=True,
+        )
+
+        mocker.patch(
+            "superset.security_manager.find_user",
+            return_value=mocker.MagicMock(email="impersonated_user@example.com"),
+        )
+        assert SnowflakeEngineSpec.impersonate_user(
+            database=database,
+            username="impersonated_user",
+            user_token="test_token",  # noqa: S106
+            url=make_url("snowflake://user:pass@account/database_name/default"),
+            engine_kwargs={},
+        ) == (
+            make_url(
+                "snowflake://impersonated_user:pass@account/database_name/default?authenticator=oauth&token=test_token"
+            ),
+            {"connect_args": {"authenticator": "oauth"}},
+        )
+
+
+def test_impersonate_user_outside_request_context(mocker: MockerFixture) -> None:
+    """
+    Background executions (alerts/reports) have no per-user token, so OAuth
+    impersonation must not engage outside a request context โ€” even when
+    ``database.is_oauth2_enabled()`` returns True because of a
+    database-level OAuth2 client config, which (unlike the app-config-based
+    check) isn't itself request-context-aware.
+    """
+    from superset.db_engine_specs.snowflake import SnowflakeEngineSpec
+    from superset.models.core import Database
+
+    database: Database = Database(sqlalchemy_uri="snowflake://abc")
+    mocker.patch.object(Database, "is_oauth2_enabled", return_value=True)
+
+    url = make_url("snowflake://user:pass@account/database_name/default")

Review Comment:
   Applied โ€” `url: URL = make_url(...)` (434074ac72).



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3565326090


##########
superset-frontend/src/features/databases/DatabaseModal/ExtraOptions.tsx:
##########
@@ -498,7 +498,7 @@ const ExtraOptions = ({
                     onChange={onInputChange}
                   >
                     {t(
-                      'Impersonate logged in user (Presto, Trino, Drill, Hive, and Google Sheets)',
+                      'Impersonate logged in user (Presto, Trino, Drill, Hive, Snowflake and Google Sheets)',

Review Comment:
   Confirmed and applied (b45276bfd8) โ€” added a Snowflake/Google Sheets sentence to the tooltip (both impersonate via the user's own OAuth credentials rather than a shared service account, per `SnowflakeEngineSpec.impersonate_user`/`GSheetsEngineSpec.impersonate_user`), so the label and the explanatory copy stay in sync.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #36856:
URL: https://github.com/apache/superset/pull/36856#discussion_r3573281804


##########
tests/unit_tests/sql_lab_test.py:
##########
@@ -198,74 +198,82 @@ def test_get_sql_results_oauth2(mocker: MockerFixture, app) -> None:
     """
     Test that `get_sql_results` works with OAuth2.
     """
+    # Pushed/popped manually (rather than via a ``with`` block) so the
+    # ``finally`` below still pops it if an assertion fails, preventing the
+    # request context from leaking into later tests in the same session.
     app_context = app.test_request_context()
     app_context.push()
 
-    mocker.patch(
-        "superset.db_engine_specs.base.uuid4",
-        return_value=UUID("fb11f528-6eba-4a8a-837e-6b0d39ee9187"),
-    )
-    mocker.patch(
-        "superset.db_engine_specs.base.generate_code_verifier",
-        return_value="xkBPVZoFChVcy3VZ2l5u7d0FZPTU-olO7HtsAOok2IUGigyoZ62tG_oldy2xg9_HdqPKrWUmKZLmU-CUqz_SQ",
-    )
-    mocker.patch("superset.daos.key_value.KeyValueDAO.delete_expired_entries")
-    mocker.patch("superset.daos.key_value.KeyValueDAO.create_entry")
-    mocker.patch("superset.db_engine_specs.base.db.session.commit")
-
-    g = mocker.patch("superset.db_engine_specs.base.g")
-    g.user = mocker.MagicMock()
-    g.user.id = 42
-
-    database = Database(
-        id=1,
-        database_name="my_db",
-        sqlalchemy_uri="sqlite://",
-        encrypted_extra=json.dumps(oauth2_client_info),
-    )
-    database.db_engine_spec.oauth2_exception = OAuth2Error
-    get_sqla_engine = mocker.patch.object(database, "get_sqla_engine")
-    get_sqla_engine().__enter__().raw_connection.side_effect = OAuth2Error(
-        "OAuth2 required"
-    )
+    try:
+        mocker.patch(
+            "superset.db_engine_specs.base.uuid4",
+            return_value=UUID("fb11f528-6eba-4a8a-837e-6b0d39ee9187"),
+        )
+        mocker.patch(
+            "superset.db_engine_specs.base.generate_code_verifier",
+            return_value="xkBPVZoFChVcy3VZ2l5u7d0FZPTU-olO7HtsAOok2IUGigyoZ62tG_oldy2xg9_HdqPKrWUmKZLmU-CUqz_SQ",
+        )
+        mocker.patch("superset.daos.key_value.KeyValueDAO.delete_expired_entries")
+        mocker.patch("superset.daos.key_value.KeyValueDAO.create_entry")
+        mocker.patch("superset.db_engine_specs.base.db.session.commit")
+
+        g = mocker.patch("superset.db_engine_specs.base.g")
+        g.user = mocker.MagicMock()
+        g.user.id = 42
+
+        database = Database(
+            id=1,
+            database_name="my_db",
+            sqlalchemy_uri="sqlite://",
+            encrypted_extra=json.dumps(oauth2_client_info),
+        )
+        database.db_engine_spec.oauth2_exception = OAuth2Error
+        get_sqla_engine = mocker.patch.object(database, "get_sqla_engine")
+        get_sqla_engine().__enter__().raw_connection.side_effect = OAuth2Error(
+            "OAuth2 required"
+        )
 
-    query = mocker.MagicMock(select_as_cta=False, database=database)
-    mocker.patch("superset.sql_lab.get_query", return_value=query)
+        query = mocker.MagicMock(select_as_cta=False, database=database)
+        mocker.patch("superset.sql_lab.get_query", return_value=query)
+
+        payload = get_sql_results(query_id=1, rendered_query="SELECT 1")

Review Comment:
   **Suggestion:** Add a concrete type annotation for this response payload variable so the modified test code remains fully type-hinted. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This newly added local variable is unannotated in modified Python code, so it matches the rule requiring type hints for relevant variables that can be annotated.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=31f1485692274b77bf9b8d39ed07362e&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=31f1485692274b77bf9b8d39ed07362e&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/sql_lab_test.py
   **Line:** 239:239
   **Comment:**
   	*Custom Rule: Add a concrete type annotation for this response payload variable so the modified test code remains fully type-hinted.
   
   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=7ea03a83840d78df3db1dee9cd07bffd4243c1505a3f503b6a6d6a3c3e8597ba&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=7ea03a83840d78df3db1dee9cd07bffd4243c1505a3f503b6a6d6a3c3e8597ba&reaction=dislike'>๐Ÿ‘Ž</a>



##########
tests/unit_tests/sql_lab_test.py:
##########
@@ -198,74 +198,82 @@ def test_get_sql_results_oauth2(mocker: MockerFixture, app) -> None:
     """
     Test that `get_sql_results` works with OAuth2.
     """
+    # Pushed/popped manually (rather than via a ``with`` block) so the
+    # ``finally`` below still pops it if an assertion fails, preventing the
+    # request context from leaking into later tests in the same session.
     app_context = app.test_request_context()
     app_context.push()
 
-    mocker.patch(
-        "superset.db_engine_specs.base.uuid4",
-        return_value=UUID("fb11f528-6eba-4a8a-837e-6b0d39ee9187"),
-    )
-    mocker.patch(
-        "superset.db_engine_specs.base.generate_code_verifier",
-        return_value="xkBPVZoFChVcy3VZ2l5u7d0FZPTU-olO7HtsAOok2IUGigyoZ62tG_oldy2xg9_HdqPKrWUmKZLmU-CUqz_SQ",
-    )
-    mocker.patch("superset.daos.key_value.KeyValueDAO.delete_expired_entries")
-    mocker.patch("superset.daos.key_value.KeyValueDAO.create_entry")
-    mocker.patch("superset.db_engine_specs.base.db.session.commit")
-
-    g = mocker.patch("superset.db_engine_specs.base.g")
-    g.user = mocker.MagicMock()
-    g.user.id = 42
-
-    database = Database(
-        id=1,
-        database_name="my_db",
-        sqlalchemy_uri="sqlite://",
-        encrypted_extra=json.dumps(oauth2_client_info),
-    )
-    database.db_engine_spec.oauth2_exception = OAuth2Error
-    get_sqla_engine = mocker.patch.object(database, "get_sqla_engine")
-    get_sqla_engine().__enter__().raw_connection.side_effect = OAuth2Error(
-        "OAuth2 required"
-    )
+    try:
+        mocker.patch(
+            "superset.db_engine_specs.base.uuid4",
+            return_value=UUID("fb11f528-6eba-4a8a-837e-6b0d39ee9187"),
+        )
+        mocker.patch(
+            "superset.db_engine_specs.base.generate_code_verifier",
+            return_value="xkBPVZoFChVcy3VZ2l5u7d0FZPTU-olO7HtsAOok2IUGigyoZ62tG_oldy2xg9_HdqPKrWUmKZLmU-CUqz_SQ",
+        )
+        mocker.patch("superset.daos.key_value.KeyValueDAO.delete_expired_entries")
+        mocker.patch("superset.daos.key_value.KeyValueDAO.create_entry")
+        mocker.patch("superset.db_engine_specs.base.db.session.commit")
+
+        g = mocker.patch("superset.db_engine_specs.base.g")
+        g.user = mocker.MagicMock()
+        g.user.id = 42
+
+        database = Database(
+            id=1,
+            database_name="my_db",
+            sqlalchemy_uri="sqlite://",
+            encrypted_extra=json.dumps(oauth2_client_info),
+        )
+        database.db_engine_spec.oauth2_exception = OAuth2Error
+        get_sqla_engine = mocker.patch.object(database, "get_sqla_engine")
+        get_sqla_engine().__enter__().raw_connection.side_effect = OAuth2Error(
+            "OAuth2 required"
+        )
 
-    query = mocker.MagicMock(select_as_cta=False, database=database)
-    mocker.patch("superset.sql_lab.get_query", return_value=query)
+        query = mocker.MagicMock(select_as_cta=False, database=database)
+        mocker.patch("superset.sql_lab.get_query", return_value=query)
+
+        payload = get_sql_results(query_id=1, rendered_query="SELECT 1")
+        assert payload["status"] == QueryStatus.FAILED
+        assert payload["error"] == "You don't have permission to access the data."
+        assert len(payload["errors"]) == 1
+
+        error = payload["errors"][0]
+        assert error["message"] == "You don't have permission to access the data."
+        assert error["error_type"] == SupersetErrorType.OAUTH2_REDIRECT
+        assert error["level"] == ErrorLevel.WARNING
+        assert error["extra"]["tab_id"] == "fb11f528-6eba-4a8a-837e-6b0d39ee9187"
+        assert (
+            error["extra"]["redirect_uri"] == "http://localhost/api/v1/database/oauth2/"
+        )
 
-    payload = get_sql_results(query_id=1, rendered_query="SELECT 1")
-    assert payload["status"] == QueryStatus.FAILED
-    assert payload["error"] == "You don't have permission to access the data."
-    assert len(payload["errors"]) == 1
-
-    error = payload["errors"][0]
-    assert error["message"] == "You don't have permission to access the data."
-    assert error["error_type"] == SupersetErrorType.OAUTH2_REDIRECT
-    assert error["level"] == ErrorLevel.WARNING
-    assert error["extra"]["tab_id"] == "fb11f528-6eba-4a8a-837e-6b0d39ee9187"
-    assert error["extra"]["redirect_uri"] == "http://localhost/api/v1/database/oauth2/"
-
-    # Parse the OAuth2 authorization URL and verify components individually,
-    # since the JWT state and PKCE code_challenge are computed deterministically
-    # from mocked inputs but their exact encoding depends on library internals.
-    url = urlparse(error["extra"]["url"])
-    assert url.scheme == "https"
-    assert url.netloc == "abcd1234.snowflakecomputing.com"
-    assert url.path == "/oauth/authorize"
-
-    params = parse_qs(url.query)
-    assert params["scope"] == ["refresh_token session:role:USERADMIN"]
-    assert params["response_type"] == ["code"]
-    assert params["redirect_uri"] == ["http://localhost/api/v1/database/oauth2/"]
-    assert params["client_id"] == ["my_client_id"]
-    assert params["code_challenge_method"] == ["S256"]
-
-    # Verify PKCE code_challenge matches the mocked code_verifier
-    from superset.utils.oauth2 import generate_code_challenge
-
-    expected_code_challenge = generate_code_challenge(
-        "xkBPVZoFChVcy3VZ2l5u7d0FZPTU-olO7HtsAOok2IUGigyoZ62tG_oldy2xg9_HdqPKrWUmKZLmU-CUqz_SQ"
-    )
-    assert params["code_challenge"] == [expected_code_challenge]
+        # Parse the OAuth2 authorization URL and verify components individually,
+        # since the JWT state and PKCE code_challenge are computed deterministically
+        # from mocked inputs but their exact encoding depends on library internals.
+        url = urlparse(error["extra"]["url"])
+        assert url.scheme == "https"
+        assert url.netloc == "abcd1234.snowflakecomputing.com"
+        assert url.path == "/oauth/authorize"
+
+        params = parse_qs(url.query)

Review Comment:
   **Suggestion:** Add an explicit type annotation for this parsed query-parameter mapping to satisfy the type-hint requirement for relevant variables. [custom_rule]
   
   **Severity Level:** Minor ๐Ÿงน
   <details>
   <summary><b>Why it matters? โญ </b></summary>
   
   This new local variable is introduced without a type hint, and it is a relevant variable that could be annotated under the Python type-hint rule.
   </details>
   <details>
   <summary><b>Rule source ๐Ÿ“– </b></summary>
   
   .cursor/rules/dev-standard.mdc (line 28)
   </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=8f6b1fb9c67f4d2a8164bcf5395736e0&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=8f6b1fb9c67f4d2a8164bcf5395736e0&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/sql_lab_test.py
   **Line:** 261:261
   **Comment:**
   	*Custom Rule: Add an explicit type annotation for this parsed query-parameter mapping to satisfy the type-hint requirement for relevant variables.
   
   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=1176bced6062cbb3bcd78aadd4816213fe43c39c69110a1bf6fafed7b9a05564&reaction=like'>๐Ÿ‘</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36856&comment_hash=1176bced6062cbb3bcd78aadd4816213fe43c39c69110a1bf6fafed7b9a05564&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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(snowflake): Add support for OAuth 2.0 authentication [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #36856:
URL: https://github.com/apache/superset/pull/36856#issuecomment-5412014845

   Thank YOU! It's a great addition!


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org