Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions etc/conf/server.properties
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,18 @@ aws.region=
# Default: false (disabled)
# server.s3-compatible-storage.enabled=false

# What clients receive for an s3_compatible storage credential without assume_role, that is, for
# S3-compatible storage without STS. Credentials with assume_role always vend scoped short-lived
# sessions and ignore this setting.
# endpoint-only (default): the S3 endpoint and region, but no keys. The server uses the key
# pair for its own storage access; engines must bring their own keys.
# static-key: the key pair itself. Its one-hour lifetime only makes engines fetch it again and
# pick up an updated key; the key itself stays valid until the storage rotates or revokes it.
# Iceberg clients get no lifetime and keep it until they load the table again. It is not
# narrowed to the requested table or path, so any client that can read a table can use it for
# everything the key reaches, including writes for a client allowed only to read.
server.s3-compatible-storage.static-key-vending=endpoint-only

# The key that the secret_access_key of s3_compatible storage credentials is encrypted with in the
# database (AES-256-GCM): 32 random bytes in base64, such as the output of `openssl rand -base64 32`.
# Required to create or use such credentials. Set it in the UC_SERVER_CREDENTIAL_ENCRYPTION_KEY
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ public class UnityCatalogServer implements AutoCloseable {
/** Set during {@link #initializeServer}; may be null if construction fails early. */
private StorageCleanupWorker cleanupWorker;

// The cloud credential vendor the repositories built, if not injected; closed with the server.
private CloudCredentialVendor cloudCredentialVendor;

/**
* Metrics registry owned by this server instance; set during {@link #initializeServer}. Closed on
* shutdown to release the JVM/GC metric listeners it binds (may be null if construction fails
Expand Down Expand Up @@ -142,6 +145,7 @@ private UnityCatalogServer(UnityCatalogServer.Builder unityCatalogServerBuilder)
closeQuietly(authorizer instanceof AutoCloseable c ? c : null, t, "the authorizer");
closeBlockingTaskExecutor(createdBlockingTaskExecutor, shutdownTimeout, t);
closeQuietly(auditor, t, "the audit sink");
closeQuietly(cloudCredentialVendor, t, "the cloud credential vendor");
closeOwnedSessionFactory(t);
throw t;
}
Expand Down Expand Up @@ -265,10 +269,18 @@ private Server initializeServer(UnityCatalogServer.Builder unityCatalogServerBui
unityCatalogServerBuilder.fileOperationsDecorator,
domainMetrics,
audit);
cloudCredentialVendor = repositories.getOwnedCloudCredentialVendor().orElse(null);
// Init metastore
repositories.getMetastoreRepository().initMetastoreIfNeeded();
if (unityCatalogServerBuilder.serverProperties.isS3CompatibleStorageEnabled()) {
warnAboutUnreadableSecrets(repositories);
if (unityCatalogServerBuilder.serverProperties.getS3CompatibleStaticKeyVending()
== ServerProperties.S3CompatibleStaticKeyVending.STATIC_KEY) {
LOGGER.warn(
"{}=static-key: clients get the key pair of s3_compatible credentials without"
+ " assume_role, which is not scoped to the requested path or privilege",
ServerProperties.Property.S3_COMPATIBLE_STATIC_KEY_VENDING.getKey());
}
}
// Init authorizer
authorizer =
Expand Down Expand Up @@ -580,6 +592,7 @@ public void close() {
closeQuietly(cleanupWorker, null, "the storage cleanup worker");
closeQuietly(authorizer instanceof AutoCloseable c ? c : null, null, "the authorizer");
closeQuietly(auditor, null, "the audit sink");
closeQuietly(cloudCredentialVendor, null, "the cloud credential vendor");
closeQuietly(
ownsHibernateConfigurator ? hibernateConfigurator : null, null, "the database pool");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ public class Repositories {
private final SessionFactory sessionFactory;
private final ExternalLocationUtils externalLocationUtils;
private final StorageCredentialVendor storageCredentialVendor;
// The vendor built here rather than injected, which the owner of this object closes.
private final Optional<CloudCredentialVendor> ownedCloudCredentialVendor;
private final FileOperations fileOperations;

private final CatalogRepository catalogRepository;
Expand Down Expand Up @@ -107,14 +109,17 @@ public Repositories(
Objects.requireNonNullElseGet(metrics, UnityCatalogMetrics::noop);
this.sessionFactory = sessionFactory;
this.externalLocationUtils = new ExternalLocationUtils(sessionFactory);
CloudCredentialVendor resolvedCloudCredentialVendor =
this.ownedCloudCredentialVendor =
cloudCredentialVendor != null
? cloudCredentialVendor
: defaultCloudCredentialVendor(serverProperties, resolvedMetrics);
? Optional.empty()
: Optional.of(defaultCloudCredentialVendor(serverProperties, resolvedMetrics));
CloudCredentialVendor resolvedCloudCredentialVendor =
ownedCloudCredentialVendor.orElse(cloudCredentialVendor);
// Wrap the vendor before FileOperationsImpl captures it, so the server's own and cleanup vends
// are audited too.
StorageCredentialVendor vendor =
new StorageCredentialVendorImpl(resolvedCloudCredentialVendor, externalLocationUtils);
new StorageCredentialVendorImpl(
resolvedCloudCredentialVendor, externalLocationUtils, serverProperties);
this.storageCredentialVendor = auditor.map(a -> a.wrap(vendor)).orElse(vendor);
this.fileOperations =
fileOperationsDecorator.apply(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@
import jakarta.persistence.Enumerated;
import jakarta.persistence.Lob;
import jakarta.persistence.Table;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HexFormat;
import java.util.Optional;
import java.util.UUID;
import lombok.AccessLevel;
Expand Down Expand Up @@ -295,6 +299,21 @@ public String getS3SecretAccessKey(CredentialSecretStore secretStore) {
return secretStore.load(stored.asText(), getS3SecretAccessKeyContext());
}

/**
* @return a fingerprint of the stored credential: any change of its payload changes it, while
* changes of other fields, such as the comment, keep it
*/
public String getCredentialFingerprint() {
try {
return HexFormat.of()
.formatHex(
MessageDigest.getInstance("SHA-256")
.digest(credential.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}

/** What the {@code secret_access_key} belongs to, for its store. */
public SecretContext getS3SecretAccessKeyContext() {
return new SecretContext(getId(), getName(), SECRET_ACCESS_KEY_FIELD);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import io.unitycatalog.server.service.credential.CredentialContext;
import io.unitycatalog.server.service.credential.CredentialUse;
import io.unitycatalog.server.service.credential.StorageCredentialVendor;
import io.unitycatalog.server.service.credential.aws.S3BucketRegions;
import io.unitycatalog.server.service.credential.azure.ADLSLocationUtils;
import io.unitycatalog.server.utils.CooperativeDeadline;
import io.unitycatalog.server.utils.NormalizedURL;
Expand All @@ -33,20 +34,16 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3ClientBuilder;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

/** Default {@link FileOperations}: builds credential-vended Iceberg {@link FileIO}s. */
public class FileOperationsImpl implements FileOperations {

private static final Logger LOGGER = LoggerFactory.getLogger(FileOperationsImpl.class);
// S3 returns the bucket's region in this response header, including on 301/403 error responses.
private static final String BUCKET_REGION_HEADER = "x-amz-bucket-region";

private final StorageCredentialVendor storageCredentialVendor;
// Per-bucket S3 region: seeded from the configured s3.region.N, then filled by HeadBucket
Expand Down Expand Up @@ -209,29 +206,54 @@ private Map<String, String> getS3Config(
AwsCredentials awsCredentials,
Long expirationTime,
Optional<String> credentialsEndpoint) {
// Use the configured region if present, otherwise discover it and cache it per bucket.
Map<String, String> config = new HashMap<>();
// Keys are absent when the path's credential vends only the S3 endpoint, and the session token
// is absent for a static key pair.
Optional.ofNullable(awsCredentials.getAccessKeyId())
.ifPresent(v -> config.put(S3FileIOProperties.ACCESS_KEY_ID, v));
Optional.ofNullable(awsCredentials.getSecretAccessKey())
.ifPresent(v -> config.put(S3FileIOProperties.SECRET_ACCESS_KEY, v));
Optional.ofNullable(awsCredentials.getSessionToken())
.ifPresent(v -> config.put(S3FileIOProperties.SESSION_TOKEN, v));
if (awsCredentials.getS3Endpoint() != null) {
// S3-compatible storage: the bucket is not on AWS, so its region is vended with the endpoint
// rather than discovered here. These stores commonly cannot serve virtual-hosted bucket
// names, so use path-style access.
config.put(S3FileIOProperties.ENDPOINT, awsCredentials.getS3Endpoint());
config.put(S3FileIOProperties.PATH_STYLE_ACCESS, "true");
config.put(
AwsClientProperties.CLIENT_REGION,
Optional.ofNullable(awsCredentials.getS3Region())
.orElse(S3BucketRegions.DEFAULT_S3_COMPATIBLE_REGION));
} else {
config.put(AwsClientProperties.CLIENT_REGION, getRegion(path.getStorageBase()));
}
// Iceberg's refreshing credentials provider requires a session token, so a vended key pair goes
// without its lifetime and the refresh endpoint, and an Iceberg client keeps it until the table
// is loaded again.
if (awsCredentials.getSessionToken() != null) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

could an iceberg reload keep returning 304 after we rotate the keys or change the endpoint? the etag only covers metadata and permissions, and these modes have no credential refresh endpoint. should we include the credential version and storage settings in the etag, or bypass 304 for these responses, with a regression test? fine to track this as a follow-up.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good point. Agreed to take this as a follow-up: I will open a separate PR to cover the credential version and storage settings in the ETag (or skip 304 for these responses), with a regression test.

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));
}
return Map.copyOf(config);
}

/** The configured region of an AWS bucket, otherwise its discovered region cached per bucket. */
private String getRegion(NormalizedURL storageBase) {
// Discovery runs outside any map lock (get + putIfAbsent rather than computeIfAbsent): a bucket
// whose discovery fails is never cached and so is re-probed on every request, and holding the
// bin lock across HeadBucket would serialize those probes and pile request threads up on it.
NormalizedURL storageBase = path.getStorageBase();
String s3Region = s3BucketRegionMap.get(storageBase);
if (s3Region == null) {
s3Region = discoverRegion(storageBase);
s3BucketRegionMap.putIfAbsent(storageBase, s3Region);
}
Map<String, String> config = new HashMap<>();
config.put(S3FileIOProperties.ACCESS_KEY_ID, awsCredentials.getAccessKeyId());
config.put(S3FileIOProperties.SECRET_ACCESS_KEY, awsCredentials.getSecretAccessKey());
config.put(S3FileIOProperties.SESSION_TOKEN, awsCredentials.getSessionToken());
config.put(AwsClientProperties.CLIENT_REGION, s3Region);
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));
return Map.copyOf(config);
return s3Region;
}

/**
Expand All @@ -252,20 +274,12 @@ private String discoverRegion(NormalizedURL storageBase) {
.credentialsProvider(AnonymousCredentialsProvider.create())
.region(Region.US_EAST_1)
.build()) {
String region =
s3Client.headBucket(HeadBucketRequest.builder().bucket(bucket).build()).bucketRegion();
if (region != null) {
return region;
}
throw permanentRegionError(storageBase, null);
return S3BucketRegions.headBucketRegion(s3Client, bucket)
.orElseThrow(() -> permanentRegionError(storageBase, null));
} catch (S3Exception e) {
String region = bucketRegionHeader(e);
if (region != null) {
return region;
}
// A 5xx, throttling, or 408 request-timeout response is transient; any other definitive 4xx
// without the region header (e.g. no such bucket) means the region cannot be determined.
if (e.statusCode() >= 500 || e.statusCode() == 408 || e.isThrottlingException()) {
if (S3BucketRegions.isTransient(e)) {
throw transientRegionError(storageBase, e);
}
throw permanentRegionError(storageBase, e);
Expand All @@ -275,15 +289,6 @@ private String discoverRegion(NormalizedURL storageBase) {
}
}

/** The {@code x-amz-bucket-region} header from an error response, or null if it is absent. */
private static String bucketRegionHeader(S3Exception e) {
AwsErrorDetails details = e.awsErrorDetails();
if (details == null || details.sdkHttpResponse() == null) {
return null;
}
return details.sdkHttpResponse().firstMatchingHeader(BUCKET_REGION_HEADER).orElse(null);
}

private static BaseException permanentRegionError(NormalizedURL storageBase, Throwable cause) {
// The cause is not surfaced to the caller, so log the underlying S3 error for diagnosis.
LOGGER.warn(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import io.unitycatalog.server.observability.StorageCredentialCacheMetrics;
import io.unitycatalog.server.observability.UnityCatalogMetrics;
import io.unitycatalog.server.persist.dao.CredentialDAO;
import io.unitycatalog.server.persist.dao.CredentialDAO.CredentialType;
import io.unitycatalog.server.service.credential.aws.AwsCredentialVendor;
import io.unitycatalog.server.service.credential.azure.AzureCredentialVendor;
import io.unitycatalog.server.service.credential.gcp.GcpCredentialVendor;
Expand All @@ -21,6 +22,7 @@
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import lombok.SneakyThrows;

Expand All @@ -31,10 +33,12 @@
* binding before calling it, so only the cloud vend is skipped; the binding is re-read on every
* request.
*
* <p>An entry is keyed by {@code (locations, privileges, roleArn, externalId)}. It is served until
* {@code min(vendTime + maxAge, credentialExpiry - expiryMargin)}, where {@code vendTime} is read
* before the cloud call; a static credential with no expiry is bounded by the max age alone.
* Callers always receive a copy, so they cannot change a cached credential.
* <p>An entry is keyed by {@code (locations, privileges, roleArn, externalId)}, plus, for
* S3-compatible storage, the storage credential's version, its S3 endpoint and region, and whether
* the server or a client uses it. It is served until {@code min(vendTime + maxAge, credentialExpiry
* - expiryMargin)}, where {@code vendTime} is read before the cloud call; a static credential with
* no expiry is bounded by the max age alone. Callers always receive a copy, so they cannot change a
* cached credential.
*
* <p>Each request is recorded as a hit or a miss in {@link StorageCredentialCacheMetrics}.
*/
Expand Down Expand Up @@ -130,32 +134,57 @@ private long now() {

/**
* The resolved credential binding. Changing the role or external ID of a location's credential
* changes the key, so credentials cached under the previous binding are never reused.
* changes the key, so credentials cached under the previous binding are never reused. An {@code
* s3_compatible} credential is identified by the fingerprint of its stored payload instead, which
* every change of its key pair, endpoint or role changes. Server and client vends of such a
* credential can differ: without {@code assume_role}, the server gets the key pair without an
* expiration, and clients get only the endpoint ({@code endpoint-only}) or the key pair with a
* refetch time ({@code static-key}). So for every {@code s3_compatible} credential they never
* share an entry; {@code server.s3-compatible-storage.static-key-vending} is read once at
* startup, so entries never span two modes.
*/
private record Key(
List<NormalizedURL> locations,
Set<CredentialContext.Privilege> privileges,
String roleArn,
String externalId) {
String externalId,
Optional<CredentialVersion> s3CompatibleVersion,
Optional<String> s3Endpoint,
Optional<String> s3Region,
boolean isServerAccess) {
Key {
// AWS and GCP scope a credential to every location in the context, so the key has them all.
locations = List.copyOf(locations);
privileges = Set.copyOf(privileges);
}

static Key of(CredentialContext context) {
// Per-bucket config vends have no credential DAO, so both role fields are null. AWS IAM role
// is the only DB-backed credential type today; a new type must add its binding to the key.
// Per-bucket config vends have no credential DAO, so both role fields are null. A new
// DB-backed credential type must add its binding to the key.
Optional<AwsIamRoleResponse> awsIamRole =
context.getCredentialDAO().map(CredentialDAO::getAwsIamRoleResponse);
context
.getCredentialDAO()
.filter(dao -> dao.getCredentialType() == CredentialType.AWS_IAM_ROLE)
.map(CredentialDAO::getAwsIamRoleResponse);
Optional<CredentialVersion> s3CompatibleVersion =
context
.getCredentialDAO()
.filter(dao -> dao.getCredentialType() == CredentialType.S3_COMPATIBLE)
.map(dao -> new CredentialVersion(dao.getId(), dao.getCredentialFingerprint()));
return new Key(
context.getLocations(),
context.getPrivileges(),
awsIamRole.map(AwsIamRoleResponse::getRoleArn).orElse(null),
awsIamRole.map(AwsIamRoleResponse::getExternalId).orElse(null));
awsIamRole.map(AwsIamRoleResponse::getExternalId).orElse(null),
s3CompatibleVersion,
context.getS3Endpoint(),
context.getS3Region(),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit (not a blocker): the cache key's region and the s3_compatible fingerprint aren't pinned by any test. Dropping context.getS3Region() from the key, or making getCredentialFingerprint() return a constant, leaves every test green. The region matters here because S3BucketRegions returns the fallback us-east-1, then the reported region, at the same endpoint, and the cached response carries that region. Would two rows in changedBindings work, plus one real-DAO check?

        Arguments.of(
            "s3_compatible payload",
            s3CompatibleCtx("fp-1", false),
            s3CompatibleCtx("fp-2", false)),
        // The storage reports its region later than a fallback, at the same endpoint.
        Arguments.of(
            "reported region",
            s3CompatibleCtx("fp-1", false, "us-east-1"),
            s3CompatibleCtx("fp-1", false, "garage")));

with an s3CompatibleCtx(fingerprint, isServerAccess, region) overload, and in CredentialDAOTest:

  @Test
  public void testFingerprintChangesWithTheStoredPayload() {
    String one = "{\"access_key_id\":\"key-id-1\",\"s3_endpoint\":\"" + S3_ENDPOINT + "\"}";
    String two = "{\"access_key_id\":\"key-id-2\",\"s3_endpoint\":\"" + S3_ENDPOINT + "\"}";
    assertThat(CredentialDAO.builder().credential(one).build().getCredentialFingerprint())
        .isEqualTo(CredentialDAO.builder().credential(one).build().getCredentialFingerprint())
        .isNotEqualTo(CredentialDAO.builder().credential(two).build().getCredentialFingerprint());
  }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

+1, could we add the region and endpoint cases plus a real-dao fingerprint check?

context.isServerAccess() && s3CompatibleVersion.isPresent());
}
}

private record CredentialVersion(UUID id, String fingerprint) {}

private record Entry(TemporaryCredentials credential, long serveUntilMs) {}

/** Expires each entry at its serve deadline; Caffeine's time comes from {@link #clock}. */
Expand Down
Loading
Loading