FrankYang0529 opened a new pull request, #73162: URL: https://github.com/apache/airflow/pull/73162
## Why - `SnowflakeSqlApiHook.get_headers()` uses OAuth only when the connection has `refresh_token`, `client_id`, and `client_secret`. That check dates from #37922, when the SQL API hook only supported the refresh token grant. - `SnowflakeHook` later added the `client_credentials` grant (#51620) and `azure_conn_id` (#55874), and `_get_conn_params()` now fetches the access token for all three setups. The SQL API hook ignores that token, so `client_credentials` and `azure_conn_id` connections fall through to key pair auth and fail with `KeyError: 'user'`. ## How - When `authenticator` is `oauth`, build the header from the token that `_get_conn_params()` already fetched. The check uses `authenticator` instead of the presence of `token`, because Workload Identity connections can also set `token`. ## Verification - Unit test: `uv run --frozen --project providers/snowflake pytest providers/snowflake/tests/unit` - Integration test: 1. Setup Azure ```sh APP_ID="$(az ad app create --display-name airflow-snowflake-sql-api-demo --query appId -o tsv)" az ad sp create --id "$APP_ID" -o none CLIENT_SECRET="$(az ad app credential reset --id "$APP_ID" --display-name demo --query password -o tsv)" TOKEN_URL="https://login.microsoftonline.com/$(az account show --query tenantId -o tsv)/oauth2/v2.0/token" curl -s -u "$APP_ID:$CLIENT_SECRET" -d grant_type=client_credentials -d scope=https://management.azure.com/.default "$TOKEN_URL" | jq -r '.token_type // .error_description' export DEMO_DIR="$(mktemp -d)" export AIRFLOW_HOME="$DEMO_DIR/airflow-home" export AIRFLOW__SNOWFLAKE__AZURE_OAUTH_SCOPE="https://management.azure.com/.default" export AIRFLOW_CONN_SNOWFLAKE_REFRESH_TOKEN='{"conn_type": "snowflake", "login": "local-client-id", "password": "local-client-secret", "extra": {"account": "demo-account", "refresh_token": "local-refresh-token", "token_endpoint": "http://127.0.0.1:18765/oauth/token-request"}}' export AIRFLOW_CONN_SNOWFLAKE_CLIENT_CREDENTIALS="$(jq -cn --arg id "$APP_ID" --arg secret "$CLIENT_SECRET" --arg url "$TOKEN_URL" '{conn_type: "snowflake", login: $id, password: $secret, extra: {account: "demo-account", authenticator: "oauth", grant_type: "client_credentials", token_endpoint: $url, scope: "https://management.azure.com/.default"}}')" export AIRFLOW_CONN_AZURE_ENTRA='{"conn_type": "azure", "extra": {"use_azure_identity_object": true}}' export AIRFLOW_CONN_SNOWFLAKE_AZURE='{"conn_type": "snowflake", "extra": {"account": "demo-account", "authenticator": "oauth", "azure_conn_id": "azure_entra"}}' ``` 2. Setup script to use `SnowflakeSqlApiHook` ```sh cat > "$DEMO_DIR/show_headers.py" <<'EOF' import base64 import json import threading import warnings from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs from airflow.exceptions import AirflowProviderDeprecationWarning from airflow.providers.snowflake.hooks.snowflake_sql_api import SnowflakeSqlApiHook class LocalRefreshTokenEndpoint(BaseHTTPRequestHandler): def do_POST(self): form = parse_qs(self.rfile.read(int(self.headers["Content-Length"])).decode()) expected_auth = "Basic " + base64.b64encode(b"local-client-id:local-client-secret").decode() auth_ok = self.headers.get("Authorization") == expected_auth if auth_ok and form.get("refresh_token") == ["local-refresh-token"]: status, body = 200, {"access_token": "token-from-local-endpoint", "expires_in": 600} else: status, body = 401, {"error": "invalid_client"} print(f"local token endpoint: grant_type={form.get('grant_type', [''])[0]}, HTTP {status}") self.send_response(status) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(json.dumps(body).encode()) def log_message(self, *args): pass def describe(token): parts = token.split(".") if len(parts) == 3: claims = json.loads(base64.urlsafe_b64decode(parts[1] + "=" * (-len(parts[1]) % 4))) return f"Entra ID token for aud={claims['aud']}" return token server = ThreadingHTTPServer(("127.0.0.1", 18765), LocalRefreshTokenEndpoint) threading.Thread(target=server.serve_forever, daemon=True).start() for conn_id in ("snowflake_refresh_token", "snowflake_client_credentials", "snowflake_azure"): with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") try: headers = SnowflakeSqlApiHook(snowflake_conn_id=conn_id).get_headers() token = headers["Authorization"].removeprefix("Bearer ") outcome = f"{headers['X-Snowflake-Authorization-Token-Type']} header with {describe(token)}" except Exception as err: outcome = f"{type(err).__name__}: {err}" deprecations = sum(issubclass(w.category, AirflowProviderDeprecationWarning) for w in caught) print(f"RESULT {conn_id}: {outcome} (deprecation warnings: {deprecations})") server.shutdown() EOF ``` 3. Run the script ```sh uv run --frozen --project providers/snowflake python "$DEMO_DIR/show_headers.py" ``` On the main branch, it shows `KeyError` for both `client_credentials` and `azure_conn_id`. ```text local token endpoint: grant_type=refresh_token, HTTP 200 RESULT snowflake_refresh_token: OAUTH header with token-from-local-endpoint (deprecation warnings: 1) RESULT snowflake_client_credentials: KeyError: 'user' (deprecation warnings: 0) RESULT snowflake_azure: KeyError: 'user' (deprecation warnings: 0) ``` On this branch, all paths can pass. ```text local token endpoint: grant_type=refresh_token, HTTP 200 RESULT snowflake_refresh_token: OAUTH header with token-from-local-endpoint (deprecation warnings: 0) RESULT snowflake_client_credentials: OAUTH header with Entra ID token for aud=https://management.azure.com (deprecation warnings: 0) RESULT snowflake_azure: OAUTH header with Entra ID token for aud=https://management.azure.com (deprecation warnings: 0) ``` <!-- SPDX-License-Identifier: Apache-2.0 https://www.apache.org/licenses/LICENSE-2.0 --> <!-- Thank you for contributing! Please provide above a brief description of the changes made in this pull request. Write a good git commit message following this guide: https://chris.beams.io/posts/git-commit/ Please make sure that your code changes are covered with tests. And in case of new features or big changes remember to adjust the documentation. For user-facing UI changes, please attach before/after screenshots (or a short screen recording) so reviewers can assess the visual impact. Feel free to ping (in general) for the review if you do not see reaction for a few days (72 Hours is the minimum reaction time you can expect from volunteers) - we sometimes miss notifications. In case of an existing issue, reference it using one of the following: * closes: #ISSUE * related: #ISSUE --> --- ##### Was generative AI tooling used to co-author this PR? <!-- If generative AI tooling has been used in the process of authoring this PR, please change below checkbox to `[X]` followed by the name of the tool, uncomment the "Generated-by". --> - [X] Yes - Claude Code <!-- Generated-by: [Tool Name] following [the guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#gen-ai-assisted-contributions) --> --- * Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information. Note: commit author/co-author name and email in commits become permanently public when merged. * For fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed. * When adding dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x). * For significant user-facing changes create newsfragment: `{pr_number}.significant.rst`, in [airflow-core/newsfragments](https://github.com/apache/airflow/tree/main/airflow-core/newsfragments). You can add this file in a follow-up commit after the PR is created so you know the PR number. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
