Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,30 @@
import java.time.Instant;

public class GcsVendedTokenProvider implements AccessTokenProvider {
protected static final String ACCESS_TOKEN_KEY = "fs.gs.auth.access.token.credential";
protected static final String ACCESS_TOKEN_EXPIRATION_KEY = "fs.gs.auth.access.token.expiration";
private Configuration conf;
public static final String ACCESS_TOKEN_KEY = "fs.gs.auth.access.token.credential";

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.

Since the CredProsUtil moved to auth package, so those two static fields need to be public.

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.

The following changes are fixing the checkstyle validation.

public static final String ACCESS_TOKEN_EXPIRATION_KEY = "fs.gs.auth.access.token.expiration";
private Configuration conf;

@Override
public AccessToken getAccessToken() {
return new AccessToken(
conf.get(ACCESS_TOKEN_KEY),
Instant.ofEpochMilli(Long.parseLong(conf.get(ACCESS_TOKEN_EXPIRATION_KEY)))
);
}
@Override
public AccessToken getAccessToken() {
return new AccessToken(
conf.get(ACCESS_TOKEN_KEY),
Instant.ofEpochMilli(Long.parseLong(conf.get(ACCESS_TOKEN_EXPIRATION_KEY)))
);
}

@Override
public void refresh() throws IOException {
throw new IOException("Temporary token, not refreshable");
}
@Override
public void refresh() throws IOException {
throw new IOException("Temporary token, not refreshable");
}

@Override
public void setConf(Configuration configuration) {
conf = configuration;
}
@Override
public void setConf(Configuration configuration) {
conf = configuration;
}

@Override
public Configuration getConf() {
return conf;
}
@Override
public Configuration getConf() {
return conf;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ public class UCHadoopConf {
private UCHadoopConf() {
}

// Key for the AWS S3 credential provider, same as org.apache.hadoop.fs.s3a.Constants
// #AWS_CREDENTIALS_PROVIDER, but defined here to avoid an extra hadoop-aws dependency.
public static final String S3A_CREDENTIALS_PROVIDER = "fs.s3a.aws.credentials.provider";

// Keys for the initialized aws s3 credentials.
public static final String S3A_INIT_ACCESS_KEY = "fs.s3a.init.access.key";
public static final String S3A_INIT_SECRET_KEY = "fs.s3a.init.secret.key";
Expand All @@ -17,29 +21,33 @@ private UCHadoopConf() {
"fs.azure.init.sas.token.expired.time";

// Keys for the UnityCatalog client.
public static final String UC_URI_KEY = "unitycatalog.uri";
public static final String UC_TOKEN_KEY = "unitycatalog.token";
// Note: Delta automatically filters out configuration keys without the "fs." prefix To ensure
Comment thread
tdas marked this conversation as resolved.
Resolved
// custom configuration keys (e.g., AWS, ABFS, or GCS credentials) propagate correctly into Hadoop
// FileSystems such as S3AFileSystem or AbfsFileSystem, the keys must include the "fs." prefix.
// See also: https://github.com/unitycatalog/unitycatalog/issues/1112.
public static final String UC_URI_KEY = "fs.unitycatalog.uri";
Comment thread
tdas marked this conversation as resolved.
Resolved
public static final String UC_TOKEN_KEY = "fs.unitycatalog.token";

// Key representing a unique credential ID. It identifies a job-level credential for a specific
// table, meaning that the same job–table combination shares the same credential. Cached
// credentials are indexed by this key and are not reused across different jobs.
public static final String UC_CREDENTIALS_UID_KEY = "unitycatalog.credentials.uid";
public static final String UC_CREDENTIALS_UID_KEY = "fs.unitycatalog.credentials.uid";
Comment thread
tdas marked this conversation as resolved.
Resolved

// Keys for table based temporary credential requests
public static final String UC_TABLE_ID_KEY = "unitycatalog.table.id";
public static final String UC_TABLE_OPERATION_KEY = "unitycatalog.table.operation";
public static final String UC_TABLE_ID_KEY = "fs.unitycatalog.table.id";
public static final String UC_TABLE_OPERATION_KEY = "fs.unitycatalog.table.operation";

// Keys for path based temporary credential requests.
public static final String UC_PATH_KEY = "unitycatalog.path";
public static final String UC_PATH_OPERATION_KEY = "unitycatalog.path.operation";
public static final String UC_PATH_KEY = "fs.unitycatalog.path";
public static final String UC_PATH_OPERATION_KEY = "fs.unitycatalog.path.operation";

// Key indicating the credential request type, table or path.
public static final String UC_CREDENTIALS_TYPE_KEY = "unitycatalog.credentials.type";
public static final String UC_CREDENTIALS_TYPE_KEY = "fs.unitycatalog.credentials.type";
public static final String UC_CREDENTIALS_TYPE_TABLE_VALUE = "table";
public static final String UC_CREDENTIALS_TYPE_PATH_VALUE = "path";

// Key to enable the credential cache.
public static final String UC_CREDENTIAL_CACHE_ENABLED_KEY =
"unitycatalog.credential.cache.enabled";
"fs.unitycatalog.credential.cache.enabled";
public static final boolean UC_CREDENTIAL_CACHE_ENABLED_DEFAULT_VALUE = true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ package io.unitycatalog.spark
import io.unitycatalog.client.{ApiClient, ApiException}
import io.unitycatalog.client.api.{SchemasApi, TablesApi, TemporaryCredentialsApi}
import io.unitycatalog.client.model.{ColumnInfo, ColumnTypeName, CreateSchema, CreateTable, DataSourceFormat, GenerateTemporaryPathCredential, GenerateTemporaryTableCredential, ListTablesResponse, PathOperation, SchemaInfo, TableOperation, TableType, TemporaryCredentials}
import io.unitycatalog.spark.auth.AbfsVendedTokenProvider
import io.unitycatalog.spark.auth.CredPropsUtil
import io.unitycatalog.spark.utils.OptionsUtil

import java.net.URI
import java.util
import org.apache.hadoop.fs.Path
import org.apache.hadoop.fs.azurebfs.constants.ConfigurationKeys.{FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME, FS_AZURE_ACCOUNT_IS_HNS_ENABLED, FS_AZURE_SAS_TOKEN_PROVIDER_TYPE}
import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.analysis.{NoSuchNamespaceException, NoSuchTableException}
Expand All @@ -17,6 +17,7 @@ import org.apache.spark.sql.connector.catalog._
import org.apache.spark.sql.connector.expressions.Transform
import org.apache.spark.sql.types.{BinaryType, BooleanType, ByteType, DataType, DoubleType, FloatType, IntegerType, LongType, ShortType, StringType, StructField, StructType, TimestampNTZType, TimestampType}
import org.apache.spark.sql.util.CaseInsensitiveStringMap
import org.sparkproject.guava.base.Preconditions

import scala.collection.convert.ImplicitConversions._
import scala.collection.JavaConverters._
Expand All @@ -30,29 +31,27 @@ class UCSingleCatalog
with SupportsNamespaces
with Logging {

private[this] var uri: URI = null
private[this] var token: String = null
private[this] var renewCredEnabled: Boolean = false
private[this] var apiClient: ApiClient = null;
private[this] var temporaryCredentialsApi: TemporaryCredentialsApi = null

@volatile private var delegate: TableCatalog = null

override def initialize(name: String, options: CaseInsensitiveStringMap): Unit = {
val urlStr = options.get("uri")
if (urlStr == null) {
throw new IllegalArgumentException(s"uri must be specified for Unity Catalog '$name'")
}
val url = new URI(urlStr)
apiClient = new ApiClient()
.setHost(url.getHost)
.setPort(url.getPort)
.setScheme(url.getScheme)
val token = options.get("token")
if (token != null && token.nonEmpty) {
apiClient = apiClient.setRequestInterceptor { request =>
request.header("Authorization", "Bearer " + token)
}
}
val urlStr = options.get(OptionsUtil.URI)
Preconditions.checkArgument(urlStr != null,
"uri must be specified for Unity Catalog '%s'", name)
uri = new URI(urlStr)
token = options.get(OptionsUtil.TOKEN)
renewCredEnabled = OptionsUtil.getBoolean(options,
OptionsUtil.RENEW_CREDENTIAL_ENABLED,
OptionsUtil.DEFAULT_RENEW_CREDENTIAL_ENABLED)

apiClient = ApiClientFactory.createApiClient(uri, token)
temporaryCredentialsApi = new TemporaryCredentialsApi(apiClient)
val proxy = new UCProxy(apiClient, temporaryCredentialsApi)
val proxy = new UCProxy(uri, token, renewCredEnabled, apiClient, temporaryCredentialsApi)
proxy.initialize(name, options)
if (UCSingleCatalog.LOAD_DELTA_CATALOG.get()) {
try {
Expand Down Expand Up @@ -114,9 +113,17 @@ class UCSingleCatalog
new GenerateTemporaryPathCredential().url(location).operation(PathOperation.PATH_CREATE_TABLE))
val newProps = new util.HashMap[String, String]
newProps.putAll(properties)
val credentialProps = UCSingleCatalog.generateCredentialProps(
CatalogUtils.stringToURI(location).getScheme, cred)
newProps.putAll(credentialProps.asJava)

val credentialProps = CredPropsUtil.createPathCredProps(
renewCredEnabled,
CatalogUtils.stringToURI(location).getScheme,
uri.toString,
token,
location,
PathOperation.PATH_CREATE_TABLE,
cred)

newProps.putAll(credentialProps)
// TODO: Delta requires the options to be set twice in the properties, with and without the
// `option.` prefix. We should revisit this in Delta.
val prefix = TableCatalog.OPTION_PREFIX
Expand Down Expand Up @@ -173,49 +180,13 @@ class UCSingleCatalog
object UCSingleCatalog {
val LOAD_DELTA_CATALOG = ThreadLocal.withInitial[Boolean](() => true)
val DELTA_CATALOG_LOADED = ThreadLocal.withInitial[Boolean](() => false)

def generateCredentialProps(
scheme: String,
temporaryCredentials: TemporaryCredentials): Map[String, String] = {
if (scheme == "s3") {
val awsCredentials = temporaryCredentials.getAwsTempCredentials
Map(
// TODO: how to support s3:// properly?
"fs.s3a.access.key" -> awsCredentials.getAccessKeyId,
"fs.s3a.secret.key" -> awsCredentials.getSecretAccessKey,
"fs.s3a.session.token" -> awsCredentials.getSessionToken,
"fs.s3a.path.style.access" -> "true",
"fs.s3.impl.disable.cache" -> "true",
"fs.s3a.impl.disable.cache" -> "true"
)
} else if (scheme == "gs") {
val gcsCredentials = temporaryCredentials.getGcpOauthToken
Map(
GcsVendedTokenProvider.ACCESS_TOKEN_KEY -> gcsCredentials.getOauthToken,
GcsVendedTokenProvider.ACCESS_TOKEN_EXPIRATION_KEY -> temporaryCredentials.getExpirationTime.toString,
"fs.gs.create.items.conflict.check.enable" -> "false",
"fs.gs.auth.type" -> "ACCESS_TOKEN_PROVIDER",
"fs.gs.auth.access.token.provider" -> classOf[GcsVendedTokenProvider].getName,
"fs.gs.impl.disable.cache" -> "true"
)
} else if (scheme == "abfs" || scheme == "abfss") {
val azCredentials = temporaryCredentials.getAzureUserDelegationSas
Map(
FS_AZURE_ACCOUNT_AUTH_TYPE_PROPERTY_NAME -> "SAS",
FS_AZURE_ACCOUNT_IS_HNS_ENABLED -> "true",
FS_AZURE_SAS_TOKEN_PROVIDER_TYPE -> classOf[AbfsVendedTokenProvider].getName,
AbfsVendedTokenProvider.ACCESS_TOKEN_KEY -> azCredentials.getSasToken,
"fs.abfs.impl.disable.cache" -> "true",
"fs.abfss.impl.disable.cache" -> "true"
)
} else {
Map.empty
}
}
}

// An internal proxy to talk to the UC client.
private class UCProxy(
uri: URI,
token: String,
renewCredEnabled: Boolean,
apiClient: ApiClient,
temporaryCredentialsApi: TemporaryCredentialsApi) extends TableCatalog with SupportsNamespaces {
private[this] var name: String = null
Expand Down Expand Up @@ -260,8 +231,9 @@ private class UCProxy(
StructField(col.getName, DataType.fromDDL(col.getTypeText), col.getNullable)
.withComment(col.getComment)
}.toArray
val uri = CatalogUtils.stringToURI(t.getStorageLocation)
val locationUri = CatalogUtils.stringToURI(t.getStorageLocation)
val tableId = t.getTableId
var tableOp = TableOperation.READ_WRITE
val temporaryCredentials = {
try {
temporaryCredentialsApi
Expand All @@ -270,17 +242,28 @@ private class UCProxy(
// request READ_WRITE credentials as the server doesn't distinguish between READ and
// READ_WRITE credentials as of today. When loading a table, Spark should tell if it's
// for read or write, we can request the proper credential after fixing Spark.
new GenerateTemporaryTableCredential().tableId(tableId).operation(TableOperation.READ_WRITE)
new GenerateTemporaryTableCredential().tableId(tableId).operation(tableOp)
)
} catch {
case e: ApiException => temporaryCredentialsApi
.generateTemporaryTableCredentials(
new GenerateTemporaryTableCredential().tableId(tableId).operation(TableOperation.READ)
)
case _: ApiException =>
tableOp = TableOperation.READ
temporaryCredentialsApi
.generateTemporaryTableCredentials(
new GenerateTemporaryTableCredential().tableId(tableId).operation(tableOp)
)
}
}
val extraSerdeProps = UCSingleCatalog.generateCredentialProps(
uri.getScheme, temporaryCredentials)

val extraSerdeProps = CredPropsUtil.createTableCredProps(
renewCredEnabled,
locationUri.getScheme,
uri.toString,
token,
tableId,
tableOp,
temporaryCredentials,
)

val sparkTable = CatalogTable(
identifier,
tableType = if (t.getTableType == TableType.MANAGED) {
Expand All @@ -289,7 +272,7 @@ private class UCProxy(
CatalogTableType.EXTERNAL
},
storage = CatalogStorageFormat.empty.copy(
locationUri = Some(uri),
locationUri = Some(locationUri),
properties = t.getProperties.asScala.toMap ++ extraSerdeProps
),
schema = StructType(fields),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@ public GenericCredential initGenericCredential(Configuration conf) {
String secretKey = conf.get(UCHadoopConf.S3A_INIT_SECRET_KEY);
String sessionToken = conf.get(UCHadoopConf.S3A_INIT_SESSION_TOKEN);

long expiredTimeMillis = conf.getLong(UCHadoopConf.S3A_INIT_CRED_EXPIRED_TIME, 0L);
long expiredTimeMillis = conf.getLong(
UCHadoopConf.S3A_INIT_CRED_EXPIRED_TIME,
Long.MAX_VALUE);

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.

@tdas , for the fixed credentials case, the expiration time should be infinite. That's why I changed its default value to Long.MAX_VALUE.

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.

I changed it because currently we TestReadWriteTest use the constant ak/sk/sessionToken to bootstrap the OSS UC server, and the uc server think it's using the fixed credentials which will never to be expired.

See:

if (s3StorageConfig.getSessionToken() != null && !s3StorageConfig.getSessionToken().isEmpty()) {
// if a session token was supplied, then we will just return static session credentials
return Credentials.builder()
.accessKeyId(s3StorageConfig.getAccessKey())
.secretAccessKey(s3StorageConfig.getSecretKey())
.sessionToken(s3StorageConfig.getSessionToken())
.build();
}

So for the AwsVendedTokenProvider in the integrated unit test, it will request the DB UC server, and get the fixed and never-expire credentials ( without setting any expiration time ).

Thrown it here for reviewing.

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.

I'm not sure it's good to set it be 0 or LONG.MAX_VALUE. Seems like the document is allowed to set 0 for the expiration_time. https://docs.databricks.com/api/gcp/workspace/temporarytablecredentials/generatetemporarytablecredentials

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

let me think about it.

@tdas tdas Oct 20, 2025 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

So the integration test in this PR is not really testing refresh at all... its only testing that the first initial cred received from actually gets injected .. thats all.

isnt it?

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.

Yes, that's true. For this PR, the focus is making the AwsVendedTokenProvider to go through the whole running path, I mean enabling it to the local integration test, for convincing people that after successfully configuring the renewCrednetial.enabled=true, it won't break the job for the starting process.

For the credential renewal process, it will be addressed in this e2e test: #1119

I mean we will start a long-runing job (> 30min), and continuesly run and renew the credentials whenever it's required.

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.

Also I can try to add the renewal local unit test, like the TableReadWriteTest. All renewal credentials will be issued from the OSS UC server. Anyway I think it's better to have separate PR to address it, since the current PR have enough complex context to address.

Preconditions.checkState(expiredTimeMillis > 0, "Expired time %s must be greater than 0, " +
"please check configure key '%s'", expiredTimeMillis, UCHadoopConf.S3A_INIT_CRED_EXPIRED_TIME);

Expand Down
Loading