Repository navigation
[Server][CLI] Finalize S3-compatible storage: endpoint and path style on the external location - #2289
Conversation
|
/review |
2766c9e to
708dcb5
Compare
|
/review |
## 🥞 Stacked PR Use this [link](https://github.com/unitycatalog/unitycatalog/pull/2169/files) to review incremental changes. - [stack/s3compat_spec](#2170) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2170/files)] [MERGED] - [stack/s3compat_credentials](#2171) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2171/files)] [MERGED] - [stack/s3compat_vending](#2172) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2172/files)] [MERGED] - [stack/s3compat_hadoop_cli](#2173) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2173/files)] [MERGED] - [stack/s3compat_test_storage](#2174) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2174/files)] [MERGED] - [stack/s3compat_helm_key](#2175) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2175/files)] [MERGED] - [**stack/s3compat_credentials_text**](#2169) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2169/files)] ← _this PR_ - [stack/s3compat_location_endpoint](#2289) [[Files changed](https://github.com/unitycatalog/unitycatalog/pull/2289/files/76859fc160061ad821312ef6bc69f986e9c44e5f..708dcb589fb36067a3e15464c2fd5513cddab4cb)] --------- Last of a stack adding experimental S3-compatible storage (MinIO, Ceph, SeaweedFS, RustFS, Garage): #2170 to #2175 are merged. **Description of changes** Stores credentials as text instead of PostgreSQL large objects, and widens the column on MySQL, where `tinytext` (255 bytes) is too small for real `s3_compatible` credentials with `assume_role`. It makes the change #1928 plans for `uc_credentials.credential`, and is a placeholder until #1928 and its follow-up merge. Builds on #2117 (merged): the server starts only once the steps have run, so it never sees the column before step V4. - `CredentialDAO.credential` drops `@Lob` and adds `length = 16777215` - Schema step `V4__credentials_credential_as_text`, one statement per database: - MySQL: `tinytext` to `mediumtext` - PostgreSQL: large object (`oid`) to `text`, through `convert_from(lo_get(credential), 'UTF8')` - H2: no change - Schema effect files for V4 - `docs/server/upgrades.md`: - the PostgreSQL step reads every credential's large object as UTF-8, as `hibernate.connection.username`; a missing or unreadable one fails it, with how to recover - the large objects stay (still holding the earlier stored values) for `vacuumlo`, and a release from before the step cannot read the converted column on PostgreSQL - Removes the `TODO(#2169)` on `CredentialDAO.setS3Compatible` - `SchemaMigratorTest.upgradeKeepsStoredCredentialsAndFitsLongerOnes`: a credential stored before the step (a large object on PostgreSQL, with two-, three- and four-byte characters) reads back as the same text, and one longer than 255 bytes fits, on all three databases; on PostgreSQL the old row is written through pgjdbc's large object path - `SchemaMigratorTest.upgradeWithAMissingLargeObjectChangesNothing`: on PostgreSQL, a credential whose large object is missing fails the step and leaves the column and the row as they were - `MigrationStepRulesTest`: MySQL `tinytext` widens to `text`, `mediumtext` or `longtext`; on PostgreSQL an `oid` column may change only as `TYPE text USING convert_from(lo_get(c), 'UTF8')`, the one allowed change that rows can fail, with cases for it; a plain type change of an `oid` column is refused - `SchemaMigratorTest.refusesAStepThatDropsAConstraintTheDatabaseNoLongerHasByThatName` brings the database to step 3 itself instead of to the newest step, so a later step no longer leaves a gap in its schema history - `BaseCredentialCRUDTest.testLongS3CompatibleCredential`: a credential over 1000 bytes, with non-ASCII text, round-trips through the server on every database Compatibility: no API change. Going back to an earlier release needs the database backup. Tests: `SchemaMigratorTest`, `BaselineMatchesEntitiesTest`, `MigrationStepRulesTest` and the credential and external location CRUD tests on H2, PostgreSQL 18 and MySQL 8 (`MigrationStepRulesTest` with `UC_TEST_MIGRATION_CHECKS=true`); all pass. **PR Checklist** - [x] 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. - [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 This pull request and its description were written by Isaac. Signed-off-by: Yi Li <[email protected]> Co-authored-by: Isaac <[email protected]>
timothyw553
left a comment
There was a problem hiding this comment.
overall the endpoint move makes sense, i left a few comments. the main blocker is the orphan location validation and repair path, along with a question on endpoint update permissions and a few test/doc gaps.
| static void validateForCredential( | ||
| String url, String endpoint, S3AddressingStyle addressingStyle, CredentialDAO credentialDAO) { | ||
| // A force-deleted credential leaves nothing to check against; setting a new one checks again. | ||
| if (credentialDAO == null) { |
There was a problem hiding this comment.
when the credential is force-deleted (credentialDAO == null), this returns early and skips checking endpoint syntax, style without an endpoint, and bucket rules. also, how would someone repair an orphaned s3-compatible location onto an IAM credential or clear bad fields if null in PATCH means keep? could we validate the credential-independent rules before this return, add a way to clear endpoint/addressingStyle, and add regression tests?
+ ValidationUtils.checkArgument(
+ addressingStyle == null || endpoint != null,
+ "An addressing style needs an endpoint.");
+ if (endpoint != null) {
+ ValidationUtils.validateHttpUrl(endpoint, "endpoint");
+ }
if (credentialDAO == null) {
return;
}There was a problem hiding this comment.
Done for the checks: the endpoint form and length, the s3:// URL and the bucket rule now run before the early return, with tests. path_style_access without an endpoint is refused earlier in the update, since an update can't give a location without an endpoint either field. For repair, the location keeps its storage kind: one with an endpoint can only get another s3_compatible_access_key credential, and one without can't get one. Moving a location to other storage means deleting it and creating a new one, so there's no way to clear endpoint or path_style_access on update.
| .region(Region.US_EAST_1) | ||
| .endpointOverride(URI.create(s3Endpoint)) | ||
| .forcePathStyle(true) | ||
| .forcePathStyle(storageBucket.addressingStyle() == S3AddressingStyle.PATH) |
There was a problem hiding this comment.
all the region-lookup tests pass PATH, so nothing exercises forcePathStyle(false) or verifies the cache isolates results by addressing style. could we extend the cache test to hit the same endpoint and bucket with both styles and check forcePathStyle(true)/false and separate cached regions?
| urls.stream().allMatch(NormalizedURL::isS3Path), | ||
| "Cannot make credential '%s' an s3_compatible credential: it is used by an external" | ||
| + " location that is not an s3:// path.", | ||
| credentialDAO.getCredentialType() == newType |
There was a problem hiding this comment.
looks like we removed test coverage for updating an in-use s3_compatible_access_key credential while keeping its type. could we add back a test for rotating keys on an in-use s3-compatible credential (and updating an in-use IAM role) alongside the type-change rejection tests?
| if (updateExternalLocation.getComment() != null) { | ||
| existingLocation.setComment(updateExternalLocation.getComment()); | ||
| } | ||
| if (updateExternalLocation.getEndpoint() != null) { |
There was a problem hiding this comment.
updating endpoint here lets someone with location MANAGE redirect existing tables and volumes without credential permissions or hitting the in-use check. is that permission shift intentional? at minimum, should an endpoint change run validateExternalLocationNotInUse unless force is set, similar to URL changes?
if (updateExternalLocation.getEndpoint() != null) {
+ if (!Objects.equals(
+ existingLocation.getEndpoint(), updateExternalLocation.getEndpoint())
+ && !Boolean.TRUE.equals(updateExternalLocation.getForce())) {
+ ExternalLocationUtils.validateExternalLocationNotInUse(
+ session, storedUrlToCheckOrRefuse(existingLocation.getUrl(), name));
+ }
existingLocation.setEndpoint(updateExternalLocation.getEndpoint());
}| || (Objects.equals(other.s3Endpoint(), aws.s3Endpoint()) | ||
| && Objects.equals(other.s3Region(), aws.s3Region())), | ||
| && Objects.equals(other.s3Region(), aws.s3Region()) | ||
| && other.isS3PathStyle() == aws.isS3PathStyle()), |
There was a problem hiding this comment.
the conflict tests don't hold endpoint and region equal while changing only addressing style, and the FileSystemCredId cache tests change the endpoint too, so tests would still pass if this check and the pathStyle. key were removed. could we add a conflict test where only style differs and a cached load test with opposite styles?
| type: string | ||
| description: | | ||
| EXPERIMENTAL. Region to sign S3 requests with, set together with `s3.endpoint`. | ||
| s3.path-style-access: |
There was a problem hiding this comment.
s3.path-style-access is a boolean here, while spec/protocols/ManagedDeltaTablesSpec.md still describes a string-to-string map, says requests always use path style, and only lists two S3 keys. could we update the protocol spec to match all three settings and both addressing styles?
708dcb5 to
b2c8b81
Compare
|
/review |
b2c8b81 to
7259ef5
Compare
|
/review |
7259ef5 to
99aa712
Compare
|
/review |
99aa712 to
582c44d
Compare
|
/review |
|
/review |
e242828 to
148d29e
Compare
|
/review |
1 similar comment
|
/review |
unitycatalog/unitycatalog#2289 now has the final S3-compatible API and one approval. It removes the server.s3-compatible-storage.enabled flag and the experimental labels. The credential becomes s3_compatible_access_key with flat role_arn and sts_endpoint. The location gets endpoint and path_style_access, with virtual-hosted as the default. Vends return external_location_settings. The storage brief now records that shape, the merged #2346 (credential purpose required), and the GCS PRs leaving draft. The governance notes move #2387 (permissions update validated whole) from open to merged, and add the token signing key checks from #2389 and #2392. Co-authored-by: Isaac <[email protected]>
unitycatalog/unitycatalog#2289 now has the final S3-compatible API and one approval. It removes the server.s3-compatible-storage.enabled flag and the experimental labels. The credential becomes s3_compatible_access_key with flat role_arn and sts_endpoint. The location gets endpoint and path_style_access, with virtual-hosted as the default. Vends return external_location_settings. The storage brief now records that shape, the merged #2346 (credential purpose required), and the GCS PRs leaving draft. The governance notes move #2387 (permissions update validated whole) from open to merged, and add the token signing key checks from #2389 and #2392. Co-authored-by: Isaac <[email protected]>
shba24
left a comment
There was a problem hiding this comment.
On lines this pull request does not change
docs/usage/cli.md:159
Nit, medium probability: The CLI guide doesn't show how to put an external location on S3-compatible storage
docs/usage/cli.md lists only --name, --url and --credential_name for external_location create, and no --endpoint or --path_style_access for update.
Its force item still says it only lets the URL change, but it now also covers a change of endpoint or path_style_access on a location that is in use.
Details
For example: A user follows the guide to create a location for an s3_compatible_access_key credential. The server rejects it with INVALID_ARGUMENT ("need the endpoint of their storage"), and the page never names the --endpoint flag that fixes it. This is one bug class: The user CLI guide was not updated when CLI commands gained S3-compatible flags and force was widened. The same issue appears in docs/usage/cli.md:105 (The create example shows only --name, --url and --credential_name.); docs/usage/cli.md:42 (The credential section documents only --aws_iam_role_arn.).
In the create and update examples, add [--endpoint <endpoint>] and [--path_style_access true|false], each with a one-line note: the endpoint is http[s]://host[:port] and is required with an s3_compatible_access_key credential; path style defaults to virtual-hosted. Widen item 6 (force) to say it also lets an in-use location change its endpoint or path style. A short s3_compatible_access_key credential example (--s3_access_key_id, --s3_secret_access_key, --s3_role_arn) in the credential section would round it out.
Evidence:
The guide's create and update blocks and the force item (docs/usage/cli.md:106-109, 143-150, 159-160) leave out the endpoint and path-style options. CliUtils now registers ENDPOINT and PATH_STYLE_ACCESS on both commands. The repository requires an endpoint for an s3_compatible_access_key credential, and its force branch now also covers endpoint and path_style_access changes. I searched docs/ for 'endpoint', 'path_style', 's3_compatible' and 's3_access_key_id'. Only docs/server/configuration.md mentions s3_compatible_access_key, and only for the encryption key.
docs/usage/cli.md:106-110
bin/uc external_location create \
--name <name> # (1) \
--url <URL> # (2) \
--credential_name <credential_name> # (3)
```
docs/usage/cli.md:143-150
bin/uc external_location update \
--name <name> \ # (1)
[--new_name <new_name>] \ # (2)
[--url <url>] \ # (3)
[--credential_name <credential_name>] \ # (4)
[--comment <comment>] \ # (5)
[--force true] # (6)
```
docs/usage/cli.md:159-160
6. `force`: _\[Optional\]_ Change the URL even if the external location is in use. Whatever is stored under the old
URL can no longer get credentials from this external location.
examples/cli/src/main/java/io/unitycatalog/cli/utils/CliUtils.java:403-425
put(
CREATE,
new CliOptions(
List.of(CliParams.NAME, CliParams.URL, CliParams.CREDENTIAL_NAME),
List.of(
CliParams.ENDPOINT, CliParams.PATH_STYLE_ACCESS, CliParams.COMMENT)));
put(
LIST,
new CliOptions(
List.of(), List.of(CliParams.MAX_RESULTS, CliParams.PAGE_TOKEN)));
put(GET, new CliOptions(List.of(CliParams.NAME), List.of()));
put(
UPDATE,
new CliOptions(
List.of(CliParams.NAME),
List.of(
CliParams.NEW_NAME,
CliParams.URL,
CliParams.CREDENTIAL_NAME,
CliParams.ENDPOINT,
CliParams.PATH_STYLE_ACCESS,
CliParams.COMMENT,
CliParams.FORCE)));
server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:115-119
credentialDAO.getName(),
url);
ValidationUtils.checkArgument(
endpoint != null,
"Storage credential '%s' is an s3_compatible_access_key credential, so its external"
How it was checked:
Checked by 1 independent check: CONFIRMED
Now that the feature is out of experimental, could the CLI guide show the S3-compatible flags too?
| UUID credentialId = externalLocationDAOs.get(0).getCredentialId(); | ||
| CredentialDAO credentialDAO = session.get(CredentialDAO.class, credentialId); | ||
| ExternalLocationDAO location = externalLocationDAOs.get(0); | ||
| CredentialDAO credentialDAO = session.get(CredentialDAO.class, location.getCredentialId()); |
There was a problem hiding this comment.
Blocker, low probability: A concurrent credential change can route a vend to AWS S3
The location and credential are read in separate statements under READ_COMMITTED, so they can come from different committed states. The credential type then determines whether the endpoint is returned, allowing requests to reach the wrong storage.
Details
For example: A vend reads a location using credential A; an operator moves the location to B and changes the now-unused A to an AWS IAM role before the vend reads A. The caller receives AWS credentials without the location's endpoint.
Read the location and its credential from a consistent snapshot, or verify and retry the binding before vending.
Evidence:
The location and credential are read in separate statements under the database's default isolation; H2 and PostgreSQL default to READ_COMMITTED. A credential reassignment followed by a type change can therefore produce a mismatched pair, and vending selects storage from the newer credential type.
server/src/main/java/io/unitycatalog/server/persist/utils/ExternalLocationUtils.java:311-316
public Optional<LocationCredential> getExternalLocationCredentialForPath(NormalizedURL url) {
return TransactionManager.executeWithTransaction(
sessionFactory,
session -> getExternalLocationCredentialForPath(session, url),
"Failed to get storage credential by URL",
/* readOnly= */ true);
server/src/main/java/io/unitycatalog/server/persist/utils/ExternalLocationUtils.java:326-358
List<ExternalLocationDAO> externalLocationDAOs =
ExternalLocationUtils.<ExternalLocationDAO>getEntityDAOsWithURLOverlap(
session,
url,
SecurableType.EXTERNAL_LOCATION,
/* limit= */ 2,
/* includeParent= */ true,
/* includeSelf= */ true,
/* includeSubdir= */ false)
.stream()
.toList();
if (externalLocationDAOs.isEmpty()) {
// Not found
return Optional.empty();
} else if (externalLocationDAOs.size() > 1) {
// This is an invalid internal state. We never allow external locations with
// overlapping URLs.
throw new BaseException(
ErrorCode.INTERNAL, "More than one external location with URL '" + url + "' exist.");
}
// Get the credential that is assigned to the external location
ExternalLocationDAO location = externalLocationDAOs.get(0);
CredentialDAO credentialDAO = session.get(CredentialDAO.class, location.getCredentialId());
if (credentialDAO == null) {
throw new BaseException(
ErrorCode.INTERNAL,
String.format(
"The storage credential for '%s' no longer exists. Update the external location "
+ "that covers this path with a new credential.",
url));
}
return Optional.of(new LocationCredential(location, credentialDAO));
server/src/main/java/io/unitycatalog/server/persist/CredentialRepository.java:291-299
private void validateTypeKeptWhileUsed(
Session session, CredentialDAO credentialDAO, CredentialType newType) {
// The message leaves the location out: managing a credential does not grant reading the
// locations that use it.
ValidationUtils.checkArgument(
credentialDAO.getCredentialType() == newType
|| getExternalLocationDAOUsingCredential(session, credentialDAO.getId()) == null,
"Cannot change the type of credential '%s' while an external location uses it.",
credentialDAO.getName());
server/src/main/java/io/unitycatalog/server/service/credential/StorageCredentialVendorImpl.java:80-91
Optional<LocationCredential> locationCredential =
externalLocationUtils.getExternalLocationCredentialForPath(path);
Optional<CredentialDAO> credentialDAO = locationCredential.map(LocationCredential::credential);
// A path on S3-compatible storage reaches the storage at its location's endpoint, addressed as
// the location says.
Optional<ExternalLocationDAO> s3CompatibleLocation =
locationCredential
.filter(found -> found.credential().getCredentialType() == CredentialType.S3_COMPATIBLE)
.map(LocationCredential::location);
Optional<String> s3Endpoint = s3CompatibleLocation.map(StorageCredentialVendorImpl::s3Endpoint);
Optional<Boolean> s3PathStyleAccess =
s3CompatibleLocation.map(ExternalLocationDAO::getS3PathStyleAccess);
server/src/test/java/io/unitycatalog/server/persist/utils/TransactionManagerTest.java:498-499
// The database's default isolation level (READ_COMMITTED on H2 and PostgreSQL,
// REPEATABLE_READ on MySQL)
How it was checked:
Reproduced: dev/run-tests.py -p 1 'server/testOnly *ExternalLocationUtilsTest' (UC_TEST_DATABASE=POSTGRES_18 for PostgreSQL)
head:
ExternalLocationUtilsTest#testVendLookupKeepsCredentialTypeInOneSnapshot(): org.opentest4j.AssertionFailedError: expected: S3_COMPATIBLE but was: AWS_IAM_ROLE (ExternalLocationUtilsTest.java:145). Same on H2 and POSTGRES_18; 12 other tests in the class passed.
server/src/test/java/io/unitycatalog/server/persist/utils/ExternalLocationUtilsTest.java:79-146
@Test
public void testVendLookupKeepsCredentialTypeInOneSnapshot() throws Exception {
UUID credentialA = UUID.randomUUID();
UUID credentialB = UUID.randomUUID();
session.beginTransaction();
for (UUID id : List.of(credentialA, credentialB)) {
session.persist(
CredentialDAO.builder()
.id(id)
.name("cred-" + id)
.credentialType(CredentialDAO.CredentialType.S3_COMPATIBLE)
.credential("{}")
.purpose(CredentialPurpose.STORAGE)
.createdAt(new java.util.Date())
.createdBy("t")
.owner("t")
.build());
}
ExternalLocationDAO location =
ExternalLocationDAO.builder()
.id(UUID.randomUUID())
.name("compat")
.url("s3://bucket/compat")
.credentialId(credentialA)
.endpoint("http://minio:9000")
.createdAt(new java.util.Date())
.build();
session.persist(location);
session.getTransaction().commit();
// Between the location read and the credential read, another session moves the location to B
// and retypes the now-unused A to an IAM role, both committed.
boolean[] armed = {true};
Properties properties = testDatabase.hibernateProperties();
properties.put(
"hibernate.session_factory.statement_inspector",
(org.hibernate.resource.jdbc.spi.StatementInspector)
sql -> {
if (armed[0] && sql.contains("uc_credentials")) {
armed[0] = false;
try (Connection c = testDatabase.dataSource().getConnection();
Statement st = c.createStatement()) {
st.executeUpdate(
"UPDATE uc_external_locations SET credential_id = '"
+ credentialB
+ "' WHERE id = '"
+ location.getId()
+ "'");
st.executeUpdate(
"UPDATE uc_credentials SET credential_type = 'AWS_IAM_ROLE' WHERE id = '"
+ credentialA
+ "'");
} catch (java.sql.SQLException e) {
throw new IllegalStateException(e);
}
}
return sql;
});
SessionFactory racing = testDatabase.openHibernateConfigurator(properties).getSessionFactory();
ExternalLocationUtils.LocationCredential found =
new ExternalLocationUtils(racing)
.getExternalLocationCredentialForPath(NormalizedURL.from("s3://bucket/compat/x"))
.orElseThrow();
assertThat(armed[0]).as("interleaving ran").isFalse();
assertThat(found.location().getEndpoint()).isNotNull();
assertThat(found.credential().getCredentialType())
.isEqualTo(CredentialDAO.CredentialType.S3_COMPATIBLE);
}
Checked by 2 independent checks: CONFIRMED
How about reading the location and credential from one consistent snapshot?
| UUID credentialId = externalLocationDAOs.get(0).getCredentialId(); | ||
| CredentialDAO credentialDAO = session.get(CredentialDAO.class, credentialId); | ||
| ExternalLocationDAO location = externalLocationDAOs.get(0); | ||
| CredentialDAO credentialDAO = session.get(CredentialDAO.class, location.getCredentialId()); |
There was a problem hiding this comment.
Blocker, low probability: A vend can pair a previous endpoint with newly rotated keys
The endpoint and key pair come from separate reads. At READ COMMITTED, those reads can return a combination that never existed in the catalog.
Details
For example: A vend reads endpoint A. An operator moves the location to B and rotates its key pair before the vend reads the credential. A static-key response then returns A with the new keys. This is one bug class: Credential vending reads a location and then its credential in two statements, with no shared snapshot and no check that the two still belong together, so the response can mix two committed states. The same issue appears in server/src/main/java/io/unitycatalog/server/service/credential/StorageCredentialVendorImpl.java:85 (The vend selects the S3-compatible path only when credential().getCredentialType()==S3_COMPATIBLE and ignores the location's stored endpoint.).
Fetch the location and credential in one query, preserving the distinction between no matching location and a location whose credential was deleted.
Evidence:
The first query materializes the location. A later session.get reads its credential. The read-only transaction uses the default isolation level. Neither read takes the writers' locks. The endpoint update and same-type key rotation can commit separately between those reads. StorageCredentialVendorImpl then places the two versions in one context.
server/src/main/java/io/unitycatalog/server/persist/utils/ExternalLocationUtils.java:311-317
public Optional<LocationCredential> getExternalLocationCredentialForPath(NormalizedURL url) {
return TransactionManager.executeWithTransaction(
sessionFactory,
session -> getExternalLocationCredentialForPath(session, url),
"Failed to get storage credential by URL",
/* readOnly= */ true);
}
server/src/main/java/io/unitycatalog/server/persist/utils/ExternalLocationUtils.java:326-336
List<ExternalLocationDAO> externalLocationDAOs =
ExternalLocationUtils.<ExternalLocationDAO>getEntityDAOsWithURLOverlap(
session,
url,
SecurableType.EXTERNAL_LOCATION,
/* limit= */ 2,
/* includeParent= */ true,
/* includeSelf= */ true,
/* includeSubdir= */ false)
.stream()
.toList();
server/src/main/java/io/unitycatalog/server/persist/utils/ExternalLocationUtils.java:347-358
// Get the credential that is assigned to the external location
ExternalLocationDAO location = externalLocationDAOs.get(0);
CredentialDAO credentialDAO = session.get(CredentialDAO.class, location.getCredentialId());
if (credentialDAO == null) {
throw new BaseException(
ErrorCode.INTERNAL,
String.format(
"The storage credential for '%s' no longer exists. Update the external location "
+ "that covers this path with a new credential.",
url));
}
return Optional.of(new LocationCredential(location, credentialDAO));
server/src/main/java/io/unitycatalog/server/persist/utils/TransactionManager.java:38-45
public static <R> R executeWithTransaction(
SessionFactory sessionFactory,
DatabaseOperation<R> operation,
String errorMessage,
boolean readOnly) {
return executeWithTransaction(
sessionFactory, operation, errorMessage, readOnly, Optional.empty());
}
server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:377-379
if (endpoint != null) {
existingLocation.setEndpoint(endpoint);
}
How it was checked:
Reproduced: UC_TEST_DATABASE=POSTGRES_18 dev/run-tests.py -p 1 'server/testOnly *ExternalLocationUtilsTest' (also default H2, and UC_TEST_DATABASE=MYSQL_8)
head:
H2 and PostgreSQL 18: ExternalLocationUtilsTest#testVendLookupDoesNotPairOldEndpointWithRotatedKeys(): java.lang.AssertionError: Expecting actual: ["http://a.example", "new"] to be in: [["http://a.example", "old"], ["http://b.example", "new"]] (ExternalLocationUtilsTest.java:804). 13 tests, 1 failed. The test also asserts that the hook fired exactly once.
with the fix:
MySQL 8: 1 suites, 13 tests, 0 failed. REPEATABLE READ reads one snapshot, so the claim does not hold there. No fix was tried, so there is no run with a fix.
server/src/test/java/io/unitycatalog/server/persist/utils/ExternalLocationUtilsTest.java:713-806
@Test
public void testVendLookupDoesNotPairOldEndpointWithRotatedKeys() throws Exception {
Properties properties = testDatabase.hibernateProperties();
properties.setProperty("hibernate.connection.pool_size", "3");
SessionFactory realFactory =
testDatabase.openHibernateConfigurator(properties).getSessionFactory();
UUID credentialId = UUID.randomUUID();
try (Session setup = realFactory.openSession()) {
setup.beginTransaction();
setup.persist(
io.unitycatalog.server.persist.dao.CredentialDAO.builder()
.id(credentialId)
.name("cred")
.credentialType(
io.unitycatalog.server.persist.dao.CredentialDAO.CredentialType.S3_COMPATIBLE)
.credential("{\"access_key_id\":\"old\"}")
.purpose(io.unitycatalog.server.model.CredentialPurpose.STORAGE)
.createdAt(new java.util.Date())
.build());
setup.persist(
ExternalLocationDAO.builder()
.id(UUID.randomUUID())
.name("loc")
.url("s3://bucket/a")
.credentialId(credentialId)
.endpoint("http://a.example")
.build());
setup.getTransaction().commit();
}
// Commit an endpoint move and a key rotation between the location read and the credential read.
java.util.concurrent.atomic.AtomicInteger hookFired =
new java.util.concurrent.atomic.AtomicInteger();
java.util.function.Consumer<Session> afterLocationRead =
ignored -> {
hookFired.incrementAndGet();
try (Session other = realFactory.openSession()) {
other.beginTransaction();
other
.createMutationQuery("UPDATE ExternalLocationDAO SET endpoint = 'http://b.example'")
.executeUpdate();
other
.createMutationQuery(
"UPDATE CredentialDAO SET credential = '{\"access_key_id\":\"new\"}'")
.executeUpdate();
other.getTransaction().commit();
}
};
SessionFactory hooked =
(SessionFactory)
java.lang.reflect.Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] {SessionFactory.class},
(p, m, a) -> {
try {
Object result = m.invoke(realFactory, a);
if (!m.getName().equals("openSession")) {
return result;
}
Session real = (Session) result;
return java.lang.reflect.Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] {Session.class},
(sp, sm, sa) -> {
try {
if (sm.getName().equals("get")
&& sa != null
&& sa[0]
== io.unitycatalog.server.persist.dao.CredentialDAO.class) {
afterLocationRead.accept(real);
}
return sm.invoke(real, sa);
} catch (java.lang.reflect.InvocationTargetException e) {
throw e.getCause();
}
});
} catch (java.lang.reflect.InvocationTargetException e) {
throw e.getCause();
}
});
ExternalLocationUtils.LocationCredential lc =
new ExternalLocationUtils(hooked)
.getExternalLocationCredentialForPath(NormalizedURL.from("s3://bucket/a/data"))
.orElseThrow();
assertThat(hookFired.get()).as("hook fired").isEqualTo(1);
assertThat(
List.of(
lc.location().getEndpoint(),
lc.credential().getS3CompatibleAccessKeyResponse().getAccessKeyId()))
.isIn(List.of("http://a.example", "old"), List.of("http://b.example", "new"));
}
Checked by 2 independent checks: CONFIRMED
References:
- https://www.postgresql.org/docs/18/transaction-iso.html#XACT-READ-COMMITTED: "Also note that two successive SELECT commands can see different data, even though they are within a single transaction, if other transactions commit changes after the first SELECT starts and before the second SELECT starts."
Could the lookup read the location and credential from one database snapshot?
| Optional.empty(), | ||
| "Changing the endpoint or path_style_access of external location '" + name + "'"); | ||
| } else { | ||
| ExternalLocationUtils.validateExternalLocationNotInUse( |
There was a problem hiding this comment.
Blocker, low probability: An endpoint change can redirect a newly registered volume without force
The update locks the location row, but volume registration does not take that lock. The in-use query can pass just before registration, so a live volume moves without force.
Details
For example: A PATCH finds no volume under s3://in-use-bucket/root. Before it commits, an external volume at root/volume commits and can be read at the old endpoint. The pending PATCH then redirects it. This is one bug class: An external location's not-in-use check is a read with no lock that registrations under the location never conflict with, so a storage user created after the check survives the guarded change. The same issue appears in server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:356 (An unforced URL change that no longer covers the old URL has the same check-then-act gap.); server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:497 (An unforced delete reads the location without a row lock (getExternalLocationDAO, not ForUpdate), checks that it is not in use, and removes it.); server/src/main/java/io/unitycatalog/server/persist/VolumeRepository.java:43 (Registers an external volume's storage_location without reading or locking the covering external location, so it never conflicts with the location's FOR UPDATE.); server/src/main/java/io/unitycatalog/server/persist/TableRepository.java:895 (An external table's storage_location is checked only against managed storage (validateNotOverlapWithManagedStorage), with no lock on the covering location.); server/src/main/java/io/unitycatalog/server/persist/CatalogRepository.java:62.
Make every registration of a resource under a location path (external volumes, tables, models) take a shared lock on the covering external-location row, so the PATCH's FOR UPDATE conflicts with it. Do this for the new endpoint and path-style change and for the existing URL change. Use one lock order and add a test that forces the interleaving.
Evidence:
The PATCH locks the location row, queries its current users, then writes the new endpoint. VolumeService authorizes the covering location before calling VolumeRepository. The volume transaction checks the path and inserts a volume with a storage-location string, without taking the covering location lock. The existing test commits the volume before starting the PATCH, which covers the sequential case.
server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:301-309
return TransactionManager.executeWithTransaction(
sessionFactory,
session -> {
// The location, then its credential, are locked on their first read in this session.
ExternalLocationDAO existingLocation = getExternalLocationDAOForUpdate(session, name);
if (existingLocation == null) {
throw new BaseException(ErrorCode.NOT_FOUND, "External location not found: " + name);
}
String storedUrl = existingLocation.getUrl();
server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:364-381
if (changesS3CompatibleSettings(
existingLocation, endpoint, updateExternalLocation.getPathStyleAccess())) {
if (Boolean.TRUE.equals(updateExternalLocation.getForce())) {
warnIfInUse(
session,
storedUrl,
Optional.empty(),
"Changing the endpoint or path_style_access of external location '" + name + "'");
} else {
ExternalLocationUtils.validateExternalLocationNotInUse(
session, storedUrlToCheckOrRefuse(storedUrl, name));
}
}
if (endpoint != null) {
existingLocation.setEndpoint(endpoint);
}
if (updateExternalLocation.getPathStyleAccess() != null) {
existingLocation.setPathStyleAccess(updateExternalLocation.getPathStyleAccess());
server/src/main/java/io/unitycatalog/server/persist/utils/ExternalLocationUtils.java:646-660
public static void validateExternalLocationNotInUse(Session session, NormalizedURL url) {
LocationUse use = findLocationUse(session, url);
if (use.pendingCleanup()) {
throw new BaseException(
ErrorCode.FAILED_PRECONDITION,
"Input path overlaps pending storage cleanup. " + FORCE_HINT);
}
use.storageUser()
.ifPresent(
user -> {
throw new BaseException(
ErrorCode.INVALID_ARGUMENT,
"External location still used by " + user + ". " + FORCE_HINT);
});
}
server/src/main/java/io/unitycatalog/server/service/VolumeService.java:90-104
(#volume_type != 'EXTERNAL' ||
(#no_overlap_with_data_securable &&
(#external_location == null ||
#authorizeAny(#principal, #external_location, OWNER, CREATE_EXTERNAL_VOLUME))))
""")
public HttpResponse createVolume(
@AuthorizeResourceKeys({
@AuthorizeResourceKey(value = SCHEMA, key = "schema_name"),
@AuthorizeResourceKey(value = CATALOG, key = "catalog_name"),
@AuthorizeResourceKey(value = EXTERNAL_LOCATION, key = "storage_location")
})
@AuthorizeKey(key = "volume_type")
CreateVolumeRequestContent createVolumeRequest) {
// Throw error if catalog/schema does not exist
VolumeInfo volumeInfo = volumeRepository.createVolume(createVolumeRequest);
server/src/main/java/io/unitycatalog/server/persist/VolumeRepository.java:74-85
// EXTERNAL volume.
if (createVolumeRequest.getStorageLocation() == null) {
throw new BaseException(
ErrorCode.INVALID_ARGUMENT, "Storage location is required for external volume");
}
storageLocation = NormalizedURL.from(createVolumeRequest.getStorageLocation());
ValidationUtils.checkArgument(
!storageLocation.isCloudStorageRoot(),
"External volume storage location must include a non-empty path prefix: %s",
createVolumeRequest.getStorageLocation());
ExternalLocationUtils.validateNotOverlapWithManagedStorage(session, storageLocation);
}
How it was checked:
Reproduced: dev/run-tests.py -p 1 'server/testOnly *SdkExternalLocationCRUDTest' (H2 default; UC_TEST_DATABASE=POSTGRES_18 and UC_TEST_DATABASE=MYSQL_8 for the others)
head:
[error] Test io.unitycatalog.server.sdk.externallocation.SdkExternalLocationCRUDTest.testEndpointPatchCannotMissVolumeRegisteredBeforeCommit failed: java.lang.AssertionError: [PATCH committed endpoint http://storage-moved.invalid:9000 while volume at the old endpoint exists] Expecting actual not to be null (BaseExternalLocationCRUDTest.java:660)
[error] Failed: Total 19, Failed 1, Errors 0, Passed 18 (identical on H2, POSTGRES_18, MYSQL_8)
server/src/test/java/io/unitycatalog/server/base/externallocation/BaseExternalLocationCRUDTest.java:599-665
/**
* An external volume registered after the endpoint change's in-use check passes, but before the
* change commits, must not leave both operations succeeding without force.
*/
@Test
public void testEndpointPatchCannotMissVolumeRegisteredBeforeCommit() throws ApiException {
String endpoint = "http://storage.invalid:9000";
String movedEndpoint = "http://storage-moved.invalid:9000";
String root = "s3://race-bucket/root";
createCompatCredential(COMPAT_CREDENTIAL_NAME);
createLocation("el_race", root, COMPAT_CREDENTIAL_NAME, endpoint, true);
io.unitycatalog.server.persist.ExternalLocationRepository repository =
new io.unitycatalog.server.persist.Repositories(
hibernateConfigurator.getSessionFactory(),
new io.unitycatalog.server.utils.ServerProperties(new java.util.Properties()))
.getExternalLocationRepository();
boolean[] volumeCreated = {false};
Throwable patchFailure = null;
try (org.mockito.MockedStatic<io.unitycatalog.server.persist.utils.ExternalLocationUtils>
utils =
org.mockito.Mockito.mockStatic(
io.unitycatalog.server.persist.utils.ExternalLocationUtils.class,
org.mockito.Mockito.CALLS_REAL_METHODS)) {
utils
.when(
() ->
io.unitycatalog.server.persist.utils.ExternalLocationUtils
.validateExternalLocationNotInUse(
org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()))
.thenAnswer(
invocation -> {
// The real check passes: no volume exists yet. Then a volume registers.
invocation.callRealMethod();
volumeOperations.createVolume(
new CreateVolumeRequestContent()
.name(VOLUME_NAME)
.catalogName(CATALOG_NAME)
.schemaName(SCHEMA_NAME)
.volumeType(VolumeType.EXTERNAL)
.storageLocation(root + "/volume"));
volumeCreated[0] = true;
return null;
});
try (com.linecorp.armeria.common.util.SafeCloseable ignored =
com.linecorp.armeria.server.ServiceRequestContext.of(
com.linecorp.armeria.common.HttpRequest.of(
com.linecorp.armeria.common.HttpMethod.PATCH, "/"))
.push()) {
repository.updateExternalLocation(
"el_race",
new io.unitycatalog.server.model.UpdateExternalLocation().endpoint(movedEndpoint));
} catch (Throwable t) {
patchFailure = t;
}
}
assertThat(volumeCreated[0]).as("hook ran; PATCH threw: %s", patchFailure).isTrue();
// The volume and the endpoint move cannot both commit without force.
assertThat(patchFailure)
.as(
"PATCH committed endpoint %s while volume at the old endpoint exists",
externalLocationOperations.getExternalLocation("el_race").getEndpoint())
.isNotNull();
externalLocationOperations.updateExternalLocation(
"el_race", new UpdateExternalLocation().force(true));
volumeOperations.deleteVolume(CATALOG_NAME + "." + SCHEMA_NAME + "." + VOLUME_NAME);
credentialOperations.deleteCredential(COMPAT_CREDENTIAL_NAME, Optional.of(true));
}
Checked by 2 independent checks, which split: CONFIRMED, CONTESTED
References:
- https://www.postgresql.org/docs/18/transaction-iso.html#XACT-READ-COMMITTED: "In effect, a SELECT query sees a snapshot of the database as of the instant the query begins to run."
Could registration and endpoint changes synchronize on the covering location?
There was a problem hiding this comment.
Agreed, but this check-then-act race isn't specific to endpoint changes: a URL change and a location delete run the same in-use check, and a volume or table registered concurrently doesn't take the location's lock either. So it needs one fix covering all three, for example having registration take a shared lock on the covering location. I'd rather do that as a follow-up than fix one of the three here.
| // vended with the endpoint rather than discovered here. | ||
| config.put(S3FileIOProperties.ENDPOINT, s3Compatible.get().getEndpoint()); | ||
| config.put( | ||
| S3FileIOProperties.PATH_STYLE_ACCESS, |
There was a problem hiding this comment.
Should fix, low probability: Iceberg credential renewal succeeds with obsolete routing settings
Iceberg sets the addressing style when it builds the S3 client. Its credential provider refreshes keys and expiry, so a successful refresh can leave the client using the old route.
Details
For example: A table loads with s3.path-style-access=true. After a forced switch to false, its refresh gets a new session, but subsequent requests still put the bucket in the path. This is one bug class: The Iceberg credential refresh is not bound to the routing a table was loaded with, while the Hadoop connector's refresh is. The same issue appears in server/src/main/java/io/unitycatalog/server/service/IcebergRestCatalogService.java:417 (The refresh endpoint (advertised through REFRESH_CREDENTIALS_ENDPOINT in FileOperationsImpl.getS3Config:250) vends keys for the current endpoint and path style.).
Include the endpoint and path style the table was loaded with in the Iceberg refresh request, and reject a refresh whose binding is out of date with an error that tells the client to reload the table. Failing that, document that after a forced endpoint or path-style change, Iceberg clients must reload tables.
Evidence:
FileOperationsImpl returns the location's current addressing style alongside a refresh URL for STS sessions. Both initial table load and refresh use a URL identified solely by table name. I checked both handlers and the pinned Iceberg provider. Neither handler receives the routing settings from the original load, and the provider extracts session keys and expiry from the response without rebuilding the S3 client.
server/src/main/java/io/unitycatalog/server/persist/utils/FileOperationsImpl.java:227-237
if (s3Compatible.isPresent()) {
// S3-compatible storage: the bucket is not on AWS, so its region and addressing style are
// vended with the endpoint rather than discovered here.
config.put(S3FileIOProperties.ENDPOINT, s3Compatible.get().getEndpoint());
config.put(
S3FileIOProperties.PATH_STYLE_ACCESS,
String.valueOf(Boolean.TRUE.equals(s3Compatible.get().getPathStyleAccess())));
config.put(
AwsClientProperties.CLIENT_REGION,
Optional.ofNullable(s3Compatible.get().getRegion())
.orElse(S3BucketRegions.DEFAULT_S3_COMPATIBLE_REGION));
server/src/main/java/io/unitycatalog/server/persist/utils/FileOperationsImpl.java:244-252
if (awsCredentials.getSessionToken() != null) {
if (expirationTime != null) {
// Without this, an Iceberg client cannot tell when the session it was handed dies, so it
// neither renews ahead of the expiry nor treats the credential as expiring at all.
config.put(S3FileIOProperties.SESSION_TOKEN_EXPIRES_AT_MS, Long.toString(expirationTime));
}
credentialsEndpoint.ifPresent(
endpoint -> config.put(AwsClientProperties.REFRESH_CREDENTIALS_ENDPOINT, endpoint));
}
server/src/main/java/io/unitycatalog/server/service/IcebergRestCatalogService.java:401-414
Map<String, String> config =
credentialPrivileges.isEmpty()
? Map.of()
: tableConfigService.getTableConfig(
tableLocation,
credentialPrivileges,
credentialsEndpoint(catalog, namespace, table));
return HttpResult.of(
ResponseHeaders.builder(HttpStatus.OK)
.contentType(MediaType.JSON)
.add(HttpHeaderNames.ETAG, etag)
.build(),
LoadTableResponse.builder().withTableMetadata(tableMetadata).addAllConfig(config).build());
server/src/main/java/io/unitycatalog/server/service/IcebergRestCatalogService.java:435-447
NormalizedURL tableLocation = NormalizedURL.from(state.storageLocation());
Map<String, String> config =
tableConfigService.getTableConfig(
tableLocation, credentialPrivileges, credentialsEndpoint(catalog, namespace, table));
if (config.isEmpty()) {
// A local (file://) table vends nothing. The response is a list, so answer an empty one:
// Iceberg's own Credential type rejects an empty config.
return ImmutableLoadCredentialsResponse.builder().build();
}
return ImmutableLoadCredentialsResponse.builder()
.addCredentials(
ImmutableCredential.builder().prefix(tableLocation.toString()).config(config).build())
.build();
server/src/main/java/io/unitycatalog/server/service/IcebergRestCatalogService.java:456-460
private static String credentialsEndpoint(String catalog, String namespace, String table) {
return "v1/%s%s/namespaces/%s/tables/%s/credentials"
.formatted(
PREFIX_BASE, catalog, RESTUtil.encodeString(namespace), RESTUtil.encodeString(table));
}
How it was checked:
Reproduced: dev/run-tests.py -p 1 'server/testOnly *FileOperationsTest'
head:
1 suites, 39 tests, 1 failed. io.unitycatalog.server.utils.FileOperationsTest#testIcebergRefreshCannotSucceedWithObsoletePathStyle(): org.opentest4j.AssertionFailedError: expected: "bucket.storage.example" but was: "storage.example" (FileOperationsTest.java:903)
server/src/test/java/io/unitycatalog/server/utils/FileOperationsTest.java:822-907
@SneakyThrows
@Test
public void testIcebergRefreshCannotSucceedWithObsoletePathStyle() {
// The refresh endpoint answers with new keys, as after a forced switch to virtual hosting.
com.sun.net.httpserver.HttpServer http =
com.sun.net.httpserver.HttpServer.create(new java.net.InetSocketAddress("localhost", 0), 0);
http.createContext(
"/",
ex -> {
byte[] body =
("{\"storage-credentials\":[{\"prefix\":\"s3\",\"config\":{"
+ "\"s3.access-key-id\":\"NEWKEY\",\"s3.secret-access-key\":\"newsecret\","
+ "\"s3.session-token\":\"newtoken\",\"s3.session-token-expires-at-ms\":\""
+ (System.currentTimeMillis() + 3_600_000L)
+ "\"}}]}")
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json");
ex.sendResponseHeaders(200, body.length);
ex.getResponseBody().write(body);
ex.close();
});
http.start();
try {
String base = "http://localhost:" + http.getAddress().getPort();
StorageCredentialVendor vendor = mock(StorageCredentialVendor.class);
when(vendor.vendCredential(any(), any(), any()))
.thenReturn(
new TemporaryCredentials()
.awsTempCredentials(
new AwsCredentials()
.accessKeyId("OLDKEY")
.secretAccessKey("oldsecret")
.sessionToken("oldtoken"))
.externalLocationSettings(
new ExternalLocationSettings()
.s3Compatible(
new S3CompatibleSettings()
.endpoint("http://storage.example")
.region("eu-test-1")
.pathStyleAccess(true)))
// Already expired, so the client refreshes at its first request.
.expirationTime(System.currentTimeMillis() - 1000L));
FileOperations fileOps =
new FileOperationsImpl(
vendor, new ServerProperties(new Properties()), mock(Supplier.class));
Map<String, String> config =
new java.util.HashMap<>(
fileOps.getFileIOConfig(
NormalizedURL.from("s3://bucket/table"),
CredentialContext.READ_ONLY,
Optional.of("/credentials")));
assertThat(config).containsEntry(S3FileIOProperties.PATH_STYLE_ACCESS, "true");
config.put("uri", base);
config.put(AwsClientProperties.REFRESH_CREDENTIALS_ENDPOINT, "/credentials");
// The server now requires virtual hosting; the loaded client's settings are unchanged.
java.util.concurrent.atomic.AtomicReference<java.net.URI> sent =
new java.util.concurrent.atomic.AtomicReference<>();
S3ClientBuilder builder = S3Client.builder();
new S3FileIOProperties(config).applyServiceConfigurations(builder);
new S3FileIOProperties(config)
.applyCredentialConfigurations(new AwsClientProperties(config), builder);
new S3FileIOProperties(config).applyEndpointConfigurations(builder);
new AwsClientProperties(config).applyClientRegionConfiguration(builder);
builder.overrideConfiguration(
c ->
c.addExecutionInterceptor(
new software.amazon.awssdk.core.interceptor.ExecutionInterceptor() {
@Override
public void beforeTransmission(
software.amazon.awssdk.core.interceptor.Context.BeforeTransmission ctx,
software.amazon.awssdk.core.interceptor.ExecutionAttributes attrs) {
sent.set(ctx.httpRequest().getUri());
throw new IllegalStateException("stop before transmission");
}
}));
try (S3Client client = builder.build()) {
assertThatThrownBy(() -> client.headObject(r -> r.bucket("bucket").key("table/f")))
.hasMessageContaining("stop before transmission");
}
// The refresh succeeded (new keys fetched), and the request must now be virtual-hosted.
assertThat(sent.get().getHost()).isEqualTo("bucket.storage.example");
} finally {
http.stop(0);
}
}
Checked by 2 independent checks, which split: CONFIRMED, CONTESTED
References:
- https://github.com/apache/iceberg/blob/apache-iceberg-1.11.0/aws/src/main/java/org/apache/iceberg/aws/s3/S3FileIOProperties.java#L1009-L1017: ".pathStyleAccessEnabled(isPathStyleAccess)"
- https://github.com/apache/iceberg/blob/apache-iceberg-1.11.0/aws/src/main/java/org/apache/iceberg/aws/s3/VendedCredentialsProvider.java#L171-L189: "AwsSessionCredentials.builder()
.accessKeyId(accessKeyId)
.secretAccessKey(secretAccessKey)
.sessionToken(sessionToken)
.expirationTime(expiresAt)"
Could refresh detect a routing change and require the Iceberg client to reload the table?
There was a problem hiding this comment.
Agreed that a refresh can't change the routing an Iceberg S3 client was built with. Fixing it needs the refresh bound to the routing the table was loaded with, so a refresh after a forced path-style switch fails and the client reloads the table, much like the Hadoop connector's renewal check. That touches the Iceberg credential refresh flow, so I'd like to do it as a follow-up. Until then, a forced path-style switch takes effect for Iceberg clients on their next table load.
| // The region to sign requests to that S3 endpoint with, set together with s3Endpoint. | ||
| @Builder.Default private final Optional<String> s3Region = Optional.empty(); | ||
| // Whether requests to that S3 endpoint are path-style, set together with s3Endpoint. | ||
| @Builder.Default private final Optional<Boolean> s3PathStyleAccess = Optional.empty(); |
There was a problem hiding this comment.
Nit, high probability: S3-compatible vend settings travel as separate Optionals that nothing keeps together
CredentialContext now holds s3Endpoint, s3Region and s3PathStyleAccess as separate Optionals that are only "set together" by a comment. The vend cache Key copies all three.
Each reader handles the half-set case its own way: orElseThrow() in StorageCredentialVendorImpl, orElse(false) in CloudCredentialVendor, orElseThrow() and a default region in AwsCredentialVendor.
Details
Cost of keeping it: The next layer of the stack adds a fourth one, externalLocationId, with the same comment. That means another positional Optional.empty() in CredentialContext.create, another field in Key, and another reader that picks its own default. The follow-up settings for s3, adls and gcs would keep widening every one of these signatures.
// one value, built once after the region lookup
record S3CompatibleStorage(String endpoint, String region, boolean isPathStyleAccess) {}
@Builder.Default private final Optional<S3CompatibleStorage> s3Compatible = Optional.empty();
Evidence:
CredentialContext declares three independent Optionals tied only by the comment 'set together with s3Endpoint'. Readers handle a half-set state differently: orElseThrow in StorageCredentialVendorImpl and AwsCredentialVendor, orElse(false)/orElse(null) in CloudCredentialVendor. The cache Key copies the three fields one by one. The stacked layer #2395 (git diff e3673bf..2fc9f41) adds externalLocationId to CredentialContext with the same comment and one more positional Optional.empty() in create.
server/src/main/java/io/unitycatalog/server/service/credential/CredentialContext.java:44-49
// The S3 endpoint of the external location for this path, set for S3-compatible storage.
@Builder.Default private final Optional<String> s3Endpoint = Optional.empty();
// The region to sign requests to that S3 endpoint with, set together with s3Endpoint.
@Builder.Default private final Optional<String> s3Region = Optional.empty();
// Whether requests to that S3 endpoint are path-style, set together with s3Endpoint.
@Builder.Default private final Optional<Boolean> s3PathStyleAccess = Optional.empty();
server/src/main/java/io/unitycatalog/server/service/credential/StorageCredentialVendorImpl.java:89-104
Optional<String> s3Endpoint = s3CompatibleLocation.map(StorageCredentialVendorImpl::s3Endpoint);
Optional<Boolean> s3PathStyleAccess =
s3CompatibleLocation.map(ExternalLocationDAO::getS3PathStyleAccess);
CredentialContext credentialContext =
CredentialContext.create(
path,
privileges,
credentialDAO,
s3Endpoint,
// Requests to S3-compatible storage are signed with the region it reports, which is
// part of the vend cache key, so a region reported later selects its own entry.
s3Endpoint.map(
endpoint ->
s3BucketRegions.getS3CompatibleRegion(
endpoint, path.toUri().getAuthority(), s3PathStyleAccess.orElseThrow())),
s3PathStyleAccess,
server/src/main/java/io/unitycatalog/server/service/credential/CloudCredentialVendor.java:102-113
private static ExternalLocationSettings s3CompatibleSettings(CredentialContext context) {
return context
.getS3Endpoint()
.map(
endpoint ->
new ExternalLocationSettings()
.s3Compatible(
new S3CompatibleSettings()
.endpoint(endpoint)
.region(context.getS3Region().orElse(null))
.pathStyleAccess(context.getS3PathStyleAccess().orElse(false))))
.orElse(null);
server/src/main/java/io/unitycatalog/server/service/credential/aws/AwsCredentialVendor.java:227-234
String stsEndpoint =
s3Compatible.getStsEndpoint() != null
? s3Compatible.getStsEndpoint()
: context.getS3Endpoint().orElseThrow();
StsClientKey key =
new StsClientKey(
stsEndpoint,
context.getS3Region().orElse(S3BucketRegions.DEFAULT_S3_COMPATIBLE_REGION));
server/src/main/java/io/unitycatalog/server/service/credential/CachingCloudCredentialVendor.java:152-156
Optional<CredentialVersion> s3CompatibleVersion,
Optional<String> s3Endpoint,
Optional<String> s3Region,
Optional<Boolean> s3PathStyleAccess,
boolean isServerAccess) {
How it was checked:
Checked by 1 independent check: NITPICK
Could the three fields (and the location id in the next PR) become one record, so the cache key and the vend mapping each read a single value?
There was a problem hiding this comment.
Fair point. Folding the endpoint, region and path style into one small value type would touch CredentialContext, the cache key, the vendors and the Hadoop AwsCredential, so I'd rather do it as a separate refactor than grow this PR. The readers do agree today: the three are set together from the location in StorageCredentialVendorImpl.
| example `https://minio.example.com:9000`: `http[s]://host[:port]`, of at most 2048 | ||
| characters, and without a path (not even a trailing `/`), user info, a query or a fragment; | ||
| other values fail with `INVALID_ARGUMENT`. Stored, returned and vended with the scheme and | ||
| host in lowercase. Set exactly when the location's credential is `s3_compatible_access_key`. |
There was a problem hiding this comment.
Nit, medium probability: An orphaned location keeps its endpoint
The field description ties endpoint presence to the current credential. An endpoint can survive its credential, as the PATCH repair contract already explains.
Details
For example: Force-deleting the credential leaves credential_name absent while the location retains endpoint. Assigning another compatible credential repairs vending at that same endpoint. This is one bug class: Contract prose added by this change states rules without conditions, but the code has supported exceptions to them (force-delete, browse-only, pending cleanup, settings-only vend, cache key). The same issue appears in server/src/main/java/io/unitycatalog/server/persist/CredentialRepository.java:289 (The Javadoc repeats 'a location has an endpoint exactly when its credential is s3_compatible_access_key', the same invariant that force-delete breaks.); server/src/main/java/io/unitycatalog/server/persist/dao/ExternalLocationDAO.java:50 (The field comment says the endpoint is 'set exactly when the credential is s3_compatible_access_key', which an orphaned location contradicts.); api/all.yaml:3197; api/all.yaml:1541; docs/server/configuration.md:144; server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:135 (The Javadoc says regions are cached per 'S3 endpoint and bucket' and that 'one lookup runs per bucket at a time'.); api/all.yaml:1256 ('The credential holds no endpoint' contradicts the optional sts_endpoint described two lines below.).
Describe endpoint presence in terms of S3-compatible storage kind and keep the credential-type requirement for creation and reassignment.
Evidence:
The endpoint field ties its presence to the current credential. The PATCH contract explicitly retains the storage kind after credential deletion. Existing endpoint and style are returned by the DAO independently of credential name, and the SDK repair test confirms the original endpoint survives deletion and repair.
api/all.yaml:3182-3188
S3 API endpoint of the S3-compatible storage the external location is on, for
example `https://minio.example.com:9000`: `http[s]://host[:port]`, of at most 2048
characters, and without a path (not even a trailing `/`), user info, a query or a fragment;
other values fail with `INVALID_ARGUMENT`. Stored, returned and vended with the scheme and
host in lowercase. Set exactly when the location's credential is `s3_compatible_access_key`.
Credential vending returns it in `external_location_settings`, with the region and
addressing style engines need to reach the storage.
api/all.yaml:1535-1541
A location whose credential is `s3_compatible_access_key` must have an `s3://`
URL and an `endpoint`; a location with another credential must not have an `endpoint`. An
update without `endpoint` keeps the stored one. A location keeps its storage kind, even after
its credential was force-deleted: one with an `endpoint` can only get an
`s3_compatible_access_key` credential, and one without can get neither an `endpoint` nor
such a credential. To move a location to other storage, delete it and create a new one. An
update that breaks any of these rules fails with `INVALID_ARGUMENT`.
server/src/main/java/io/unitycatalog/server/persist/dao/ExternalLocationDAO.java:86-90
.id(getId() != null ? getId().toString() : null)
.credentialId(getCredentialId() != null ? getCredentialId().toString() : null)
.credentialName(credentialName)
.endpoint(getEndpoint())
.pathStyleAccess(getS3PathStyleAccess())
server/src/test/java/io/unitycatalog/server/sdk/externallocation/SdkExternalLocationCRUDTest.java:103-115
String path = "s3://orphan-bucket/a/t";
createCompatCredential(COMPAT_CREDENTIAL_NAME);
createLocation("el_s3", "s3://orphan-bucket/a", COMPAT_CREDENTIAL_NAME, endpoint);
credentialOperations.deleteCredential(COMPAT_CREDENTIAL_NAME, Optional.of(true));
TestUtils.assertApiException(
() -> vended(path),
ErrorCode.INTERNAL,
"The storage credential for '" + path + "' no longer exists");
createCompatCredential(ANOTHER_COMPAT_CREDENTIAL_NAME);
externalLocationOperations.updateExternalLocation(
"el_s3", new UpdateExternalLocation().credentialName(ANOTHER_COMPAT_CREDENTIAL_NAME));
assertThat(vendedS3Endpoint(path)).isEqualTo(endpoint);
How it was checked:
Reproduced: dev/run-tests.py -p 1 'server/testOnly *SdkExternalLocationCRUDTest'
head:
[error] Test io.unitycatalog.server.sdk.externallocation.SdkExternalLocationCRUDTest.testDocumentedEndpointRequiresExistingCompatibleCredential failed: org.opentest4j.AssertionFailedError: expected: null but was: "http://storage.invalid:9000" (SdkExternalLocationCRUDTest.java:129). Total 19, Failed 1, Passed 18
server/src/test/java/io/unitycatalog/server/sdk/externallocation/SdkExternalLocationCRUDTest.java:119-130
/** The API text says the endpoint is set exactly when the credential is s3_compatible. */
@Test
public void testDocumentedEndpointRequiresExistingCompatibleCredential() throws ApiException {
String endpoint = "http://storage.invalid:9000";
createCompatCredential(COMPAT_CREDENTIAL_NAME);
createLocation("el_doc", "s3://doc-bucket/a", COMPAT_CREDENTIAL_NAME, endpoint);
credentialOperations.deleteCredential(COMPAT_CREDENTIAL_NAME, Optional.of(true));
io.unitycatalog.client.model.ExternalLocationInfo info =
externalLocationOperations.getExternalLocation("el_doc");
assertThat(info.getCredentialName()).isNull();
assertThat(info.getEndpoint()).isNull();
}
Checked by 1 independent check: CONFIRMED
Could the field description use the location's storage kind and mention what survives force-delete?
| host in lowercase. Set exactly when the location's credential is `s3_compatible_access_key`. | ||
| Credential vending returns it in `external_location_settings`, with the region and | ||
| addressing style engines need to reach the storage. | ||
| type: string |
There was a problem hiding this comment.
Nit, medium probability: The request schema accepts values the server rejects
The length and prefix checks live in prose or Java. Schema-based clients cannot validate these requests before sending them.
Details
For example: An empty access_key_id, a role_arn without arn:, or an endpoint longer than 2048 characters can pass the field schema and then receive INVALID_ARGUMENT.
Add maxLength: 2048 to the location endpoint, minLength: 1 to both request keys and an anchored arn: pattern to the role ARN.
Evidence:
The new schema gives the access-key fields, role ARN and location endpoint plain string types. The server checks nonempty keys, the ARN prefix and the endpoint length. The latter two restrictions appear in prose, so a schema validator and the server accept different input sets.
api/all.yaml:3131-3145
type: object
required:
- access_key_id
- secret_access_key
properties:
access_key_id:
description: The access key ID.
type: string
secret_access_key:
description: The secret access key. Write-only; never returned.
type: string
sts_endpoint:
$ref: "#/components/schemas/S3CompatibleStsEndpoint"
role_arn:
$ref: "#/components/schemas/S3CompatibleRoleArn"
api/all.yaml:3170-3189
S3CompatibleRoleArn:
description: |
The ARN of the role to assume, for example `arn:aws:iam:::role/uc-tables`;
storage that ignores the role, such as MinIO, still needs an ARN-shaped value. Unity
Catalog sends it unchanged as AssumeRole's `RoleArn`; a value that does not start with
`arn:` fails with `INVALID_ARGUMENT`. When set, the key pair signs AssumeRole on the
storage's STS, and Unity Catalog vends the resulting short-lived credentials scoped to the
requested path and privilege. AssumeRole is signed with the region the server detects for
the requested path's bucket.
type: string
S3CompatibleEndpoint:
description: |
S3 API endpoint of the S3-compatible storage the external location is on, for
example `https://minio.example.com:9000`: `http[s]://host[:port]`, of at most 2048
characters, and without a path (not even a trailing `/`), user info, a query or a fragment;
other values fail with `INVALID_ARGUMENT`. Stored, returned and vended with the scheme and
host in lowercase. Set exactly when the location's credential is `s3_compatible_access_key`.
Credential vending returns it in `external_location_settings`, with the region and
addressing style engines need to reach the storage.
type: string
server/src/main/java/io/unitycatalog/server/persist/dao/CredentialDAO.java:230-245
private static void validateS3CompatibleAccessKey(S3CompatibleAccessKeyRequest accessKey) {
ValidationUtils.checkArgument(
accessKey.getAccessKeyId() != null && !accessKey.getAccessKeyId().isEmpty(),
"s3_compatible_access_key.access_key_id is required.");
ValidationUtils.checkArgument(
accessKey.getSecretAccessKey() != null && !accessKey.getSecretAccessKey().isEmpty(),
"s3_compatible_access_key.secret_access_key is required.");
// role_arn turns STS on, and sts_endpoint only says where it is.
// Sent unchanged as AssumeRole's RoleArn.
ValidationUtils.checkArgument(
accessKey.getRoleArn() == null || accessKey.getRoleArn().startsWith("arn:"),
"s3_compatible_access_key.role_arn must be the ARN of the role to assume, such as"
+ " arn:aws:iam:::role/uc-tables.");
ValidationUtils.checkArgument(
accessKey.getStsEndpoint() == null || accessKey.getRoleArn() != null,
"s3_compatible_access_key.sts_endpoint is allowed only with role_arn.");
server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:133-142
private static String normalizeEndpoint(String endpoint) {
if (endpoint == null) {
return null;
}
ValidationUtils.checkArgument(
endpoint.length() <= ExternalLocationDAO.MAX_ENDPOINT_LENGTH,
"Invalid endpoint: must be at most %s characters.",
ExternalLocationDAO.MAX_ENDPOINT_LENGTH);
return ValidationUtils.normalizeHttpUrl(endpoint, "endpoint");
}
How it was checked:
Checked by 1 independent check: NITPICK
References:
- https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/3.0.0.md#schema-object: "- maxLength
- minLength
- pattern (This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect)"
Could we encode the existing server checks in the new string schemas?
| * | ||
| * @param s3Endpoint the storage's S3 endpoint | ||
| * @param bucket the bucket name | ||
| * @param isPathStyleAccess whether requests to {@code s3Endpoint} are path-style |
There was a problem hiding this comment.
Nit, medium probability: Opposite addressing styles can start independent region lookups
The method describes one lookup per bucket. Lookup coalescing also depends on addressing style, and the endpoint now comes from the external location.
Details
For example: The same endpoint and bucket with path_style_access=true and false create different StorageBucket values. Each can own an in-flight lookup and cache a different region.
Describe caching and coalescing per endpoint, bucket and addressing style, and update the endpoint-source comment.
Evidence:
The region-cache comment still identifies the credential API as the endpoint source, and the public method describes cache and in-flight lookup scope per endpoint and bucket. StorageCredentialVendorImpl now gets the endpoint from the location, and both cache and in-flight lookups use a key that includes addressing style.
server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:49-62
private final Supplier<S3ClientBuilder> s3ClientBuilderSupplier;
// Endpoints come from the credential API and buckets from request paths, so the caches are
// bounded. A reported region is asked again after REPORTED_REGION_TTL, so that a region fixed at
// the storage, or an endpoint moved to other storage, is picked up without a restart; it stays in
// use while that request fails.
static final Duration REPORTED_REGION_TTL = Duration.ofHours(1);
private static final int MAX_BUCKETS = 10_000;
private final Cache<StorageBucket, Reported> reportedRegions;
// Until when, in epoch milliseconds, a bucket without a reported region gets the default.
private final Cache<StorageBucket, Long> retryAfterMs;
private final Map<StorageBucket, CompletableFuture<String>> lookups = new ConcurrentHashMap<>();
private final LongSupplier currentTimeMillis;
private record StorageBucket(String s3Endpoint, String bucket, boolean isPathStyleAccess) {}
server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:134-146
/**
* The region of a bucket on S3-compatible storage. A region the storage reports is cached per S3
* endpoint and bucket, and asked again after {@link #REPORTED_REGION_TTL}. Otherwise the default
* region is used. After a failed request or a transient error, the last reported region, or the
* default, is used and the storage is asked again after {@link #FAILURE_RETRY_DELAY}; a missing
* bucket (which may be created later) does the same with the default. After an answer without a
* region, the default is used for {@link #NO_REGION_RECHECK_DELAY}. One lookup runs per bucket at
* a time.
*
* @param s3Endpoint the storage's S3 endpoint
* @param bucket the bucket name
* @param isPathStyleAccess whether requests to {@code s3Endpoint} are path-style
* @return the reported region, otherwise {@link #DEFAULT_S3_COMPATIBLE_REGION}
server/src/main/java/io/unitycatalog/server/service/credential/aws/S3BucketRegions.java:148-156
public String getS3CompatibleRegion(String s3Endpoint, String bucket, boolean isPathStyleAccess) {
StorageBucket storageBucket = new StorageBucket(s3Endpoint, bucket, isPathStyleAccess);
Optional<String> known = knownRegion(storageBucket);
if (known.isPresent()) {
return known.get();
}
CompletableFuture<String> lookup = new CompletableFuture<>();
CompletableFuture<String> running = lookups.putIfAbsent(storageBucket, lookup);
if (running != null) {
server/src/main/java/io/unitycatalog/server/service/credential/StorageCredentialVendorImpl.java:85-104
Optional<ExternalLocationDAO> s3CompatibleLocation =
locationCredential
.filter(found -> found.credential().getCredentialType() == CredentialType.S3_COMPATIBLE)
.map(LocationCredential::location);
Optional<String> s3Endpoint = s3CompatibleLocation.map(StorageCredentialVendorImpl::s3Endpoint);
Optional<Boolean> s3PathStyleAccess =
s3CompatibleLocation.map(ExternalLocationDAO::getS3PathStyleAccess);
CredentialContext credentialContext =
CredentialContext.create(
path,
privileges,
credentialDAO,
s3Endpoint,
// Requests to S3-compatible storage are signed with the region it reports, which is
// part of the vend cache key, so a region reported later selects its own entry.
s3Endpoint.map(
endpoint ->
s3BucketRegions.getS3CompatibleRegion(
endpoint, path.toUri().getAuthority(), s3PathStyleAccess.orElseThrow())),
s3PathStyleAccess,
How it was checked:
Checked by 1 independent check: CONFIRMED
Could we name all three key fields and update where the endpoint comes from?
| endpoint -> | ||
| s3BucketRegions.getS3CompatibleRegion(endpoint, path.toUri().getAuthority())), | ||
| s3BucketRegions.getS3CompatibleRegion( | ||
| endpoint, path.toUri().getAuthority(), s3PathStyleAccess.orElseThrow())), |
There was a problem hiding this comment.
Nit, medium probability: A regression to path-style region lookups for virtual-hosted locations would pass every test
StorageCredentialVendorImpl now passes the location's style to getS3CompatibleRegion, but no test checks that argument.
With it hard-coded to true, CloudCredentialVendorTest and SdkExternalLocationCRUDTest still pass (34 of 34).
Details
For example: The vendor test stubs getS3CompatibleRegion(any(), any(), anyBoolean()) and never verifies the style. The SDK test's .invalid endpoints fail discovery under either style, so they fall back to the default region whatever the argument is.
// CloudCredentialVendorTest, after vendCredential(COMPAT_PATH, READ_ONLY):
verify(s3BucketRegions).getS3CompatibleRegion(S3_ENDPOINT, "compat-bucket", false);
// and with a location built with .pathStyleAccess(true):
verify(s3BucketRegions).getS3CompatibleRegion(S3_ENDPOINT, "compat-bucket", true);
Evidence:
The vend passes the location's style to region discovery (lines 102-103). The only vendor-test stub accepts any boolean (test lines 105-107), and the SDK vend test uses unreachable .invalid endpoints (lines 69-75), so the lookup falls back to the default region under either style. I also checked S3BucketRegionsTest (unit-level only), S3CompatibleCredentialVendingTest (real storage, path style true only) and S3CompatibleCredentialScopeTest (path style true). A mutation hard-coding true passed 34 of 34 tests.
server/src/main/java/io/unitycatalog/server/service/credential/StorageCredentialVendorImpl.java:86-105
locationCredential
.filter(found -> found.credential().getCredentialType() == CredentialType.S3_COMPATIBLE)
.map(LocationCredential::location);
Optional<String> s3Endpoint = s3CompatibleLocation.map(StorageCredentialVendorImpl::s3Endpoint);
Optional<Boolean> s3PathStyleAccess =
s3CompatibleLocation.map(ExternalLocationDAO::getS3PathStyleAccess);
CredentialContext credentialContext =
CredentialContext.create(
path,
privileges,
credentialDAO,
s3Endpoint,
// Requests to S3-compatible storage are signed with the region it reports, which is
// part of the vend cache key, so a region reported later selects its own entry.
s3Endpoint.map(
endpoint ->
s3BucketRegions.getS3CompatibleRegion(
endpoint, path.toUri().getAuthority(), s3PathStyleAccess.orElseThrow())),
s3PathStyleAccess,
/* isServerAccess= */ isServerAccess(use.getPurpose()));
server/src/test/java/io/unitycatalog/server/service/credential/CloudCredentialVendorTest.java:105-107
lenient()
.when(s3BucketRegions.getS3CompatibleRegion(any(), any(), anyBoolean()))
.thenReturn(DISCOVERED_REGION);
server/src/test/java/io/unitycatalog/server/sdk/externallocation/SdkExternalLocationCRUDTest.java:68-96
public void testPathsReachTheStorageOfTheirLocation() throws ApiException {
String endpointA = "http://storage-a.invalid:9000";
String endpointB = "http://storage-b.invalid:9000";
createCompatCredential(COMPAT_CREDENTIAL_NAME);
createLocation("el_a", "s3://shared-bucket/a", COMPAT_CREDENTIAL_NAME, endpointA);
createLocation("el_b", "s3://shared-bucket/b", COMPAT_CREDENTIAL_NAME, endpointB);
assertThat(vendedS3Endpoint("s3://shared-bucket/a/t")).isEqualTo(endpointA);
assertThat(vendedS3Endpoint("s3://shared-bucket/b/t")).isEqualTo(endpointB);
// Updating the location's endpoint moves every path under it, for example to the storage's new
// host name, vended as stored, with its scheme and host in lowercase.
String movedEndpoint = "http://storage-a-moved.invalid:9000";
externalLocationOperations.updateExternalLocation(
"el_a", new UpdateExternalLocation().endpoint("HTTP://Storage-A-Moved.invalid:9000"));
assertThat(vendedS3Endpoint("s3://shared-bucket/a/t")).isEqualTo(movedEndpoint);
assertThat(vendedS3Endpoint("s3://shared-bucket/b/t")).isEqualTo(endpointB);
// The path style is vended with the endpoint, and an update of it reaches the vend. Its
// credential vends no keys, so the vend carries only the location's settings.
assertThat(vended("s3://shared-bucket/b/t").getAwsTempCredentials()).isNull();
assertThat(vended("s3://shared-bucket/b/t").getExternalLocationSettings().getS3Compatible())
.returns(false, S3CompatibleSettings::getPathStyleAccess)
.returns(S3BucketRegions.DEFAULT_S3_COMPATIBLE_REGION, S3CompatibleSettings::getRegion);
externalLocationOperations.updateExternalLocation(
"el_b", new UpdateExternalLocation().pathStyleAccess(true));
assertThat(vended("s3://shared-bucket/b/t").getExternalLocationSettings().getS3Compatible())
.returns(true, S3CompatibleSettings::getPathStyleAccess);
assertThat(vended("s3://shared-bucket/a/t").getExternalLocationSettings().getS3Compatible())
.returns(false, S3CompatibleSettings::getPathStyleAccess);
How it was checked:
Checked by 1 independent check: CONFIRMED
Would a verify on the existing vend tests, one for each style, cover this?
| ExternalLocationDAO location, String endpoint, Boolean pathStyleAccess) { | ||
| return (endpoint != null && !endpoint.equals(location.getEndpoint())) | ||
| || (pathStyleAccess != null | ||
| && pathStyleAccess != Boolean.TRUE.equals(location.getPathStyleAccess())); |
There was a problem hiding this comment.
Nit, medium probability: Resending the returned path_style_access: false to an in-use location could start failing unnoticed
A location created without path_style_access stores null, but GET returns false. changesS3CompatibleSettings treats the two as equal, so resending false is not a change.
No test covers this. With a plain equals, the suite still passes (18 of 18).
Details
For example: With !pathStyleAccess.equals(location.getPathStyleAccess()), a client that reads an in-use location and PATCHes back path_style_access: false gets External location still used by .... No test notices.
createLocation("el_default", "s3://default-bucket/root", COMPAT_CREDENTIAL_NAME, endpoint);
// ... create a volume under it ...
assertThat(externalLocationOperations.getExternalLocation("el_default").getPathStyleAccess()).isFalse();
assertThat(
externalLocationOperations.updateExternalLocation(
"el_default", new UpdateExternalLocation().pathStyleAccess(false)))
.returns(false, ExternalLocationInfo::getPathStyleAccess);
Evidence:
The change check maps a stored null to false (line 435). The in-use test creates el_used with path_style_access true (lines 541-545) and resends only true (lines 569-576), so the null-stored case never runs. I also checked testS3CompatiblePathStyleAccess (el_hosted is not in use) and testS3CompatibleLocations. A mutation to a plain equals passed 18 of 18 tests.
server/src/main/java/io/unitycatalog/server/persist/ExternalLocationRepository.java:431-436
private static boolean changesS3CompatibleSettings(
ExternalLocationDAO location, String endpoint, Boolean pathStyleAccess) {
return (endpoint != null && !endpoint.equals(location.getEndpoint()))
|| (pathStyleAccess != null
&& pathStyleAccess != Boolean.TRUE.equals(location.getPathStyleAccess()));
}
server/src/test/java/io/unitycatalog/server/base/externallocation/BaseExternalLocationCRUDTest.java:541-576
assertThat(
createLocation(
"el_used", root, COMPAT_CREDENTIAL_NAME, "HTTP://Storage.INVALID:9000", true)
.getEndpoint())
.isEqualTo(endpoint);
createLocation("el_free", "s3://free-bucket/root", COMPAT_CREDENTIAL_NAME, endpoint, true);
VolumeInfo volume =
volumeOperations.createVolume(
new CreateVolumeRequestContent()
.name(VOLUME_NAME)
.catalogName(CATALOG_NAME)
.schemaName(SCHEMA_NAME)
.volumeType(VolumeType.EXTERNAL)
.storageLocation(root + "/volume"));
for (UpdateExternalLocation update :
List.of(
new UpdateExternalLocation().endpoint(movedEndpoint),
new UpdateExternalLocation().pathStyleAccess(false).force(false))) {
assertApiException(
() -> externalLocationOperations.updateExternalLocation("el_used", update),
ErrorCode.INVALID_ARGUMENT,
"External location still used by volume '"
+ volume.getVolumeId()
+ "'. Set force to true to skip this check.");
}
// Resending the stored values, even in another case, is not a change, and a location not in
// use may change.
for (String sameEndpoint : List.of(endpoint, "http://STORAGE.invalid:9000")) {
assertThat(
externalLocationOperations.updateExternalLocation(
"el_used",
new UpdateExternalLocation().endpoint(sameEndpoint).pathStyleAccess(true)))
.returns(endpoint, ExternalLocationInfo::getEndpoint)
.returns(true, ExternalLocationInfo::getPathStyleAccess);
}
How it was checked:
Checked by 1 independent check: CONFIRMED
Could testS3CompatibleSettingsChangeWhileInUse take this case beside its resend loop?
tdas
left a comment
There was a problem hiding this comment.
lgtm to yaml changes. glad this is not experimental any more
e3673bf to
176eed4
Compare
|
/review |
176eed4 to
a33b7c0
Compare
|
/review |
… on the external location - S3-compatible storage is no longer experimental: the labels are gone, and the property `server.s3-compatible-storage.enabled` is removed with its guards; `server.credential-encryption-key` is read whenever it is set - `CreateExternalLocation`, `UpdateExternalLocation` and `ExternalLocationInfo` get `endpoint` (at most 2048 characters) and `path_style_access`; the credential no longer has `s3_endpoint` - The credential field `s3_compatible` is now `s3_compatible_access_key`: keys plus flat `sts_endpoint` and `role_arn` (`S3AssumeRole` and `sts_region` removed) - `TemporaryCredentials.external_location_settings` carries `s3_compatible` (`endpoint`, `region`, `path_style_access`); `AwsCredentials` carries only keys - Location rules: - an `endpoint` exactly with an `s3_compatible_access_key` credential; an update without it keeps it - `path_style_access` missing or false is virtual-hosted, which needs a bucket name that is a host name label - changing `endpoint` or `path_style_access` of a location in use needs `force`, as a URL change does - a location keeps its storage kind, decided by its stored `endpoint`, also after its credential was force-deleted - a location whose credential was force-deleted still checks its endpoint, URL and bucket name - A credential in use cannot switch between `s3_compatible_access_key` and another type - STS is on with `role_arn`, sent unchanged as AssumeRole's `RoleArn`; without `sts_endpoint` it goes to the location's endpoint, signed with the detected region - Schema steps `V20__external_location_endpoint` (`varchar(2048)`) and `V21__external_location_path_style_access` - Hadoop connector and CLI read the location's settings; the connector sets `path.style.access` per bucket and refuses a renewal that changes it - CLI: `--endpoint` and `--path_style_access` on external locations; docs, `ManagedDeltaTablesSpec.md`, Helm, the Helm CI install case and tests updated Signed-off-by: Yi Li <[email protected]> Co-authored-by: Isaac <[email protected]>
- Store an external location's `endpoint` and a credential's `sts_endpoint` with the scheme and host in lowercase - normalized once, by `ValidationUtils.normalizeHttpUrl`, when a create or update stores them - a case-only `endpoint` edit is no change, so it needs no `force` on a location in use - API text: - `sts_endpoint` in `createCredential` states the `http[s]://host[:port]` form without a path - `UpdateExternalLocation.path_style_access` gets its own description: the stored `endpoint` counts, and leaving it out keeps the stored value - `updateExternalLocation` says which rules fail with `INVALID_ARGUMENT` - Comments say clients get the location's settings (endpoint, region, path style), and badly wrapped comments are re-wrapped, including `helm/values.yaml` and the regenerated `helm/README.md` Signed-off-by: Yi Li <[email protected]> Co-authored-by: Isaac <[email protected]>
…nd address review notes - `ExternalLocationUtils.getExternalLocationCredentialForPath` reads the location and its credential in one snapshot transaction - `TransactionManager.snapshotIsolation`: REPEATABLE READ on PostgreSQL and MySQL, SERIALIZABLE on H2 - a test commits a credential change between the two reads and expects the old credential - A virtual-hosted location is stored as `false`, so `path_style_access` is null exactly without an `endpoint` - `api/all.yaml`: - schema limits: `maxLength: 2048` on the endpoint, `minLength: 1` on the keys, `pattern: '^arn:'` on `role_arn` - wording: which endpoint is vended and which the server calls for STS, `FAILED_PRECONDITION` for a pending cleanup, an endpoint kept after a force-deleted credential, `browse_only` responses - `ui/src/types/api/catalog.gen.ts` regenerated from `api/all.yaml` - `docs/usage/cli.md` documents `--endpoint`, `--path_style_access` and what `--force` covers - The encryption key docs say an `endpoint-only` client vend reads no secret - `S3BucketRegions` docs name the endpoint, bucket and addressing style - Tests: the region lookup gets the location's addressing style, and resending the returned `path_style_access: false` to a location in use is no change Signed-off-by: Yi Li <[email protected]> Co-authored-by: Isaac <[email protected]>
a33b7c0 to
279e421
Compare
|
/review |
|
On the note in the review about |
|
@tdas @timothyw553 since your approvals, three things changed that you may want to look at:
|
|
sure, I can take a look at it again. |
timothyw553
left a comment
There was a problem hiding this comment.
just left one small nit on the cli docs, overall looks good.
| 3. `credential_name`: The name of the credential to be associated with. | ||
| 4. `endpoint`: _\[Optional\]_ The S3 API endpoint of the S3-compatible storage the location is on, as | ||
| `http[s]://host[:port]` without a path, for example `https://minio.example.com:9000`. Required with an | ||
| `s3_compatible_access_key` credential, and refused with any other. |
There was a problem hiding this comment.
nit: we mention s3_compatible_access_key here, but the credential section above doesn't show how to create one. could we add a cli example for creating it with the key and optional role/sts flags?
Picks up unitycatalog#2289, which moves the S3-compatible endpoint from the credential to the external location and removes server.s3-compatible-storage.enabled. Signed-off-by: Scott Haines <[email protected]> Co-authored-by: Isaac <[email protected]>
unitycatalog#2289 moved the S3-compatible endpoint from the credential to the external location, renamed the credential type s3_compatible_access_key, and removed server.s3-compatible-storage.enabled. On main, storage-init's credential create with --s3_endpoint printed the CLI's help and stopped the stack; the storage-init test caught it on the PR's merge with main. - storage-init registers the credential with only the keys and the role, and the location with --endpoint http://rustfs:9000 and --path_style_access true: a virtual-hosted address such as uc-warehouse.rustfs doesn't resolve on the Compose network. - config-init no longer writes the removed property. - The tests, the README and the Compose comment follow. Signed-off-by: Scott Haines <[email protected]> Co-authored-by: Isaac <[email protected]>
🥞 Stacked PR
Use this link to review incremental changes.
Finalizes S3-compatible storage, which the stack #2170 to #2175 and #2169 (all merged) built.
Description of changes
Why. The S3 endpoint belongs to the storage a location is on, not to the key pair that reaches it. With the endpoint on the credential, one credential could not serve locations on several storage hosts, and moving a bucket to a new host meant editing the credential. This PR moves the endpoint, and whether its requests are path-style, to the external location. The vend returns the location's settings beside the keys, so a client always gets the endpoint, region and addressing style that match the keys it signs with. It also takes the feature out of experimental status.
API (
api/all.yaml,api/delta.yaml, regeneratedapi/docs)Storage credential and external location:
{"name": "aistor_cred", "purpose": "STORAGE", "s3_compatible_access_key": {"access_key_id": "uc-user", "secret_access_key": "...", "sts_endpoint": "https://sts.example.com", "role_arn": "arn:aws:iam:::role/uc-tables"}} {"name": "aistor_loc", "url": "s3://sales/tables", "credential_name": "aistor_cred", "endpoint": "https://aistor.example.com", "path_style_access": true}Vended credentials (
TemporaryCredentials):{"aws_temp_credentials": {"access_key_id": "...", "secret_access_key": "...", "session_token": "..."}, "expiration_time": 1764200000000, "external_location_settings": { "s3_compatible": {"endpoint": "https://aistor.example.com", "region": "us-east-1", "path_style_access": true}}}s3_compatibleis renameds3_compatible_access_key(S3CompatibleAccessKeyRequest/Response). It holds the keys plus the optional flat STS fieldssts_endpointandrole_arn.s3_endpoint, the nestedassume_role(S3AssumeRole) andsts_regionare removed.CreateExternalLocation,UpdateExternalLocationandExternalLocationInfogetendpoint(http[s]://host[:port], at most 2048 characters, without a path) andpath_style_access(boolean).UpdateExternalLocation.path_style_accesshas its own description: it needs a storedendpoint, and leaving it out keeps the stored value.endpointand a credential'ssts_endpointare stored, returned and vended with the scheme and host in lowercase. Thests_endpointtext states the samehttp[s]://host[:port]form, andupdateExternalLocationsays which rules fail withINVALID_ARGUMENT.maxLength: 2048on the endpoint,minLength: 1on the keys, andpattern: '^arn:'onrole_arn. Vended credentials carry the location'sendpoint; a credential'ssts_endpointis only where the server calls STS, and is never vended.ui/src/types/api/catalog.gen.tsis regenerated fromapi/all.yaml, which also picks up earlier spec changes it was missing (browse_only,include_browse, the requiredpurpose).TemporaryCredentialsgetsexternal_location_settings(ExternalLocationSettings), set exactly when the path is on S3-compatible storage. It hass3_compatible(endpoint,region,path_style_access).AwsCredentialscarries only keys again:s3_endpointands3_regionare removed. An endpoint-only vend returns the settings andexpiration_timewithoutaws_temp_credentials.configkey map carriess3.endpoint,client.regionands3.path-style-access, the same keys the Iceberg REST config uses.spec/protocols/ManagedDeltaTablesSpec.mdmatchesapi/delta.yaml: the config carriess3.endpoint,client.regionand the booleans3.path-style-access, so its values are strings or a boolean, and a false or absents3.path-style-accessmeans virtual-hosted.Rules
endpoint, and may havepath_style_access, exactly when it is on S3-compatible storage: required with ans3_compatible_access_keycredential, refused with another, and kept after its credential is force-deleted. An update that leaves either out keeps the stored value.path_style_accessmeans virtual-hosted. Then the bucket name must be a host name label: 3 to 63 lowercase letters, digits and hyphens, a letter or digit at both ends, and no dots, since a dot breaks wildcard TLS certificates. Create and update refuse other names and name the bucket.ExternalLocationInfoalways returnspath_style_accesswhen the location has anendpoint.role_arnis set. It holds the ARN of the role to assume, for examplearn:aws:iam:::role/uc-tables, sent unchanged as AssumeRole'sRoleArn; a value that doesn't start witharn:is refused. Storage that ignores the role, such as MinIO, still needs an ARN-shaped value.sts_endpointis allowed only withrole_arn. Without it, AssumeRole goes to the location's endpoint, signed with the bucket region the server detects.endpointdecides, also after its credential was force-deleted. A location with an endpoint can only get anothers3_compatible_access_keycredential; one without can get neither an endpoint, norpath_style_access, nor such a credential. Moving a location to other storage means deleting it and creating a new one, so an update can't clearendpointorpath_style_access. A credential's type can't change while a location uses it; new keys or a new role can.endpointorpath_style_accessof a location in use is refused unlessforceis set, with the same in-use check as a URL change. Resending the stored value isn't a change, and neither is anendpointthat differs only in the case of its scheme or host.s3://URL, and the bucket rule for virtual-hosted addressing. Vending under it fails until it is repaired.Server
V20__external_location_endpoint(nullablevarchar(2048)) andV21__external_location_path_style_access(nullable boolean,biton MySQL), with their effect files. A virtual-hosted location storesfalse, so the column is null exactly without an endpoint.ExternalLocationUtils.getExternalLocationCredentialForPathreturns the location together with its credential, read from one snapshot (TransactionManager.snapshotIsolation: REPEATABLE READ on PostgreSQL and MySQL, SERIALIZABLE on H2), so a vend never pairs a location with a credential from another committed state. A location of ans3_compatible_access_keycredential without an endpoint fails the vend withINTERNAL, so keys are never sent to AWS S3 by mistake.CredentialContextand the vend cache key intoexternal_location_settings; theendpoint-onlyclient response, built after the cache inStorageCredentialVendorImpl, carries the same settings; the Iceberg REST config (s3.endpoint,client.region,s3.path-style-access) and the Delta config. Region discovery addresses the bucket as the location says.server.s3-compatible-storage.enabledis removed, with every guard that read it. The encryption keyserver.credential-encryption-keyis now read whenever it's set: a malformed key refuses startup. Without a key, creating or updating ans3_compatible_access_keysecret fails withFAILED_PRECONDITION, while stored credentials stay readable, renamable and deletable.server.s3-compatible-storage.static-key-vendingis unchanged.Clients
external_location_settings.s3_compatible. Settings that are absent mean AWS S3, and a missingpath_style_accessmeans virtual-hosted. It setsfs.s3a.bucket.<bucket>.path.style.access, records the style per bucket and in the file system cache id, and renewal refuses a changed style just as it refuses a changed endpoint.credential create/update:--s3_endpointand--s3_sts_regionare removed, and--s3_role_arnsetsrole_arn.external_location create/update: new--endpointand--path_style_access.docs/usage/cli.mddocuments--endpointand--path_style_accessonexternal_location create/update, and that--forcealso covers an endpoint or path-style change on a location in use.etc/conf/server.propertiesuse the new names and no longer mention the enable property. The chart needs onlyserver.credentialEncryptionKeySecret, and the Helm CI install case passes only the key Secret.Tests
force), locations whose credential was force-deleted, andpath_style_accessdefaults, updates and the bucket-name rule.endpointandsts_endpointvalues on create and update are stored, returned and vended lowercased, and a case-onlyendpointedit on a location in use needs noforce.forcePathStyle(true)andforcePathStyle(false), cached apart.role_arnandsts_endpointvalidation.FileSystemCredId.create(Configuration)) differs by endpoint, region and path style.pathStyle.key of the cache id is removed.127.0.0.1ports, so its locations setpath_style_access: true. Virtual-hosted addressing isn't run against real storage.Follow-ups:
external_location_idinExternalLocationSettings(#2395, stacked on this PR);ExternalLocationSettingsentries for other storage types:s3(withregion),adlsandgcs.Compatibility. S3-compatible storage hasn't been released, so these API, property and CLI changes need no compatibility shim, and no data is migrated. Credentials, locations and vends for other storage are unchanged.
Tests run on the final head, rebased onto main with #2268, #1928 and #2394:
io.unitycatalog.server.migrate.*withUC_TEST_MIGRATION_CHECKS=trueon H2, PostgreSQL 18 and MySQL 8: 241 tests each.dev/run-tests.py, full suite on H2: 4,085 tests.UC_TEST_STORAGE=MINIO): the S3-compatible, external location and credential tests plusspark/test, 576 tests.helm/README.mdregenerated with helm-docs v1.14.2.yarn test:formatpasses inui/, andtsc --noEmitreports no errors outsidenode_modules, as before.On an earlier head, before the endpoint length limit: the S3-compatible tests plus
spark/teston Garage (555). All pass.PR Checklist
docsis updatedThis pull request and its description were written by Isaac.