Skip to content

[Server] Vend GCS credentials from storage credentials - #2273

Open
timothyw553 wants to merge 20 commits into
unitycatalog:mainfrom
timothyw553:stack/gcp-credential-vending
Open

timothyw553 wants to merge 20 commits into
unitycatalog:mainfrom
timothyw553:stack/gcp-credential-vending

Conversation

@timothyw553

@timothyw553 timothyw553 commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

🥞 Stacked PR

Use this link to review incremental changes.


PR Checklist

  • A description of the changes is added to the description of this PR.
  • If there is a related issue, make sure it is linked to this PR.
  • If you've fixed a bug or added code that should be tested, add tests!
  • If you've added or modified a feature, documentation in docs is updated

Description of changes

Depends on #2260, which lets an admin store a Google service account key as a storage credential. This PR uses that key: a client can now ask for access to a path under a gs:// external location and get a Google token for it. Before, such a request failed with UNIMPLEMENTED.

How a request works now

A client asks for access to gs://my-bucket/data/table1. UC finds the external location that covers the path, takes its credential, decrypts the stored private key, and uses it to get a short-lived Google token. The token can only read (or read and write, if the client asked for that) objects under data/table1. UC returns the token and never the key.

The code that restricts a token to a path already exists. It's what the gcs.* server settings use today. This PR takes the key from the stored credential instead of a key file. It also tightens the list condition so a token cannot list sibling paths such as path_archive/; that applies to the gcs.* settings too.

Changes

  • GcpCredentialVendor reads the key from the storage credential when there is one, and from the gcs.* settings otherwise, as before
  • The storage credential cache (off by default) now keys a gcp_service_account_key credential by its id and a fingerprint of its stored key, the same as s3_compatible credentials. Without this, a request using a saved GCS credential could be served a token cached from the server's gcs.* settings, or after a key is replaced, one made with the old key
  • Errors: Google rejecting the server's sign-in timestamps (clock skew, which also comes back as invalid_grant) is INTERNAL, not a request to replace the key. A failure reading the stored key returns a message that names nothing of the credential, and the details are logged for the administrator
  • The condition on a token no longer lets it list with the bare path as the prefix: a token for data/t could list data/t_archive/ names (not read them). It now lists only under data/t/, as the GCS connector does, and still reads the path itself. This also applies to locations served from the gcs.* server settings, so it is a behavior change for them too
  • docs/usage/cli.md says which role the service account needs on the bucket: roles/storage.objectViewer to read, roles/storage.objectAdmin to write

Testing

Against a real GCS bucket, with a service account that could access the whole bucket:

  • a read token read a file under the location, and was refused for a file outside it
  • a read and write token wrote a file under the location, and was refused a write outside it
  • a read-only token was refused a write inside the location
  • with the credential cache on, two requests for the same path returned the same token
  • On real GCS: a token for data/sib_t is refused (403) when listing the bare prefix data/sib_t, lists data/sib_t/, and still cannot read data/sib_t_archive/. With the same server, Spark 4.1.0 and connector 4.0.10 pass Delta DML, optimize, vacuum, checkpoint, time travel, restore, partitioned tables, parquet partitioned overwrite and overwrite-to-empty, a DataFrame append, path SQL read and write, and streaming Delta to Delta. Spark 4.0, 4.2 and 4.3 were not rerun for this change

In the repo's tests, using a stand-in for Google's token service:

  • a path under the location is vended from the stored key, and the vendor receives the key as it was created
  • 16 paths that look like they are inside the location or try to leave it (data2, data/../other, other buckets, user-info and port tricks and so on): 15 are refused, and data/%2e%2e/other is accepted but the token only covers that literal name, which GCS doesn't resolve to other/
  • the cache keeps a different credential, or a replaced key, separate
  • the failures Google can give for a stored key (invalid_grant, invalid_client, unauthorized_client, clock skew, 5xx, unreachable) map to the right error code, and a credential of another type on a gs:// location is not named in the error

Full server/test and cli/test on H2.

Not covered

  • Azure is not part of this stack.

@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from 4863f59 to 8e61269 Compare November 17, 2026 17:18
@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from 8e61269 to ad3801d Compare November 17, 2026 20:31
yili-db pushed a commit that referenced this pull request Nov 19, 2026
…icit dir repair off for vended tokens (#2281)

## 🥞 Stacked PR
Use this
[link](https://github.com/unitycatalog/unitycatalog/pull/2281/files) to
review incremental changes.
-
[stack/gcs-hadoop-conflict-check](#2281)
[[Files
changed](https://github.com/unitycatalog/unitycatalog/pull/2281/files)]

---------
**PR Checklist**

- [x] A description of the changes is added to the description of this
PR.
- [x] If there is a related issue, make sure it is linked to this PR.
- [x] If you've fixed a bug or added code that should be tested, add
tests!
- [x] If you've added or modified a feature, documentation in `docs` is
updated

**Description of changes**

Fixes [#2278](#2278):
reading or writing a table on `gs://` through Unity Catalog failed on
Spark 4.2 and 4.3 with `403` errors from Google.

**Why it failed.** The token Unity Catalog vends only covers the table's
own folder. Google's GCS connector has three settings that make it touch
things outside that folder:
- `fs.gs.create.items.conflict.check.enable` reads every folder above a
new file or folder, so creating a table or writing to it fails. Unity
Catalog already tried to turn it off, but Hadoop 3.5 started shipping it
as "on" in its own defaults, and our code took that default for the
user's choice.
- `fs.gs.hierarchical.namespace.folders.enable` reads the bucket's
layout when a folder is deleted or renamed. The connector turns it on
itself, on every Spark version. Parquet tables fail because their commit
deletes folders; Delta tables do not.
- `fs.gs.implicit.dir.repair.enable` looks up the parent folder after a
folder is deleted, for example by `INSERT OVERWRITE` on a parquet table.
The connector turns it on itself, on every Spark version.

**The fix**
- All three are now off on every Spark version, unless the user turns
one on themselves (for example with broader credentials, or on a
hierarchical-namespace bucket).
- The Spark docs now use Google's connector 4.0.10 on every Spark
version. Hadoop 3.5's own GCS module can't take a vended token, and the
old 3.0.2 jar doesn't work on Spark 4.2. With 4.0.10, Spark 4.1 also no
longer needs the workaround in
[#2277](#2277).
- The docs also show the settings for releases before 0.8.0, which don't
have this fix. The Spark 4.0.x and 4.1.x commands set the hierarchical
namespace and implicit directory repair settings; the 4.2.x command also
sets the conflict check, because only Hadoop 3.5 turns it on.
- With the hierarchical namespace setting off, folder delete and rename
on hierarchical-namespace buckets lose the connector's native folder
path until users set it back to `true`.
- `engineSets` moved from the S3 builder into `CredPropsBuilder` (moved
with a generalized comment; S3 behavior is unchanged). The GCS-only
`setOffUnlessEngineSets` stays in `GcsCredPropsBuilder`.
- The docs also add a short note on Structured Streaming: a checkpoint
location gets no Unity Catalog credentials, so the session needs its own
access limited to that location.

**Testing**
- New unit tests; the existing ones still pass. The unit tests in this
repo still use connector 3.0.2 on purpose; the real-GCS runs below use
4.0.10.
- On a real GCS bucket, with Spark 4.0, 4.1, 4.2 and 4.3 and connector
4.0.10, using a Unity Catalog server that vends GCS credentials
([#2260](#2260),
[#2273](#2273)): Delta
and parquet tables, managed tables, and path reads and writes in Spark
SQL all work. A Spark session also kept working past the one-hour token
expiry.
- On Spark 4.0 and 4.1, turning any of them on by hand makes tests fail:
the bucket-layout one breaks non-Delta table writes, the folder one
breaks everything, the folder-repair one breaks `INSERT OVERWRITE` on
parquet tables.

**Not covered.** Reading a bare `gs://` path with the DataFrame API
(`spark.read.parquet("gs://...")`) doesn't use Unity Catalog credentials
on any version. This PR doesn't change that.

---------

Signed-off-by: Timothy Wang <[email protected]>
Co-authored-by: Isaac <[email protected]>

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mostly looks good, left a few comments on error handling (clock drift and leaking stored credential metadata) and having the tests go through the real vendor flow instead of bypassing it. also a couple nits on test retries, the pkcs#1 test, and docs.

* startup, so entries never span two modes.
* s3_compatible} or {@code gcp_service_account_key} credential is identified by the fingerprint
* of its stored payload instead, which every change of its key pair, endpoint, role or service
* account key changes. Server and client vends of such a credential can differ: without {@code

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: "such a credential" here now reads as applying server/client differences to gcp_service_account_key too, when GCP server and client vends share the same behavior, and the cache key also includes the credential ID alongside the fingerprint. could we tighten this javadoc (and update the PR description, which says email + key ID and mentions AWS role/external ID separation as new here)?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tightened the Javadoc and updated the description.

Comment thread docs/usage/cli.md Resolved
@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from ad3801d to b9f1162 Compare November 19, 2026 09:48

@timothyw553 timothyw553 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mostly looks good. left a few comments on error handling for Google token responses and test coverage on path boundaries and credential precedence.

@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch 2 times, most recently from b27d80b to 10a69b8 Compare November 20, 2026 02:21
@timothyw553
timothyw553 marked this pull request as ready for review November 20, 2026 08:45
@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from 10a69b8 to fce01ea Compare November 20, 2026 09:20
@yili-db

yili-db commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

/review

1 similar comment
@timothyw553

Copy link
Copy Markdown
Collaborator Author

/review

@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from fce01ea to a42906f Compare November 20, 2026 23:53
@timothyw553

Copy link
Copy Markdown
Collaborator Author

On the blank encryption key blocker: a blank value cannot reach parseKey in either real path. ServerProperties.readPropertiesFromFile removes every blank value when it loads server.properties (the comment there says those lines are only for demonstration), and getEnv treats an empty UC_SERVER_CREDENTIAL_ENCRYPTION_KEY as unset. So I did not add a blank filter. The docs that still said only s3_compatible credentials need the key (docs/server/configuration.md, helm/values.yaml, helm/README.md) were wrong, and are fixed in #2260. Also in this update: the cache key now lives in #2260 (with a regression test), the storedKeyError Javadoc lists all four outcomes, and there are new tests for an undecryptable stored key and for invalid_request.

@yili-db yili-db left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[AI Assisted] Review of a42906f7: comment. Inline items are the caller-facing message, a Javadoc wording nit, and a bucket-root doc note. The sibling-matching list clause is in code this PR does not change, so it is raised here. Please merge #2260 first, since this PR stacks on it.

Sibling-matching list clause (GcpCredentialVendor.java, line 259, not in this PR's diff): This clause also allows a list whose prefix is exactly path, which returns names under sibling paths such as path_archive/. The GCS connector lists directories with a trailing slash and checks parent paths with object reads, so startsWith(path/) on the list prefix covers the engine calls. Could we drop the equality from this clause?

Note only: vending does one STS exchange per token, as the existing gcs.* path does. That is fine for now. If vend latency becomes a concern, a client-side credential access boundary factory is the follow-up.

Comment thread docs/usage/cli.md Resolved
@shba24
shba24 self-requested a review November 21, 2026 01:04
key.getPrivateKey() != null && !key.getPrivateKey().isBlank(),
"gcp_service_account_key.private_key is required.");
try {
GcpCredentialVendor.credentialsOf(key);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Persist layer calls into the service-layer GcpCredentialVendor

CredentialDAO.validateGcpServiceAccountKey calls GcpCredentialVendor.credentialsOf, so persist now depends at runtime on service.credential.gcp. credentialsOf was also made public only for this call. Nothing fails because of it, but it points the dependency from persist up to service.

For example: A later change to GcpCredentialVendor, such as constructor or config changes, would also change what CredentialDAO needs to load.

Move the key parsing into a small utility below both layers, used by the DAO and the vendor, and keep credentialsOf out of the vendor's public surface. This changes no behavior.

Would a shared key-parsing helper that both layers use work for you?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved key loading into utils.GcpServiceAccountKeys, so the DAO no longer depends on the vendor.

Comment thread docs/usage/cli.md Resolved
@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from a42906f to 89be778 Compare November 22, 2026 00:46
@timothyw553

Copy link
Copy Markdown
Collaborator Author

On the sibling-matching list clause: left for now. The existing comment says listing with the bare path as the prefix is deliberate, for parity with the S3 policy, so I want to check on real GCS that the connector does not need it before dropping it.

@timothyw553

Copy link
Copy Markdown
Collaborator Author

On the sibling-matching list clause: dropped in ddf62a4. On real GCS, a token for data/sib_t could list the bare prefix data/sib_t and see data/sib_t_archive/b.txt (names only; reading it was already refused). With the change the bare prefix is a 403, data/sib_t/ still lists, and the exact read of the path itself is kept. The connector does not need the bare-prefix list: with this server, Spark 4.1.0 and connector 4.0.10 on real GCS pass Delta DML, optimize, vacuum, checkpoint, time travel, restore, partitioned tables, parquet partitioned overwrite and overwrite-to-empty, a DataFrame append, path SQL read and write, and streaming Delta to Delta. I did not rerun Spark 4.0, 4.2 or 4.3. This helper also serves the gcs.* settings, so the tighter list applies there too, which the description now says.

String roleArn,
String externalId,
Optional<CredentialVersion> s3CompatibleVersion,
Optional<CredentialVersion> gcpKeyVersion,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Cache Key holds two mutually exclusive Optional version fields

Key carries s3CompatibleVersion and gcpKeyVersion, and Key.of fills each by filtering on a different CredentialType, so at most one is ever set. The type would say this more directly with a single optional version. Key is private and nothing is wrong today. The S3-specific server-access flag has to stay separate if the fields are merged.

For example: A GCP key credential produces Key(s3CompatibleVersion=empty, gcpKeyVersion=Optional.of(v)). The shape allows both to be set, which no caller does.

Merge the two version fields into one Optional filled for either credential type, and keep the S3 server-access flag as its own field.

Would a single version field read better here?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left as is: Key is private and nothing behaves differently. Happy to merge the two version fields in a separate change.

@yili-db

yili-db commented Nov 22, 2026

Copy link
Copy Markdown
Collaborator

/review

@timothyw553

timothyw553 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Real-GCS Spark runs with the current code, each 10 of 10 scenarios passing (Delta DML, optimize, vacuum, checkpoint, time travel, restore, partitioned tables, parquet partitioned overwrite and overwrite-to-empty, DataFrame append, path SQL read and write, streaming Delta to Delta):

Spark Delta
4.0.1 4.4.1
4.1.0 4.4.1 and 4.5.0-SNAPSHOT
4.2.0 4.4.1 and 4.5.0-SNAPSHOT
4.3.0 4.5.0-SNAPSHOT

The connector was built for each Spark line and 4.0 ran on the 4.0.1 distribution. There is no 4.0 Delta snapshot, so 4.0 ran on 4.4.1 only. On real GCS a token for data/sib_t gets a 403 listing the bare prefix and can still list data/sib_t/; a bucket-root location is refused by the server.

Iceberg 1.11.0 through the UC Iceberg REST catalog, on Spark 4.0 and 4.1: create, insert, update, delete, merge, DataFrame append, partitioned table, time travel, rewrite_data_files, expire_snapshots, remove_orphan_files (prefix listing, dry run) and DROP TABLE PURGE all pass on real GCS (9 of 9 on each).

@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from 5918937 to 65760c1 Compare November 23, 2026 21:15
@timothyw553

Copy link
Copy Markdown
Collaborator Author

/review

+ " it may have been disabled, deleted or revoked. Contact the server administrator.",
e);
}
if (isPermanentFailure(e)) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A transient Google STS outage is reported as FAILED_PRECONDITION 'Contact the server administrator'

isPermanentFailure treats any Retryable cause whose isRetryable() is false as permanent. The downscoping exchange raises OAuthException from StsRequestHandler, and its constructor always sets isRetryable=false, so an STS 5xx lands in the permanent branch. The Javadoc and spec say a failure where a retry may succeed should be UNAVAILABLE ('Try again'). The same blind spot appears in two neighbouring places: the oauth2 sign-in factory marks only {500, 503, 408, 429} as retryable, so a 502 or 504 from oauth2.googleapis.com is also mapped to FAILED_PRECONDITION (read in the google-auth 1.52.0 bytecode, not tested). The gcs.* mapper credentialError (line 315) sends everything except invalid_request to FAILED_PRECONDITION 'GCS credentials not found.', but that code is unchanged from the base and is out of scope for this PR.

For example: A caller vends through a stored key while oauth2.googleapis.com returns 200 and sts.googleapis.com/v1/token returns 503 {"error":"backend_error"}. A temporary row through vendorThroughTheRealGenerator(new FakeGoogle(503, ...)) returned code=FAILED_PRECONDITION with 'Contact the server administrator', and an assertion expecting UNAVAILABLE failed. The caller is told to call an administrator for an outage that a retry would clear. The same happens for STS 500, 429 and 408.

Trust isRetryable() only for the token endpoint's GoogleAuthException, which classifies the HTTP status. Do not trust it on OAuthException from the STS exchange, because that type always reports false and drops the original status. Alternatively, map an OAuthException whose error code is not invalid_grant, invalid_client or unauthorized_client to UNAVAILABLE. Then add a GcpCredentialVendorTest row for an STS 503 expecting UNAVAILABLE, so the existing 400/403 rows still pin FAILED_PRECONDITION. Consider also adding 502 and 504 rows for the sign-in endpoint.

Evidence
isaac-1: GcpCredentialVendor.java:361-367: `if (isPermanentFailure(e)) { return new BaseException(ErrorCode.FAILED_PRECONDITION, "Google refused to issue an access token for the storage credential of this location." + " Contact the server administrator.", e); }` and :375-380: `if (cause instanceof Retryable retryable && !retryable.isRetryable()) { return true; }`. The Javadoc at :329-331 says `any other failure, such as a network error, is {@code UNAVAILABLE}, since a retry may succeed.` Library side (javap, google-auth-library-oauth2-http 1.52.0, the version pinned in build.sbt:458): StsRequestHandler.exchangeToken catches HttpResponseException and calls `OAuthException.createFromHttpResponseException`. That builds `new OAuthException(error, error_description, error_uri)`, whose constructor calls `GoogleAuthException."<init>":()V`, and that constructor stores `iconst_0` into `isRetryable`, so the flag is false for every status. DownscopedCredentials.refreshAccessToken wraps only the source-refresh step (its exception table covers offsets 0-7), so the STS OAuthException reaches storedKeyError directly. Local run of a temporary test: `PROBE code=FAILED_PRECONDITION msg=Google refused to issue an access token for the storage credential of this location. Contact the server administrator. urls=[https://oauth2.googleapis.com/token, https://sts.googleapis.com/v1/token]`. Guards checked: the invalid_request check (:338) and the reason-string checks (:345-360) do not match `backend_error`, so control reaches isPermanentFailure.

role_maintainer_claude-1: GcpCredentialVendor.java:361-367: `if (isPermanentFailure(e)) { return new BaseException(ErrorCode.FAILED_PRECONDITION, "Google refused to issue an access token for the storage credential of this location." + " Contact the server administrator.", e); }` and :375-380: `if (cause instanceof Retryable retryable && !retryable.isRetryable()) { return true; }`. On the library side, javap of google-auth 1.52.0 `StsRequestHandler.exchangeToken` shows the exception handler at offset 120: `invokestatic OAuthException.createFromHttpResponseException(HttpResponseException)` then `athrow`, with no check on the status. `OAuthException(String,String,String)` calls `GoogleAuthException."<init>":()V`, and that constructor stores `iconst_0` into `isRetryable`. So every STS HTTP error with a JSON `error` field, including 503, is non-retryable and lands in the FAILED_PRECONDITION branch. In GcpCredentialVendorTest.java:259, `Arguments.of(503, "{\"error\": \"backend_error\"}", ErrorCode.UNAVAILABLE)` runs through `refreshStoredKeyAgainst`, which sets the mock transport only on the source ServiceAccountCredentials (:511). The STS step is never stubbed with a 5xx there. FakeGoogle (:437-443) can return an STS status, but it is used only with 400 bodies (:463, :488).
How it was checked

Disprovers agreed (CONFIRMED): codex, opus

How about limiting the isRetryable() check to the token endpoint's exception type and mapping STS failures by their error code?

.contains("source-token")
.contains("projects/_/buckets/test-bucket")
.contains("roles/storage.objectViewer")
.contains("objects/t");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): The real-generator test would pass for a boundary built for a sibling path, bucket or extra role

testStoredKeyIsDownscopedToTheRequestedPath checks the STS exchange with contains() on the bucket, the role and objects/t. Those substrings also match a boundary for t-sibling, and they ignore added roles. The exact-boundary tests call ruleFor directly, so nothing checks that the generator forwards the requested context.

For example: If ServiceAccountCredentialGenerator.generate were changed to downscope for gs://test-bucket/t-sibling, or to add roles/storage.objectAdmin next to objectViewer, the exchange would still contain every asserted substring and the test would stay green.

Parse the URL-decoded options JSON of the STS exchange and compare its accessBoundary with the rule that ruleFor("gs://test-bucket/t") builds, covering resource, permissions and the full availability condition, instead of using contains("objects/t").

Evidence
GcpCredentialVendorTest.java:315-318 requests `gs://test-bucket/t`; lines 477-482 assert only `.contains("projects/_/buckets/test-bucket")`, `.contains("roles/storage.objectViewer")`, and `.contains("objects/t")`. A boundary for `objects/t-sibling` would also satisfy these substring assertions. Other boundary tests call downscopeGcpCreds directly.
How it was checked

Disprovers agreed (CONFIRMED): codex, opus

Would you be open to comparing the whole decoded boundary against ruleFor's output?


/** A stored key that cannot be decrypted names nothing of the credential to whoever asks. */
@Test
public void testUndecryptableStoredKeyIsNotNamedInTheError() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): No test reaches the 'stored service account key cannot be loaded' error branches

createKeyGenerator turns an IOException from GcpServiceAccountKeys.credentialsOf into INTERNAL 'The stored service account key cannot be loaded.', and getGcpPrivateKey throws INTERNAL "Storage credential '%s' has no stored private_key." when the JSON has no textual private_key. Every fixture builds the stored key through CredentialDAO.from, whose validation rules those states out, so neither branch runs. The S3 sibling (getS3SecretAccessKey) is covered at CredentialDAOTest.java:216, but the GCP copy is not.

For example: Change the catch to another ErrorCode, or let the IOException escape, and every test still passes. A stored credential whose private_key decrypts to a PEM with a header and AAAA body would reach the first branch. A GCP_SERVICE_ACCOUNT_KEY DAO whose JSON is {"email":"[email protected]","private_key_id":"k"} would reach the second.

In GcpCredentialVendorTest, vend through vendorThroughTheRealGenerator with a secret store that decrypts to an unparseable PEM, and assert INTERNAL with a message that does not name the credential. Overwriting the ciphertext does not work, because it fails earlier in decryption. In CredentialDAOTest, add a GCP counterpart of the S3 missing-field test for getGcpPrivateKey.

Evidence
GcpCredentialVendor.createKeyGenerator: `catch (IOException e) { throw new BaseException(ErrorCode.INTERNAL, "The stored service account key cannot be loaded.", e); }`. I searched `GcpCredentialVendorTest` and `StoredGcpKeyVendingTest` for 'cannot be loaded' and for a stored key that fails `GcpServiceAccountKeys.credentialsOf` at vend time. Neither exists. `testUndecryptableStoredKeyIsNotNamedInTheError` fails earlier, in `storedKey`, so a change of this code to any other one, or deleting the catch, would pass.
How it was checked

Disprovers agreed (CONFIRMED): codex

Could we add one row for each of these two branches so the INTERNAL mapping is pinned?

.isInstanceOfSatisfying(
ApiException.class,
e -> {
assertThat(e.getResponseBody()).contains("Contact the server administrator");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Credential-error tests check the message but not the ErrorCode or HTTP status

testCredentialOfAnotherTypeIsNotNamedInTheError and testUndecryptableStoredKeyIsNotNamedInTheError (GcpCredentialVendorTest.java:398) assert the wording and that the credential name is absent, but not the code storedKey carries through. The DAO check at CredentialDAOTest.java:102 accepts any BaseException for a different encryption key. The repository's testing conventions ask for the correct error code and message on failure paths.

For example: Change storedKey to throw new BaseException(ErrorCode.INTERNAL, sameMessage, e). The vend of gs://uc-test-bucket/aws/table then returns 500 instead of FAILED_PRECONDITION, and the test stays green because the message is unchanged.

Assert the HTTP status (or the error code in the body) in StoredGcpKeyVendingTest, error.getErrorCode() in the GcpCredentialVendorTest undecryptable-key test, and the specific ErrorCode in the CredentialDAOTest check. The outside-the-location case needs no change, since testPathsOutsideTheLocationAreRefused already asserts 400 for it.

Evidence
StoredGcpKeyVendingTest.java:176-177: `assertThat(e.getResponseBody()).contains("Contact the server administrator"); assertThat(e.getResponseBody()).doesNotContain("aws_role_credential");` There is no assertion on `e.getCode()`. GcpCredentialVendorTest.java:398-399 (`testUndecryptableStoredKeyIsNotNamedInTheError`) likewise asserts only message text. `storedKey` rethrows `e.getErrorCode()` of the underlying failure (FAILED_PRECONDITION for a type mismatch from `readCredential`), but no test pins that code. StoredGcpKeyVendingTest.java:183-186 `testPathOutsideTheLocationIsNotVended` accepts any `ApiException`, and its URL is also in the 400-asserting parameterized list.
How it was checked

Disprovers agreed (CONFIRMED): codex

How about adding the code assertions next to the existing message checks?

@shba24 shba24 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On lines this pull request does not change

server/src/main/java/io/unitycatalog/server/service/CredentialService.java:39

Nit (not a blocker): The credential service still says GCP is unavailable

Readers checking the service's supported providers will see the opposite of the new API behavior.

For example: The provider list says GCP - Not implemented yet, while createCredential now persists a gcp_service_account_key.

 *   <li><b>GCP</b> - Service account key credentials.
How it was checked

Checked by 1 independent check: CONFIRMED

Could we update the GCP entry alongside the new provider support?

url);
} else if (credentialDAO.getCredentialType() == CredentialType.GCP_SERVICE_ACCOUNT_KEY) {
ValidationUtils.checkArgument(
NormalizedURL.isGsPath(url),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: Two external locations can grant access to the same GCS objects

The overlap check compares the stored URL spelling. The token generator decodes the path with URI.getPath(), so two independently governed locations can resolve to one storage prefix. This is one bug class: Location identity is compared on the stored raw spelling, but the credential scope is built from the percent-decoded path, so two distinct locations can govern the same objects. The same issue appears in server/src/main/java/io/unitycatalog/server/service/credential/gcp/GcpCredentialVendor.java:230 (downscopeGcpCreds uses the decoded locationUri.getPath(), so the encoded and plain spellings produce identical boundaries.); server/src/main/java/io/unitycatalog/server/service/credential/aws/AwsPolicyGenerator.java:301 (The S3 policy uses the decoded uri.getPath() too, so s3://b/Archive and s3://b/%41rchive, stored as distinct locations, give the same resource ARN.); server/src/main/java/io/unitycatalog/server/service/credential/azure/AzureCredentialGenerator.java:74 (The ADLS SAS path is the decoded getPath(), so encoded and plain spellings of one directory get the same SAS scope.).

For example: An owner registers gs://bucket/Archive and gs://bucket/%41rchive. The catalog compares different strings, while both token conditions name Archive.

Use one GCS path representation for overlap checks, authorization, and boundary construction. Account for existing stored spellings when comparing a new location.

How it was checked

Reproduced: UC_TEST_DATABASE=<H2|POSTGRES_18|MYSQL_8> dev/run-tests.py "server/testOnly io.unitycatalog.server.service.credential.gcp.GcpCredentialVendorTest io.unitycatalog.server.sdk.externallocation.SdkExternalLocationCRUDTest"

head:

Failed tests: io.unitycatalog.server.sdk.externallocation.SdkExternalLocationCRUDTest#testEquivalentEncodedGsLocationIsRejected(): org.opentest4j.AssertionFailedError: Expected io.unitycatalog.client.ApiException to be thrown, but nothing was thrown. (at io.unitycatalog.server.utils.TestUtils.assertApiException(TestUtils.java:143)). Same on H2, POSTGRES_18 and MYSQL_8. The registration of gs://enc-bucket/%41rchive succeeds after gs://enc-bucket/Archive exists.

with the fix:

GcpCredentialVendorTest#testEncodedSpellingsOfOneNameShareOneBoundary passed on all three databases: NormalizedURL.from("gs://test-bucket/Archive") != NormalizedURL.from("gs://test-bucket/%41rchive") (different stored spellings), yet downscopeGcpCreds emits an identical availability condition for both (same boundary).

Checked by 2 independent checks: CONFIRMED

References:

Could location checks and token construction use one canonical GCS object path?

Path keyFile = null;
try {
if (createCredentialRequest.getGcpServiceAccountKey() != null) {
keyFile = writeKeyFile(createCredentialRequest.getGcpServiceAccountKey());

@shba24 shba24 Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A failed fixture write leaves its temporary file behind

The caller assigns keyFile only after writing succeeds. A write failure therefore skips cleanup of the generated test-key file, and the successful-write path also ignores the deletion result. This is one bug class: A test helper creates a temp file inside a callee, so the caller's finally cannot delete it if the write fails. The same issue appears in examples/cli/src/test/java/io/unitycatalog/cli/credential/CliCredentialOperations.java:67 (Files.createTempFile succeeds and Files.writeString throws, so writeKeyFile throws before returning, keyFile stays null at line 48, and the finally at line 56 s).

For example: If the temporary volume fills after createTempFile succeeds, writeKeyFile throws and the caller's keyFile remains null.

keyFile = Files.createTempFile("uc-test-key", ".json");
writeKeyFile(keyFile, createCredentialRequest.getGcpServiceAccountKey());
How it was checked

Reproduced: build/sbt 'cli/testOnly io.unitycatalog.cli.credential.CliCredentialCRUDTest -- --tests=.*testFailedFixtureWriteCleansUpKeyFile.*'

head:

[error] Test io.unitycatalog.cli.credential.CliCredentialCRUDTest.testFailedFixtureWriteCleansUpKeyFile failed: java.lang.AssertionError: 
[error] Expecting empty but was: [/tmp/uc-test-key8930384621801217317.json], took 33.353s
[error] Failed: Total 8, Failed 1, Errors 0, Passed 0, Skipped 7

Checked by 1 independent check: CONFIRMED

References:

Could the caller own the path before writing begins and check deletion through Files?

*/
public String getGcpPrivateKey(CredentialSecretStore secretStore) {
JsonNode stored = readCredential(CredentialType.GCP_SERVICE_ACCOUNT_KEY).get(PRIVATE_KEY_FIELD);
if (stored == null || !stored.isTextual()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A stored GCP credential without its private_key would fail with an NPE if the null check went away

The secret_access_key version of this check has a test, testMissingStoredValueIsReportedByName. The new private_key check does not.

Without it, the NPE escapes storedKey's catch (BaseException), so it is neither wrapped nor logged by name.

For example: Delete the stored == null || !stored.isTextual() check on line 395, and no test fails.

Add a case to CredentialDAOTest beside testMissingStoredValueIsReportedByName that removes private_key from a GCP DAO's stored JSON. It should assert INTERNAL and the credential name in the message.

How it was checked

Checked by 1 independent check: CONFIRMED

Could the existing missing-value test take a GCP case as well?

cloudCredentialVendor = repositories.getOwnedCloudCredentialVendor().orElse(null);
// Init metastore
repositories.getMetastoreRepository().initMetastoreIfNeeded();
warnAboutUnreadableSecrets(repositories);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A server without S3-compatible storage could quietly stop warning about unreadable GCP keys

The scan moved out of the S3-compatible branch so it now covers GCP keys too.

The repository method is tested, but the call site that now runs unconditionally is not.

For example: Move warnAboutUnreadableSecrets(repositories) back under isS3CompatibleStorageEnabled(), and no test fails.

If there is an existing startup-log test, add a case with S3-compatible storage disabled and an unreadable GCP credential. Otherwise this one may not be worth a dedicated test.

How it was checked

Checked by 1 independent check: CONFIRMED

Is there an existing startup test this could slot into, or would you rather leave it as log-only?

CredentialDAO dao = credentialDAO.get();
GcpServiceAccountKeyRequest key = storedKey(dao);
try {
return keyGenerators.apply(key).generate(credentialContext);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: A request can receive a token from a replacement location

PATH_READ checks READ_FILES against a location UUID. Vending then resolves the URL in a second transaction, so the binding used to sign the token can belong to a location the caller cannot read. Not settled: Codex said CONTESTED (mechanism shown by reading, no interleaving test). Opus said DISPROVED (behavior the PR did not change). I read the code. StorageCredentialVendorImpl.java and TemporaryPathCredentialsService.java are unchanged between base 69ff96e and head (git diff --stat is empty). At base, vending already resolved the CredentialDAO by URL (externalLocationUtils.getExternalLocationCredentialDaoForPath(path)), in its own transaction after authorization. So the window between authorizing one location UUID and resolving the credential by URL already exists at base for aws_iam_role and s3_compatible. The PR does not create the race. It does make the window reachable for GCP: at base, GcpCredentialVendor.vendGcpCredential threw UNIMPLEMENTED for a stored credential, and now it signs with it. Opus's DISPROVED rests on 'unchanged behavior', which holds for the mechanism but not for the new GCP branch, so I do not accept DISPROVED. Who can trigger it: only an administrator who deletes and recreates an external location at the same URL with a different credential while another caller's path-credential request is in flight. What the caller ends with: a token limited by the access boundary to the path and privilege they were authorized for a moment earlier. That is the same access a request finishing just before the replacement would have given them, since vended tokens cannot be revoked. The only difference is that the token is signed by the replacement's service account. Strongest evidence for: the two lookups run in separate transactions and no location id is carried between them. Strongest evidence against: the pattern exists at base, and the boundary limits the outcome to the already-authorized path. The interleaving is testable and nobody tested it, so the verdict stays CONTESTED. Missing fact: a deterministic test that replaces the location between authorization and credential resolution and checks which credential signs, and whether the caller gets any path or privilege beyond what the original authorization granted. If the boundary holds as read, this is at most a NITPICK about a pre-existing pattern. If the token reaches beyond the authorized path, it is a real blocker.

For example: A reader passes the check on the old location. If an administrator replaces it at the same URL before the credential lookup, the request uses the replacement's key and its storage permissions.

Do not fix in this PR. If it is worth fixing, do it in a separate cross-cutting PR: pass the authorized external-location UUID from the authorization step into StorageCredentialVendorImpl, and fail (or re-authorize) when the location that covers the URL at resolution time has a different id. Apply this to every credential type, not only gcp_service_account_key.

How it was checked

Checked by 2 independent checks, which split: CONTESTED, DISPROVED

Missing fact: Codex said CONTESTED (mechanism shown by reading, no interleaving test). Opus said DISPROVED (behavior the PR did not change). I read the code. StorageCredentialVendorImpl.java and TemporaryPathCredentialsService.java are unchanged between base 69ff96e and head (git diff --stat is empty). At base, vending already resolved the CredentialDAO by URL (externalLocationUtils.getExternalLocationCredentialDaoForPath(path)), in its own transaction after authorization. So the window between authorizing one location UUID and resolving the credential by URL already exists at base for aws_iam_role and s3_compatible. The PR does not create the race. It does make the window reachable for GCP: at base, GcpCredentialVendor.vendGcpCredential threw UNIMPLEMENTED for a stored credential, and now it signs with it. Opus's DISPROVED rests on 'unchanged behavior', which holds for the mechanism but not for the new GCP branch, so I do not accept DISPROVED. Who can trigger it: only an administrator who deletes and recreates an external location at the same URL with a different credential while another caller's path-credential request is in flight. What the caller ends with: a token limited by the access boundary to the path and privilege they were authorized for a moment earlier. That is the same access a request finishing just before the replacement would have given them, since vended tokens cannot be revoked. The only difference is that the token is signed by the replacement's service account. Strongest evidence for: the two lookups run in separate transactions and no location id is carried between them. Strongest evidence against: the pattern exists at base, and the boundary limits the outcome to the already-authorized path. The interleaving is testable and nobody tested it, so the verdict stays CONTESTED. Missing fact: a deterministic test that replaces the location between authorization and credential resolution and checks which credential signs, and whether the caller gets any path or privilege beyond what the original authorization granted. If the boundary holds as read, this is at most a NITPICK about a pre-existing pattern. If the token reaches beyond the authorized path, it is a real blocker.

Could credential resolution verify that it is vending for the same location UUID that passed authorization?

}
// A gcp_service_account_key credential reaches only gs:// paths, so it cannot become
// another type; the update API has no field to change its key.
ValidationUtils.checkArgument(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A key-rotation request can succeed without replacing the key

UpdateCredentialRequest omits the create-only field, and the UC mapper ignores unknown properties. The GCP guard therefore never sees the attempted rotation, leaving the previous key active after a successful response.

For example: An operator sends a replacement gcp_service_account_key to PATCH. The response succeeds and updated_at advances, but the next vend still uses the old key.

Optional, not needed for this PR. If operators should get explicit feedback, reject a PATCH body that names gcp_service_account_key with INVALID_ARGUMENT, scoped to the credential update endpoint (for example by checking the raw JSON for that key). Do not turn on FAIL_ON_UNKNOWN_PROPERTIES for every endpoint, because that would break API compatibility. Otherwise keep the current behavior: it is documented in api/all.yaml and docs/usage/cli.md.

How it was checked

Reproduced: UC_TEST_DATABASE=<H2|POSTGRES_18|MYSQL_8> dev/run-tests.py "server/testOnly io.unitycatalog.server.service.credential.gcp.StoredGcpKeyVendingTest"

head:

[error] Test ...StoredGcpKeyVendingTest.testRawPatchRejectsKeyReplacement failed: AssertionFailedError: [{"name":"gcs_credential",...,"gcp_service_account_key":{"email":"[email protected]","private_key_id":"0123456789abcdef"},"comment":"rotated",...,"updated_at":1795837979078,...}] expected: 400 but was: 200 (StoredGcpKeyVendingTest.java:247). The suite reported Total 20, Failed 1, Passed 19 on H2, PostgreSQL 18 and MySQL 8.4.

Checked by 2 independent checks, which split: CONFIRMED, NITPICK

References:

Should this specific field on PATCH produce INVALID_ARGUMENT so operators can distinguish an unsupported rotation from a successful one?

session.createQuery(
"FROM CredentialDAO WHERE credentialType = :type", CredentialDAO.class);
query.setParameter("type", CredentialDAO.CredentialType.S3_COMPATIBLE);
"FROM CredentialDAO WHERE credentialType IN :types", CredentialDAO.class);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A new credential type with a secret would be left out of the startup secret check

findUnreadableSecrets keeps its own list of secret-bearing types, S3_COMPATIBLE and GCP_SERVICE_ACCOUNT_KEY, and branches to pick the getter. CredentialDAO already knows this through WRITE_ONLY_FIELDS and its per-type getters.

The two copies are kept in step by hand.

Cost of keeping it: Adding a type with a secret means editing the DAO, the scan's IN :types list and the scan's if/else. Forget the list and that type is never checked at startup. A changed server.credential-encryption-key then shows up only on the first vend. Forget the branch and the else calls getGcpPrivateKey on a non-GCP credential.

// CredentialDAO
public void checkStoredSecretsReadable(CredentialSecretStore secretStore) {
  switch (credentialType) {
    case S3_COMPATIBLE -> getS3SecretAccessKey(secretStore);
    case GCP_SERVICE_ACCOUNT_KEY -> getGcpPrivateKey(secretStore);
    case AWS_IAM_ROLE -> {}
  }
}

// CredentialRepository.findUnreadableSecrets
for (CredentialDAO dao : query.list()) {
  try {
    dao.checkStoredSecretsReadable(secretStore);
  } catch (RuntimeException e) {
    unreadable.put(dao.getName(), e);
  }
}
How it was checked

Checked by 1 independent check: NITPICK

How about moving the per-type secret read into CredentialDAO, so the scan has nothing of its own to keep in step?

Comment thread api/all.yaml
private_key_id:
$ref: "#/components/schemas/GcpPrivateKeyId"
private_key:
description: The PEM-encoded PKCS#8 private key of the service account key. Write-only; never returned.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A correctly encoded EC key gets a format error

Credential creation requires an RSA key. Without that qualifier, the error directs callers to fix the encoding when the algorithm is the problem.

For example: The field description says PEM-encoded PKCS#8 private key. The DAO test builds an EC key in exactly that format and expects INVALID_ARGUMENT.

Describe the field and error as requiring a PEM-encoded PKCS#8 RSA private key, then regenerate the model reference.

How it was checked

Checked by 1 independent check: NITPICK

References:

Could we name RSA in both the schema and the validation error?

*/
static BaseException storedKeyError(IOException e) {
if (String.valueOf(e.getMessage()).startsWith("Error code invalid_request")) {
return credentialError(e);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocker: One stored-key error forwards the upstream diagnostic to the caller

The method promises that no public message names an account or key. For invalid_request, it calls credentialError, which appends the complete upstream message. This is one bug class: Upstream token-service text is copied into the caller-facing error for invalid_request, so the no-account-or-key promise depends on Google's wording. The same issue appears in server/src/main/java/io/unitycatalog/server/service/credential/gcp/GcpCredentialVendor.java:302 (The same verbatim forwarding on the gcs.* settings path. It predates the change, and that path has no privacy promise, but it is the same helper.).

For example: If an invalid_request description includes an account identifier, a reader who can vend a token but cannot read the credential would receive that identifier. The guarantee matters on this branch even though the other mappings use fixed messages.

How it was checked

Checked by 2 independent checks: CONTESTED

Is there a guarantee about the contents of this response, or could we keep its details in the administrator log?


private static void validateGcpServiceAccountKey(GcpServiceAccountKeyRequest key) {
ValidationUtils.checkArgument(
key.getEmail() != null && !key.getEmail().isBlank(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): A key file without client_email could turn into a 500 without any test noticing

The CLI passes null for any field the key file lacks and leaves it for the server to report.

The server checks email != null, but the tests only send a blank email. A blank private_key_id is not tested either. This is one bug class: New guard and branch operands in the GCP credential path have no input that reaches them, so removing them passes every test. The same issue appears in server/src/main/java/io/unitycatalog/server/persist/dao/CredentialDAO.java:295 (No test sends a blank private_key_id, so dropping !isBlank() would store ' ' as the key id.); server/src/main/java/io/unitycatalog/server/persist/dao/CredentialDAO.java:395 (The GCP 'no stored private_key' INTERNAL branch is untested. Without it, asText gives an NPE, which escapes storedKey's catch (BaseException).); server/src/main/java/io/unitycatalog/server/service/credential/CachingCloudCredentialVendor.java:192 (Nothing pins that server and client vends of a GCP key share one cache entry.); server/src/main/java/io/unitycatalog/server/UnityCatalogServer.java:344 (warnAboutUnreadableSecrets now runs with S3-compatible storage off, but moving it back inside the flag branch fails no test.).

For example: Remove key.getEmail() != null && on line 292, and a null email throws an NPE. Every test still passes.

new InvalidCreate(gcpRequest(privateKey, null), String.format(missing, "email")),
new InvalidCreate(
    gcpRequest(privateKey).gcpServiceAccountKey(gcpKey(privateKey).privateKeyId(" ")),
    String.format(missing, "private_key_id")),
How it was checked

Checked by 1 independent check: CONFIRMED

How about adding these two rows to the existing invalidCreates list?

gcpKeyVersion,
context.getS3Endpoint(),
context.getS3Region(),
context.isServerAccess() && s3CompatibleVersion.isPresent());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (not a blocker): Server and client vends of a GCP key could stop sharing a cache entry without a test noticing

The Key Javadoc says a gcp_service_account_key credential is vended the same way to both, so the two share an entry.

Only AWS IAM roles have a test for that.

For example: Make line 192 also depend on gcpKeyVersion.isPresent(), and every GCP server vend misses the cache. No test notices.

@Test
public void testGcpKeyServerAndClientVendsShareAnEntry() {
  vendDistinctCredentials();
  CachingCloudCredentialVendor cache = cache();
  CredentialContext client = gcpCtx(GCP_KEY_ID, "fingerprint-1");
  CredentialContext server =
      CredentialContext.create(
          GCS_LOC, READ_ONLY, client.getCredentialDAO(), Optional.empty(), Optional.empty(),
          /* isServerAccess= */ true);
  assertEquals(cache.vendCredential(client), cache.vendCredential(server));
  // verify the GCP vendor was called once
}
How it was checked

Checked by 1 independent check: CONFIRMED

Would a GCP twin of the AWS sharing test be worth adding?

timothyw553 and others added 20 commits November 30, 2026 19:11
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]>
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]>
@timothyw553
timothyw553 force-pushed the stack/gcp-credential-vending branch from e122cbe to 3a80188 Compare November 30, 2026 19:14

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants