Skip to content

Commit d61b6d3

Browse files
fix(bigquery-jdbc): use loopback binding, PKCE, and state verification in user account OAuth flow (#15241)
b/584840384 ### Summary Aligns interactive user-account authentication (`OAuthType=1`) in `BigQueryJdbcOAuthUtility` with RFC 8252 and RFC 7636, extracts the local loopback HTTP callback listener into `BigQueryJdbcOAuthCallbackServer`, and ensures `RequestGoogleDriveScope` and explicit `universeDomain` settings apply to user-account credentials. ### What Changed & Why - **Desktop pre-check & deterministic socket cleanup:** `getGoogleUserAccountCredentials` checks `isDesktopBrowseSupported()` (`GraphicsEnvironment.isHeadless()`, `Desktop.isDesktopSupported()`, and `Desktop.Action.BROWSE`) before opening a local socket, and wraps `BigQueryJdbcOAuthCallbackServer` and accepted `Socket` instances in `try-with-resources` so the listener closes prior to token exchange and on any error or timeout. - **RFC 8252 loopback redirect URI (`BigQueryJdbcOAuthCallbackServer`):** `openLoopbackServerSocket()` binds `127.0.0.1` (falling back to `::1` on IPv6-only hosts, `backlog = 8`) using `java.net.ServerSocket` (`java.base`, avoiding a `jdk.httpserver` module dependency in custom `jlink` / OSGi runtimes) and `buildLoopbackCallbackUri()` formats `http://127.0.0.1:<port>` or `http://[::1]:<port>` for `getUserAuthorizer`. Matching the bound IP family avoids `Connection Refused` errors when the browser and JVM resolve `localhost` to different address families. (The 9-argument `getGoogleUserAccountCredentials` and 1-argument `openLoopbackServerSocket` package-private overloads are deterministic test seams to which the production entry points delegate.) - **RFC 7636 `S256` PKCE, OAuth `state`, & `RequestGoogleDriveScope`:** Configured `UserAuthorizer` with `Rfc7636PkceProvider` (used instead of `DefaultPKCEProvider`, which in `google-auth-library-oauth2-http` `1.58.0` emits a 172-character `=`-padded `code_verifier` outside RFC 7636 Section 4.1's 43–128 unreserved-character range), added `state` generation and callback verification, and wired `RequestGoogleDriveScope` (`BIGQUERY_WITH_DRIVE_SCOPES` vs. `DEFAULT_BIGQUERY_SCOPES`) at authorization consent time. - **Explicit `universeDomain` propagation:** `getCredentialsFromCode` propagates `UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME` from `overrideProperties` onto `UserCredentials.Builder`, matching non-JSON credential handling for custom universe domains. - **Reliable HTTP/1.1 callback parsing & responses:** - Enforces a `1000 ms` per-socket read timeout within the `120 s` callback window, skipping empty browser TCP preconnects, returning `404 Not Found` for secondary requests such as `/favicon.ico`, and continuing to listen after malformed or unverified HTTP requests (responding `400 Bad Request` and recording the last rejected request reason in case the callback window times out). - Parses the callback request target via `URI`, UTF-8 URL-decodes query parameters while preserving literal `+` characters per RFC 3986 (`code`, `state`, `error`), and immediately aborts when a `state`-verified callback reports an OAuth `error=` or omits `code`. - Drains up to `64 KiB` of request headers (accommodating `127.0.0.1` cookies) and calls `socket.shutdownOutput()` after flushing `\r\n`-formatted HTTP/1.1 responses (`200 OK`, `400 Bad Request`, `404 Not Found`) with `Cache-Control: no-store`, `X-Content-Type-Options: nosniff`, `Content-Security-Policy: default-src 'none'`, `Connection: close`, and exact UTF-8 byte `Content-Length`. - **Documentation (`docs/USER_GUIDE.md`):** Documented that custom `OAuthClientId` values used with `OAuthType=1` must be configured as a **Desktop app** OAuth 2.0 client. ### Compatibility Notes - Existing `OAuthType=1` flows already used ephemeral ports (`ServerSocket(0)`), which require a Google **Desktop app** OAuth 2.0 client (default or custom `OAuthClientId`). Google Desktop OAuth clients natively support `http://127.0.0.1:<port>` and `http://[::1]:<port>` redirect URIs and `S256` PKCE without Cloud Console changes. ### Testing - `BigQueryJdbcOAuthUtilityTest` covers `S256` PKCE challenge/verifier exchange, `RequestGoogleDriveScope` consent scope selection, default vs. explicit `universeDomain` propagation (including ignoring `GOOGLE_CLOUD_UNIVERSE_DOMAIN` for non-JSON credentials), IPv4/IPv6 loopback binding without mocking JDK networking classes, RFC 3986 `+` and `%2B` query decoding and malformed `%` handling, `state` and `error=` callback validation, `> 16 KiB` and `> 64 KiB` header draining, resilience to browser TCP preconnects / `/favicon.ico` / unverified local HTTP probes, timeout diagnostics and socket cleanup paths, and non-desktop environment fast-fail. - Live interactive browser consent was not run in automated CI as `OAuthType=1` requires desktop user interaction.
1 parent 1c0a358 commit d61b6d3

4 files changed

Lines changed: 1650 additions & 91 deletions

File tree

‎java-bigquery-jdbc/docs/USER_GUIDE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ The driver supports multiple OAuth 2.0 and identity workflows specified via the
109109
| **`0`** | **Service Account Key File (P12)** | `OAuthPvtKeyPath`, `OAuthServiceAcctEmail` | `OAuthP12Password` | Path to `.p12` key file. Requires explicit `OAuthServiceAcctEmail` as `.p12` files do not contain email metadata. `OAuthP12Password` defaults to `notasecret`. |
110110
| **`0`** | **Service Account Key String (JSON)** | `OAuthPvtKey` | `OAuthServiceAcctEmail` | Raw JSON key file string content in URL. Service account email and private key are automatically extracted from the JSON string. |
111111
| **`0`** | **Service Account Key String (PKCS#8 / P12 Bytes)** | `OAuthPvtKey`, `OAuthServiceAcctEmail` | `OAuthP12Password` | Raw PKCS#8 or P12 bytes key string content in URL. Requires explicit `OAuthServiceAcctEmail`. |
112-
| **`1`** | **User Account (Interactive 3-Legged OAuth)** | None (for built-in client app) | `OAuthClientId`, `OAuthClientSecret` | Launches local browser tab for interactive user login on desktop. Built-in client ID/secret used if omitted. |
112+
| **`1`** | **User Account (Interactive 3-Legged OAuth)** | None (for built-in client app) | `OAuthClientId`, `OAuthClientSecret` | Launches local browser tab for interactive user login on desktop. Built-in client ID/secret used if omitted. Custom `OAuthClientId` values must be configured as a **Desktop app** OAuth 2.0 client. |
113113
| **`2`** | **Pre-generated Access Token** | `OAuthAccessToken` | `OAuthAccessTokenReadonly` | Uses short-lived bearer token directly. `OAuthAccessTokenReadonly` defaults to `false`. |
114114
| **`2`** | **Pre-generated Refresh Token** | `OAuthRefreshToken`, `OAuthClientId`, `OAuthClientSecret` | None | Uses refresh token with client credentials to automatically mint access tokens. |
115115
| **`3`** | **Application Default Credentials (ADC)** | None | None | Uses GCP standard credential resolution (`GOOGLE_APPLICATION_CREDENTIALS` env var or `gcloud` CLI context). |
@@ -160,7 +160,7 @@ String url = "jdbc:bigquery://https://bigquery.googleapis.com:443"
160160
| `OAuthAccessToken` | `null` | Pre-generated OAuth 2.0 access token string. |
161161
| `OAuthAccessTokenReadonly` | `false` | Indicates whether the pre-generated access token has read-only scope. |
162162
| `OAuthRefreshToken` | `null` | Pre-generated refresh token to automatically mint access tokens. |
163-
| `OAuthClientId` | *Google Client ID* | OAuth 2.0 Client ID for user authentication or refresh token flows. |
163+
| `OAuthClientId` | *Google Client ID* | OAuth 2.0 Client ID for user authentication or refresh token flows. For `OAuthType=1`, custom client IDs must be configured as a **Desktop app** OAuth 2.0 client so dynamic loopback redirect URIs (`http://127.0.0.1:<port>` or `http://[::1]:<port>`) are accepted. |
164164
| `OAuthClientSecret` | *Google Secret* | OAuth 2.0 Client Secret for user authentication or refresh token flows. |
165165
| `ServiceAccountImpersonationEmail` | `null` | Target Service Account email to impersonate for query job execution. |
166166
| `ServiceAccountImpersonationChain` | `null` | Comma-separated list of service account emails representing the impersonation chain. |

0 commit comments

Comments
 (0)