Repository navigation
[Server] Add gcp_server_identity storage credential for keyless GCS vending - #2379
timothyw553 wants to merge 27 commits into
Conversation
a4e3b6d to
39813a2
Compare
|
/review |
1 similar comment
|
/review |
timothyw553
left a comment
There was a problem hiding this comment.
overall looks good, just a few comments on GCP metadata/ADC error handling and whether sharing the server identity should be gated or documented. also left a couple smaller comments on the CLI flag and generator duplication.
| GoogleCredentials creds; | ||
| try { | ||
| creds = defaultCredentials.load(); | ||
| } catch (IOException e) { |
There was a problem hiding this comment.
both catch blocks here only catch IOException, right? to my understanding malformed ADC can throw IllegalArgumentException or NullPointerException, and a 503 from the universe-domain metadata endpoint throws IllegalStateException, so those leak as INTERNAL or INVALID_ARGUMENT instead of FAILED_PRECONDITION or UNAVAILABLE. should we handle those runtime exceptions at the boundary (and maybe reuse scoped credentials) and add tests for malformed ADC and a 503 metadata response?
There was a problem hiding this comment.
Good catch — updated ADC loading to catch runtime exceptions (FAILED_PRECONDITION) and refresh to catch IllegalStateException (UNAVAILABLE), and added tests for malformed ADC and a 503 universe-domain response.
| || reasons.contains("unauthorized_client")) { | ||
| return new BaseException(ErrorCode.FAILED_PRECONDITION, rejectedCredentialsMessage, e); | ||
| } | ||
| if (checkMetadata404 |
There was a problem hiding this comment.
what happens if the metadata endpoint returns 401 or 403 instead of 404? it looks like those fall through to UNAVAILABLE telling the client to try again, even though retrying won't fix auth or permissions. should we map them to FAILED_PRECONDITION too, and add mocked HTTP tests covering 401, 403, 404, 429, and 503?
+ if (checkMetadata404
+ && (reasons.contains("Error code 401 trying to get security access token")
+ || reasons.contains("Error code 403 trying to get security access token"))) {
+ return new BaseException(
+ ErrorCode.FAILED_PRECONDITION, rejectedCredentialsMessage, e);
+ }There was a problem hiding this comment.
Done — mapped metadata 401/403 to FAILED_PRECONDITION and added mocked HTTP tests for 401, 403, 404, 429, and 503.
| String callerId = IdentityUtils.findPrincipalEmailAddress(); | ||
| CredentialDAO dao = CredentialDAO.from(createCredentialRequest, callerId, secretStore); | ||
| // Validate ADC and resolve the server's service account email before opening a DB transaction. | ||
| Optional<String> gcpServerIdentityEmail = |
There was a problem hiding this comment.
unlike s3_compatible, there's no server config gate here before letting users create a gcp_server_identity credential. to my understanding every credential of this type shares the same server cloud identity, so separate credential names don't isolate IAM boundaries. is this shared trust intentional (and if so, should we document it), or should we require an admin opt-in flag at creation and vending?
There was a problem hiding this comment.
Intentional for now — the server uses one ambient service account, and we can add per-credential impersonation by email later. Documented this shared identity in api/all.yaml and docs/usage/cli.md.
| "The JSON key file of the Google Cloud service account of a gcp_service_account_key" | ||
| + " credential", | ||
| "gcp_service_account_key_file"), | ||
| GCP_SERVER_IDENTITY( |
There was a problem hiding this comment.
if someone runs --gcp_server_identity false, doesn't false get treated as an ignored positional argument so we still enable server identity? should we reject unexpected positional arguments before sending the request, and add tests for the bare flag, space-separated false, and =false?
There was a problem hiding this comment.
Good catch — rejected unexpected positional args in UnityCatalogCli.validateCommand and added tests for --gcp_server_identity, --gcp_server_identity false, and --gcp_server_identity=false.
| e); | ||
| } | ||
| try { | ||
| return downscopeGcpCreds(creds.createScoped(INITIAL_SCOPES), context).refreshAccessToken(); |
There was a problem hiding this comment.
this looks like it repeats the load, scope, downscope, and refresh sequence from ServiceAccountCredentialGenerator (and the try/catch logging block in vendGcpCredential above). why not reuse ServiceAccountCredentialGenerator with its own loader and error mapper so error-handling fixes apply to both paths?
There was a problem hiding this comment.
Done — reused ServiceAccountCredentialGenerator and unified the try/catch warning log in vendGcpCredential.
timothyw553
left a comment
There was a problem hiding this comment.
overall looks good after the updates. left one comment on permanent IAM failures coming back as UNAVAILABLE.
| * (unauthorized/forbidden or no service account / scopes on the instance) as {@code | ||
| * FAILED_PRECONDITION}. | ||
| */ | ||
| static BaseException serverIdentityError(Exception e) { |
There was a problem hiding this comment.
to my understanding IAM impersonation failures can carry HttpResponseException, which doesn't implement Retryable, so isPermanentFailure misses 400 and 403 and returns UNAVAILABLE instead of FAILED_PRECONDITION. should we check HttpResponseException status codes in isPermanentFailure and add mocked tests for 400, 401, 403, 429, and 503?
+import com.google.api.client.http.HttpResponseException;
...
for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
+ if (cause instanceof HttpResponseException response) {
+ int status = response.getStatusCode();
+ return status >= 400 && status < 500
+ && status != 408 && status != 429;
+ }
if (cause instanceof Retryable retryable && !retryable.isRetryable()) {There was a problem hiding this comment.
Good catch — updated isPermanentFailure to treat 4xx HttpResponseException (excluding 408/429) as permanent FAILED_PRECONDITION, and added mocked ImpersonatedCredentials HTTP tests for 400, 401, 403, 429, and 503.
12fed83 to
3689ae4
Compare
timothyw553
left a comment
There was a problem hiding this comment.
overall looks good after the updates. left two comments: one on transient STS JSON errors getting treated as permanent failures, and one on the mixed-case CLI help lookup crashing.
| /** Whether google-auth says that asking again cannot succeed, e.g. an HTTP 403 or 400. */ | ||
| private static boolean isPermanentFailure(Throwable failure) { | ||
| for (Throwable cause = failure; cause != null; cause = cause.getCause()) { | ||
| if (cause instanceof HttpResponseException response) { |
There was a problem hiding this comment.
to my understanding, JSON responses from STS only produce an OAuthException without HttpResponseException in the cause chain, and OAuthException.isRetryable() returns false. wouldn't that turn transient 429, 503, and JSON 500 responses into FAILED_PRECONDITION instead of UNAVAILABLE? should we preserve the STS status or classify 408/429/5xx as temporary before checking Retryable, add tests with real Google client JSON errors, and update the Javadoc?
There was a problem hiding this comment.
Good catch — transient STS OAuth error codes (temporarily_unavailable, server_error, internal_failure) now map to UNAVAILABLE before checking Retryable, with mocked STS JSON error tests and updated Javadoc.
| System.out.println( | ||
| "Unexpected positional arguments: " | ||
| + String.join(" ", Arrays.copyOfRange(subArgs, 2, subArgs.length))); | ||
| CliUtils.printSubCommandHelp(entity, operation); |
There was a problem hiding this comment.
if someone runs Catalog list extra or catalog LIST extra, validation accepts the mixed case, but printSubCommandHelp looks up cliOptions without lowercasing and hits a NullPointerException. should we normalize entity and operation once up front and add regression tests for both mixed-case inputs? also please note in the PR description that all CLI commands now reject extra positional arguments.
+import java.util.Locale;
...
- String entity = cmd.getArgs()[0];
+ String entity = cmd.getArgs()[0].toLowerCase(Locale.ROOT);
...
- String operation = cmd.getArgs()[1];
+ String operation = cmd.getArgs()[1].toLowerCase(Locale.ROOT);There was a problem hiding this comment.
Good catch — normalized entity and operation with Locale.ROOT up front, added mixed-case tests in UnityCatalogCliTest, and noted the CLI positional-argument check in the PR description.
timothyw553
left a comment
There was a problem hiding this comment.
overall looks good after the updates. left one comment on temporary metadata email lookup failures being reported as FAILED_PRECONDITION.
| */ | ||
| private Optional<String> checkAndResolveGcpServerIdentityEmail() { | ||
| try { | ||
| GoogleCredentials credentials = gcpDefaultCredentials.load(); |
There was a problem hiding this comment.
on compute engine, serviceAccountEmail(credentials) can hit the metadata server and google-auth wraps transient failures in RuntimeException, so catching both here turns a brief metadata outage into FAILED_PRECONDITION with missing-ADC instructions. should we separate gcpDefaultCredentials.load() from serviceAccountEmail(credentials) so metadata or network failures return UNAVAILABLE instead, and add a test where ADC loads but the email lookup fails?
There was a problem hiding this comment.
Good catch — split gcpDefaultCredentials.load() from serviceAccountEmail(credentials) so transient metadata/network failures return UNAVAILABLE while permanent 401/403/404 metadata rejections still return FAILED_PRECONDITION, and added a 503 test in CredentialRepositoryTest.
timothyw553
left a comment
There was a problem hiding this comment.
overall looks good after the updates. left one comment on the GKE workload identity email and two smaller ones on the compute engine scope in the docs and the UNAVAILABLE case in the spec.
| static Optional<String> serviceAccountEmail(GoogleCredentials credentials) { | ||
| String email = null; | ||
| if (credentials instanceof ServiceAccountSigner signer) { | ||
| email = signer.getAccount(); |
There was a problem hiding this comment.
to my understanding getAccount() doesn't always return a service account email. on GKE workload identity it can be something like my-proj.svc.id.goog, and we'd publish that as unity_catalog_service_account_email. the docs then tell admins to grant bucket access to it as a service account, which wouldn't work. should we only return it when it's an actual service account email, and add a test for the .svc.id.goog case?
There was a problem hiding this comment.
Good catch — updated serviceAccountEmail to only return values that look like an email address, and added a test for the .svc.id.goog GKE pool ID case.
|
|
||
| When the server's Application Default Credentials identify a service account, the response includes | ||
| `unity_catalog_service_account_email` under `GCP_SERVER_IDENTITY`. Grant that service account | ||
| `roles/storage.objectViewer` on the GCS bucket to read, and `roles/storage.objectAdmin` to read and |
There was a problem hiding this comment.
on compute engine the VM also needs the cloud-platform access scope, right? without it creation succeeds because the email lookup works, but token requests fail later, and bucket roles can't override the VM scope. could we add that here?
+On Compute Engine, the VM must also have the
+`https://www.googleapis.com/auth/cloud-platform` OAuth access scope.There was a problem hiding this comment.
Added the Compute Engine cloud-platform OAuth access scope note to docs/usage/cli.md.
| Application Default Credentials (for example, a GKE Workload Identity or Compute Engine | ||
| service account) without storing a key or requiring `server.credential-encryption-key`. | ||
| All `gcp_server_identity` credentials share the server's single Google Cloud identity, so | ||
| separate credential names do not isolate IAM boundaries. Creating one checks that |
There was a problem hiding this comment.
nit: creation can also return UNAVAILABLE when the metadata email lookup fails temporarily. should we mention it here and in the request schema description, so callers know when to retry? also regenerate the docs.
There was a problem hiding this comment.
Updated api/all.yaml (both createCredential and GcpServerIdentityRequest) to mention UNAVAILABLE and regenerated the API docs.
Storage credentials can now hold a Google Cloud service account key, so that Unity Catalog can vend access to GCS (part of unitycatalog#47; vending follows). - API: `gcp_service_account_key` (`email`, `private_key_id`, `private_key`) on `CreateCredentialRequest`; `CredentialInfo` returns the email and key id only - `private_key` is validated as a PKCS#8 key and stored encrypted with the credential secret store from unitycatalog#2171; `server.credential-encryption-key` is now read whenever it is set, not only with S3-compatible storage enabled - external locations of such a credential must be `gs://` paths, on create and update; a gcp_service_account_key credential cannot be changed to another type - startup warns about a stored `private_key` the server cannot read - schema step V4 adds the credential type on H2, MySQL and PostgreSQL - CLI: `credential create --gcp_service_account_key_file <key.json>` On MySQL the encrypted key does not fit the `credential` column until unitycatalog#2169 widens it; the CRUD test skips MySQL until then. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…tial type, test the GCP scan, keep key file content out of CLI errors, document the PATCH restriction Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…MySQL, schema test leaves later steps pending; say vending is not supported yet Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…re stored as text Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…t the encryption key for GCP, and say vending is not supported yet in the spec Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…ace a failed temp key file delete in the CLI tests, and say in the cache Javadoc that GCP vending is not there yet Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
… version in the cache key, and fix two comments The length tests rejected only values over the limit, so a check that was off by one would still pass. Add an email and key id of exactly 1024 characters, which are accepted, and a private key of exactly 4096 characters, which passes the length check and fails on its format. The cache key held two version fields of which at most one was set. It holds one now, for either an s3_compatible or a gcp_service_account_key credential. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…ec, test a server with only GCP credentials, and cover both key types in the Helm docs The spec did not show the 1024 and 4096 character limits the server enforces, nor that the private key is write-only, so generated clients did not know either. The Helm section on the credential encryption key was titled and written for s3_compatible credentials only, though a gcp_service_account_key credential needs the same Secret and not the S3 flag. Add a test for a server that has the encryption key but leaves S3-compatible storage off, which the credential CRUD tests do not cover since they turn it on. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…mpatible as experimental, and explain why the cache key holds the GCP key's version Google's JSON key file calls the email client_email, so the spec's "the fields of the service account's JSON key file" would send someone who pastes the file to a missing-email error. Say which field goes where, and that the server does not check the key with Google. The gs:// rule of a gcp_service_account_key credential sat inside the EXPERIMENTAL paragraph of s3_compatible on the external location endpoints. Only the s3:// rule is experimental. The cache key Javadoc described the GCP key's id and fingerprint as for later, but they already keep a token cached for the gcs.* settings from satisfying a stored-key request. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
Signed-off-by: Timothy Wang <[email protected]>
A path under an external location whose credential is a gcp_service_account_key now gets a short-lived, downscoped GCS access token instead of UNIMPLEMENTED. - GcpCredentialVendor decrypts the stored private key with the credential secret store and signs in with it; the token is limited to the requested path and to read or read/write, with the downscoping the server settings (gcs.*) already use - the storage credential cache keys an entry by the credential's type and identity (AWS role and external ID; GCP service account and key ID), so a rotated key or another service account never gets a cached token - docs: the roles the service account needs on the bucket Tests use a generator in place of Google, so nothing here calls Google Cloud. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…ential details out of vend errors and log them, cover more Google failures Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…ath on its own, and test that the stored key wins over gcs.* settings without fallback Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…ntials are stored as text Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…ble key and invalid_request, say vending works in the spec Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…act the administrator when Google rejects a stored key, and load keys from a shared utility instead of the vendor Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
A token for gs://bucket/data/t could list with the prefix data/t and see the names under data/t_archive/. Allow a list only under data/t/, as the connector lists, and keep the exact object read of the path itself. This also applies to locations served from the gcs.* settings. Checked on real GCS and with Spark 4.1. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…nd treat refused tokens as permanent The stored-key vending test replaced the generator with an echo, so its claims about the token scope were never checked against the access boundary. Move those checks to GcpCredentialVendorTest, which builds the real boundary: encoded dots and slashes stay literal, and UPDATE gets objectAdmin while SELECT gets objectViewer. A token endpoint answer that google-auth marks as not retryable, such as a 403, is now FAILED_PRECONDITION with the contact-the-administrator message instead of UNAVAILABLE, so callers do not retry a request that cannot succeed. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…overs only the emitted condition, and wrap the cli docs paragraph Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
The stored-key vending tests replace the generator, so nothing ran the code that signs in with the key and downscopes the token. Let the vendor take the transport it reaches Google with, and add tests with a stand-in for Google: the key signs in, the token is downscoped to the requested bucket, path and role before it is returned, and a refused sign-in reaches the caller as the mapped error. Co-authored-by: Isaac <[email protected]> Signed-off-by: Timothy Wang <[email protected]>
…ending Signed-off-by: Timothy Wang <[email protected]>
Signed-off-by: Timothy Wang <[email protected]>
…ilure Signed-off-by: Timothy Wang <[email protected]>
Signed-off-by: Timothy Wang <[email protected]>
…lize CLI command case Signed-off-by: Timothy Wang <[email protected]>
Signed-off-by: Timothy Wang <[email protected]>
e5e14d5 to
c06dc23
Compare
timothyw553
left a comment
There was a problem hiding this comment.
overall looks good after the updates. left two comments: one on malformed STS responses bypassing the error mapper, and one on credential-ID lookups hitting Google metadata.
| return downscopeGcpCreds(creds.createScoped(INITIAL_SCOPES), context).refreshAccessToken(); | ||
| } catch (IOException e) { | ||
| throw credentialError(e); | ||
| } catch (IOException | IllegalStateException e) { |
There was a problem hiding this comment.
to my understanding google's token library can throw NullPointerException or ClassCastException when STS returns an empty 502 or unexpected JSON error body (like an object-valued error on 503 or {"foo":1} on 500), which skips this catch and returns INTERNAL instead of UNAVAILABLE. could we catch those around refreshAccessToken() and add mocked regression tests for those responses?
- return downscopeGcpCreds(creds.createScoped(INITIAL_SCOPES), context).refreshAccessToken();
+ OAuth2Credentials scoped =
+ downscopeGcpCreds(creds.createScoped(INITIAL_SCOPES), context);
+ try {
+ return scoped.refreshAccessToken();
+ } catch (NullPointerException | ClassCastException e) {
+ throw new BaseException(
+ ErrorCode.UNAVAILABLE,
+ "Google returned an invalid token-service response. Try again.",
+ e);
+ }There was a problem hiding this comment.
Good catch — caught NullPointerException | ClassCastException around scoped.refreshAccessToken() as UNAVAILABLE and added mocked tests for empty 502, {"foo":1} on 500, and object-valued error on 503.
| }, | ||
| "Failed to get storage credential", | ||
| /* readOnly= */ true); | ||
| populateGcpServerIdentityEmail(List.of(info)); |
There was a problem hiding this comment.
KeyMapper and PermissionService both call getCredential(name).getId() just to resolve the credential ID, so auth checks on a gcp_server_identity credential will hit Google metadata (and retry + log warnings if metadata lookup is failing). should we give ID-only callers a DB-only lookup so populateGcpServerIdentityEmail only runs on response paths, plus a test checking that ID resolution doesn't call the ADC loader?
There was a problem hiding this comment.
Good catch — added a DB-only getCredentialId(name) for KeyMapper and PermissionService so auth checks never touch ADC/metadata, plus a test verifying zero ADC calls.
…e malformed STS responses Signed-off-by: Timothy Wang <[email protected]>
🥞 Stacked PR
Use this link to review incremental changes.
PR Checklist
docsis updatedDescription of changes
This PR adds a keyless
gcp_server_identitystorage credential type on top of #2273 for Unity Catalog servers running on Google Cloud (such as GCE, GKE with Workload Identity, or Cloud Run), allowing UC to vend downscoped GCS tokens from the server's own Google Application Default Credentials (ADC).Now users can run:
The response returns the server's
unity_catalog_service_account_emailso admins can grant it bucket IAM roles, bindgs://external locations to the credential, and read/write tables without exporting static service account JSON keys or configuringserver.credential-encryption-key.This is done by adding
gcp_server_identityacross the API, CLI, and database schema, verifying ADC on credential creation, and vending downscoped GCS tokens directly from ADC instead of a stored key (and rejecting unexpected positional arguments in the CLI so--gcp_server_identity falsecannot silently enable it).Testing
Unit, integration, CLI, and H2/Postgres/MySQL migration tests pass, and end-to-end vending + Spark 4.0.1 / Delta 4.4.1 CRUD was verified on a GCE VM against real GCS with no static key file or
gcs.*config.