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
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@
import static org.assertj.core.api.Assertions.assertThat;

import io.unitycatalog.client.ApiClient;
import org.junit.jupiter.api.Test;

import java.net.URI;
import org.junit.jupiter.api.Test;

public class ApiClientFactoryTest extends BaseSparkIntegrationTest {
@Test
Expand All @@ -18,8 +17,8 @@ public void testApiClientBaseUri() {
.isEqualTo("https://localhost:8080/api/2.1/unity-catalog");

URI uriWithSuffix = URI.create("https://localhost:8080/path/to/uc/api");
ApiClient apiClientWithSuffix = ApiClientFactory
.createApiClient(clientConf, uriWithSuffix, token);
ApiClient apiClientWithSuffix =

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.

this file was caught when i ran javafmtAll

ApiClientFactory.createApiClient(clientConf, uriWithSuffix, token);
assertThat(apiClientWithSuffix.getBaseUri())
.isEqualTo("https://localhost:8080/path/to/uc/api/api/2.1/unity-catalog");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import io.unitycatalog.server.base.schema.SchemaOperations;
import io.unitycatalog.server.sdk.catalog.SdkCatalogOperations;
import io.unitycatalog.server.sdk.schema.SdkSchemaOperations;
import io.unitycatalog.server.service.credential.gcp.TestingCredentialsGenerator;
import io.unitycatalog.server.utils.TestUtils;
import io.unitycatalog.spark.utils.OptionsUtil;
import java.util.Optional;
Expand Down Expand Up @@ -90,8 +91,10 @@ protected void setUpProperties() {

serverProperties.put("gcs.bucketPath.0", "gs://test-bucket0");
serverProperties.put("gcs.jsonKeyFilePath.0", "testing://0");
serverProperties.put("gcs.credentialsGenerator.0", TestingCredentialsGenerator.class.getName());
serverProperties.put("gcs.bucketPath.1", "gs://test-bucket1");
serverProperties.put("gcs.jsonKeyFilePath.1", "testing://1");
serverProperties.put("gcs.credentialsGenerator.1", TestingCredentialsGenerator.class.getName());

serverProperties.put("adls.storageAccountName.0", "test-bucket0");
serverProperties.put("adls.tenantId.0", "tenantId0");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package io.unitycatalog.spark.auth;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

import com.google.auth.oauth2.AccessToken;
import com.google.cloud.hadoop.util.AccessTokenProvider;
import io.unitycatalog.server.service.credential.gcp.GcpCredentialsGenerator;
import java.time.Instant;
import java.util.Date;
import java.util.Map;

public class GcsCredRenewITTest extends BaseCredRenewITTest {
private static final String SCHEME = "gs";
private static final String CREDENTIALS_GENERATOR_CLASS = GcsCredGenerator.class.getName();

@Override
protected void setUpProperties() {
super.setUpProperties();
serverProperties.put("gcs.bucketPath.0", "gs://" + BUCKET_NAME);
serverProperties.put("gcs.credentialsGenerator.0", CREDENTIALS_GENERATOR_CLASS);
// Note: gcs.jsonKeyFilePath.0 is intentionally omitted because we're using a custom
// credentialsGenerator for testing. The generator is loaded first and jsonKeyFilePath
// is only used as a fallback for ServiceAccountCredentialsGenerator.
}

@Override
protected String scheme() {
return SCHEME;
}

@Override
protected Map<String, String> catalogExtraProps() {
// Override fs.gs.impl to use our testing filesystem that tracks credential renewals
// Note: fs.gs.impl.disable.cache is already set by CredPropsUtil.GcsPropsBuilder
return Map.of("fs.gs.impl", GcsCredFileSystem.class.getName());
}

public static class GcsCredGenerator extends TimeBasedCredGenerator<AccessToken>
implements GcpCredentialsGenerator {
@Override
protected AccessToken newTimeBasedCred(long ts) {
Instant expiration = Instant.ofEpochMilli(ts + DEFAULT_INTERVAL_MILLIS);
return AccessToken.newBuilder()
.setTokenValue(String.format("testing-renew://gs://%s#%d", BUCKET_NAME, ts))
.setExpirationTime(Date.from(expiration))
.build();
}
}

public static class GcsCredFileSystem extends CredRenewFileSystem<AccessTokenProvider> {
@Override
protected String scheme() {
return String.format("%s:", SCHEME);
}

@Override
protected AccessTokenProvider createProvider() {
String clazz = getConf().get("fs.gs.auth.access.token.provider");
assertThat(clazz).isEqualTo(GcsVendedTokenProvider.class.getName());

// The setConf() call will validate the Hadoop configuration, failing fast if
// any required properties (UC URI, token, credentials UID) are missing.
AccessTokenProvider provider = new GcsVendedTokenProvider();
provider.setConf(getConf());
return provider;
}

@Override
protected void assertCredentials(AccessTokenProvider provider, long ts) {
AccessTokenProvider.AccessToken token = provider.getAccessToken();
assertThat(token).isNotNull();
assertThat(token.getToken())
.as("OAuth token should contain timestamp %d", ts)
.isEqualTo(String.format("testing-renew://gs://%s#%d", BUCKET_NAME, ts));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,52 +15,64 @@
import io.unitycatalog.server.utils.ServerProperties;
import java.io.IOException;
import java.net.URI;
import java.sql.Date;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.SneakyThrows;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.iceberg.Files;

public class GcpCredentialVendor {

public static final List<String> INITIAL_SCOPES =
List.of("https://www.googleapis.com/auth/cloud-platform");

private final Map<String, String> gcsConfigurations;
private final Map<String, GcsStorageConfig> gcsConfigurations;
private final Map<String, GcpCredentialsGenerator> credentialGenerators =
new ConcurrentHashMap<>();

public GcpCredentialVendor(ServerProperties serverProperties) {
this.gcsConfigurations = serverProperties.getGcsConfigurations();
}

@SneakyThrows
public AccessToken vendGcpToken(CredentialContext credentialContext) {
String serviceAccountKeyJsonFilePath =
gcsConfigurations.get(credentialContext.getStorageBase());

GoogleCredentials creds;
if (serviceAccountKeyJsonFilePath != null && !serviceAccountKeyJsonFilePath.isEmpty()) {
if (serviceAccountKeyJsonFilePath.startsWith("testing://")) {
// allow pass-through of a dummy value for integration testing
return AccessToken.newBuilder()
.setTokenValue(serviceAccountKeyJsonFilePath)
.setExpirationTime(Date.from(Instant.ofEpochMilli(253370790000000L)))
.build();
}
creds =
ServiceAccountCredentials.fromStream(
Files.localInput(serviceAccountKeyJsonFilePath).newStream());
} else {
String storageBase = credentialContext.getStorageBase();
GcsStorageConfig storageConfig = gcsConfigurations.get(storageBase);

if (storageConfig == null) {
throw new BaseException(
ErrorCode.FAILED_PRECONDITION,
format("Unknown GCS storage configuration for %s.", storageBase));
}

GcpCredentialsGenerator generator =
credentialGenerators.computeIfAbsent(storageBase, key -> createGenerator(storageConfig));
return generator.generate(credentialContext);
}

private GcpCredentialsGenerator createGenerator(GcsStorageConfig storageConfig) {
String generatorClass = storageConfig.getCredentialsGenerator();
if (generatorClass != null && !generatorClass.isEmpty()) {
try {
creds = GoogleCredentials.getApplicationDefault();
} catch (IOException e) {
throw new BaseException(ErrorCode.FAILED_PRECONDITION, "GCS credentials not found.", e);
Class<? extends GcpCredentialsGenerator> generatorType =
Class.forName(generatorClass).asSubclass(GcpCredentialsGenerator.class);
try {
return generatorType
.getDeclaredConstructor(GcsStorageConfig.class)
.newInstance(storageConfig);
} catch (NoSuchMethodException e) {
return generatorType.getDeclaredConstructor().newInstance();
}
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate GCS credentials generator " + generatorClass, e);
}
}

return downscopeGcpCreds(creds.createScoped(INITIAL_SCOPES), credentialContext)
.refreshAccessToken();
String jsonKeyFilePath = storageConfig.getJsonKeyFilePath();
if (jsonKeyFilePath != null && jsonKeyFilePath.isEmpty()) {
jsonKeyFilePath = null;
}

return new ServiceAccountCredentialsGenerator(jsonKeyFilePath);
}

OAuth2Credentials downscopeGcpCreds(GoogleCredentials credentials, CredentialContext context) {
Expand Down Expand Up @@ -118,4 +130,28 @@ List<String> resolvePrivilegesToRoles(Set<CredentialContext.Privilege> privilege
}
return List.of();
}

private final class ServiceAccountCredentialsGenerator implements GcpCredentialsGenerator {
private final String jsonKeyFilePath;

private ServiceAccountCredentialsGenerator(String jsonKeyFilePath) {
this.jsonKeyFilePath = jsonKeyFilePath;
}

@Override
public AccessToken generate(CredentialContext context) {
try {
GoogleCredentials creds;
if (jsonKeyFilePath != null && !jsonKeyFilePath.isEmpty()) {
creds =
ServiceAccountCredentials.fromStream(Files.localInput(jsonKeyFilePath).newStream());
} else {
creds = GoogleCredentials.getApplicationDefault();
}
return downscopeGcpCreds(creds.createScoped(INITIAL_SCOPES), context).refreshAccessToken();
} catch (IOException e) {
throw new BaseException(ErrorCode.FAILED_PRECONDITION, "GCS credentials not found.", e);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.unitycatalog.server.service.credential.gcp;

import com.google.auth.oauth2.AccessToken;
import io.unitycatalog.server.service.credential.CredentialContext;

/**
* Pluggable contract for generating GCS OAuth tokens. Allows production code to load custom
* implementations for integration tests without coupling to {@link GcpCredentialVendor}.
*/
public interface GcpCredentialsGenerator {
AccessToken generate(CredentialContext context);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package io.unitycatalog.server.service.credential.gcp;

import lombok.Builder;
import lombok.Getter;
import lombok.ToString;

@Getter
@Builder
@ToString
public class GcsStorageConfig {
private final String bucketPath;
private final String jsonKeyFilePath;
private final String credentialsGenerator;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package io.unitycatalog.server.service.credential.gcp;

import com.google.auth.oauth2.AccessToken;
import io.unitycatalog.server.service.credential.CredentialContext;
import java.time.Instant;
import java.util.Date;

/**
* Simple generator that returns a static token for GCS. Intended for testing and local development
* scenarios where a real GCP service account is not available.
*/
public class TestingCredentialsGenerator implements GcpCredentialsGenerator {
private static final long TOKEN_EXPIRATION_MILLIS = 253370790000000L;

private final AccessToken staticToken;

public TestingCredentialsGenerator(GcsStorageConfig storageConfig) {
String tokenValue = storageConfig.getJsonKeyFilePath();
if (tokenValue == null || tokenValue.isEmpty()) {
tokenValue = String.format("testing://%s", storageConfig.getBucketPath());
}
Instant expirationInstant = Instant.ofEpochMilli(TOKEN_EXPIRATION_MILLIS);
this.staticToken =
AccessToken.newBuilder()
.setTokenValue(tokenValue)
.setExpirationTime(Date.from(expirationInstant))
.build();
}

@Override
public AccessToken generate(CredentialContext context) {
return staticToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import io.unitycatalog.server.exception.ErrorCode;
import io.unitycatalog.server.service.credential.aws.S3StorageConfig;
import io.unitycatalog.server.service.credential.azure.ADLSStorageConfig;
import io.unitycatalog.server.service.credential.gcp.GcsStorageConfig;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
Expand Down Expand Up @@ -120,16 +121,23 @@ public Map<String, S3StorageConfig> getS3Configurations() {
return s3BucketConfigMap;
}

public Map<String, String> getGcsConfigurations() {
Map<String, String> gcsConfigMap = new HashMap<>();
public Map<String, GcsStorageConfig> getGcsConfigurations() {
Map<String, GcsStorageConfig> gcsConfigMap = new HashMap<>();
int i = 0;
while (true) {
String bucketPath = getProperty("gcs.bucketPath." + i);
String jsonKeyFilePath = getProperty("gcs.jsonKeyFilePath." + i);
if (bucketPath == null || jsonKeyFilePath == null) {
if (bucketPath == null) {
break;
}
gcsConfigMap.put(bucketPath, jsonKeyFilePath);
String jsonKeyFilePath = getProperty("gcs.jsonKeyFilePath." + i);
String credentialsGenerator = getProperty("gcs.credentialsGenerator." + i);
gcsConfigMap.put(
bucketPath,
GcsStorageConfig.builder()
.bucketPath(bucketPath)
.jsonKeyFilePath(jsonKeyFilePath)
.credentialsGenerator(credentialsGenerator)
.build());
i++;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import io.unitycatalog.server.service.credential.azure.AzureCredential;
import io.unitycatalog.server.service.credential.azure.AzureCredentialVendor;
import io.unitycatalog.server.service.credential.gcp.GcpCredentialVendor;
import io.unitycatalog.server.service.credential.gcp.TestingCredentialsGenerator;
import java.time.Instant;
import java.util.Date;
import java.util.List;
Expand All @@ -41,6 +42,7 @@ protected void setUpProperties() {

serverProperties.put("gcs.bucketPath.0", "gs://test-bucket0");
serverProperties.put("gcs.jsonKeyFilePath.0", "testing://0");
serverProperties.put("gcs.credentialsGenerator.0", TestingCredentialsGenerator.class.getName());

serverProperties.put("adls.storageAccountName.0", "test-bucket0");
serverProperties.put("adls.tenantId.0", "tenantId0");
Expand Down
Loading