Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#15178] fix(spark-connector): Let a session's own token win over the application's token file (#15179)

YangJie026a6f7dd314
diff --git a/docs/spark-connector/spark-connector.md b/docs/spark-connector/spark-connector.md
index 9f8195fc44..2fbf892a00 100644
--- a/docs/spark-connector/spark-connector.md
+++ b/docs/spark-connector/spark-connector.md
@@ -39,7 +39,7 @@ The Apache Gravitino Spark connector leverages the Spark DataSourceV2 interface
| spark.sql.gravitino.client. | string | (none) | The configuration key prefix for the Gravitino client config. | No |
| spark.sql.gravitino.authType | string | `simple` | The authentication type, one of `simple`, `basic`, `oauth2`, `kerberos`, `token`. | No |
| spark.sql.gravitino.token.value | string | (none) | The bearer token to present to Gravitino, used when `authType` is `token`. | No |
-| spark.sql.gravitino.token.file | string | (none) | Path to a file holding the bearer token. Takes precedence over `token.value` and is re-read per request. | No |
+| spark.sql.gravitino.token.file | string | (none) | Path to a file holding the bearer token. Wins over a `token.value` set in the same session or application configuration, and is re-read per request. | No |
| spark.sql.gravitino.token.principalFields | string | `sub` | Comma separated, ordered JWT claim names used to identify the caller in `token` mode. | No |
| spark.sql.gravitino.clientCacheMaxSize | int | `100` | The maximum number of Gravitino clients cached, one per identity. | No |
| spark.sql.gravitino.clientCacheTtlSec | long | `3600` | Evicts a cached Gravitino client this many seconds after it was last used. | No |
@@ -65,10 +65,14 @@ for supported client configuration.
### Per-user identity in `token` mode
-When `spark.sql.gravitino.authType` is `token`, the connector presents the bearer token found in
-`spark.sql.gravitino.token.file`, or failing that `spark.sql.gravitino.token.value`, resolving it again on
-every request and reading the active Spark session's configuration in preference to the
-application's. The identity of the caller is taken from the JWT claim named by
+When `spark.sql.gravitino.authType` is `token`, the connector presents a bearer token and resolves it
+again on every request. A token that the active Spark session sets, through
+`spark.sql.gravitino.token.file` or `spark.sql.gravitino.token.value`, wins over the application's.
+If the session sets both, or the application sets both, `token.file` wins over `token.value`.
+Spark copies the application's configuration into every session, so a session setting equal to the
+application's counts as the application's; a session that wants its own token must set a token file
+or token value different from the application's. The identity of the caller is taken from the JWT
+claim named by
`spark.sql.gravitino.token.principalFields`, which should be set to match the server's
`gravitino.authenticator.oauth.principalFields` so that the connector and the server agree on who
is asking. The claim is read without verifying the signature, because validating the token remains
diff --git a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoDriverPlugin.java b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoDriverPlugin.java
index e51e271288..ceb46ee87e 100644
--- a/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoDriverPlugin.java
+++ b/spark-connector/spark-common/src/main/java/org/apache/gravitino/spark/connector/plugin/GravitinoDriverPlugin.java
@@ -60,6 +60,7 @@ import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.plugin.DriverPlugin;
import org.apache.spark.api.plugin.PluginContext;
+import org.apache.spark.sql.RuntimeConfig;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.internal.StaticSQLConf;
import org.slf4j.Logger;
@@ -387,23 +388,28 @@ public class GravitinoDriverPlugin implements DriverPlugin {
* Resolves the bearer token to present to Gravitino for the operation running on the current
* thread.
*
- * <p>The active Spark session's configuration wins over the application configuration, so a
- * shared driver can carry a different end user's token per session, and {@code tokenFile} wins
- * over {@code token}, so a token refreshed on disk is picked up without touching the
- * configuration. Neither the token nor any prefix of it is ever logged.
+ * <p>The active Spark session's own token, from either property, wins over the application's, so
+ * a shared driver can carry a different end user's token per session even when the application
+ * configures a token file of its own. Within one scope, {@code token.file} wins over {@code
+ * token.value}, so a token refreshed on disk is picked up without touching the configuration.
+ * Neither the token nor any prefix of it is ever logged.
*
- * @param sparkConf the application Spark configuration, used when no session supplies a token
+ * <p>A session starts with a copy of the application's configuration, so a session value equal to
+ * the application's is treated as inherited rather than set by the session.
+ *
+ * @param sparkConf the application Spark configuration, used when no session sets a token
* @return the bearer token, never blank
- * @throws IllegalArgumentException if neither token property is set
+ * @throws IllegalArgumentException if neither token property is set, or the token that applies is
+ * blank
* @throws UncheckedIOException if the configured token file cannot be read
*/
public static String resolveToken(SparkConf sparkConf) {
- String tokenFile =
- getSessionOrApplicationConfig(sparkConf, GravitinoSparkConfig.GRAVITINO_TOKEN_FILE);
+ Option<SparkSession> activeSession = SparkSession.getActiveSession();
String token =
- StringUtils.isNotBlank(tokenFile)
- ? readTokenFile(tokenFile)
- : getSessionOrApplicationConfig(sparkConf, GravitinoSparkConfig.GRAVITINO_TOKEN_VALUE);
+ activeSession.isDefined() ? tokenFromSession(activeSession.get(), sparkConf) : null;
+ if (token == null) {
+ token = tokenFromApplication(sparkConf);
+ }
Preconditions.checkArgument(
StringUtils.isNotBlank(token),
String.format(
@@ -423,16 +429,56 @@ public class GravitinoDriverPlugin implements DriverPlugin {
}
}
+ /**
+ * Resolves the token from one configuration scope, applying the within-scope rule that {@code
+ * token.file} wins over {@code token.value}.
+ *
+ * @param tokenFile the token file configured in this scope, nullable
+ * @param tokenValue the literal token configured in this scope, nullable
+ * @return the token for this scope, or null when the scope configures neither
+ */
@Nullable
- private static String getSessionOrApplicationConfig(SparkConf sparkConf, String configKey) {
- Option<SparkSession> activeSession = SparkSession.getActiveSession();
- if (activeSession.isDefined()) {
- Option<String> sessionValue = activeSession.get().conf().getOption(configKey);
- if (sessionValue.isDefined() && StringUtils.isNotBlank(sessionValue.get())) {
- return sessionValue.get();
- }
+ private static String resolveScopedToken(
+ @Nullable String tokenFile, @Nullable String tokenValue) {
+ return StringUtils.isNotBlank(tokenFile) ? readTokenFile(tokenFile) : tokenValue;
+ }
+
+ @Nullable
+ private static String tokenFromSession(SparkSession session, SparkConf sparkConf) {
+ RuntimeConfig sessionConf = session.conf();
+ return resolveScopedToken(
+ sessionConfig(sessionConf, sparkConf, GravitinoSparkConfig.GRAVITINO_TOKEN_FILE),
+ sessionConfig(sessionConf, sparkConf, GravitinoSparkConfig.GRAVITINO_TOKEN_VALUE));
+ }
+
+ @Nullable
+ private static String tokenFromApplication(SparkConf sparkConf) {
+ return resolveScopedToken(
+ getOptionalConfig(sparkConf, GravitinoSparkConfig.GRAVITINO_TOKEN_FILE),
+ getOptionalConfig(sparkConf, GravitinoSparkConfig.GRAVITINO_TOKEN_VALUE));
+ }
+
+ /**
+ * Returns the value the session itself set for the key, or null when the session did not set it.
+ *
+ * <p>Spark copies the application's configuration into every session's configuration at session
+ * creation, and only comparison with the application configuration tells an inherited value from
+ * one the session set. A session value equal to the application's is therefore treated as
+ * inherited, even when the session set it deliberately.
+ *
+ * @param sessionConf the active session's configuration
+ * @param sparkConf the application Spark configuration
+ * @param configKey the configuration key to look up
+ * @return the session-set value, or null when blank, unset, or inherited from the application
+ */
+ @Nullable
+ private static String sessionConfig(
+ RuntimeConfig sessionConf, SparkConf sparkConf, String configKey) {
+ Option<String> value = sessionConf.getOption(configKey);
+ if (!value.isDefined() || StringUtils.isBlank(value.get())) {
+ return null;
}
- return getOptionalConfig(sparkConf, configKey);
+ return value.get().equals(getOptionalConfig(sparkConf, configKey)) ? null : value.get();
}
/**
diff --git a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoDriverPlugin.java b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoDriverPlugin.java
index af21568292..4a4d071c32 100644
--- a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoDriverPlugin.java
+++ b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/plugin/TestGravitinoDriverPlugin.java
@@ -50,6 +50,8 @@ import org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.api.plugin.PluginContext;
+import org.apache.spark.sql.RuntimeConfig;
+import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.internal.StaticSQLConf;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -60,6 +62,7 @@ import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
+import scala.Option;
/**
* Tests what the plugin does with the bindings it is given. The bindings here are made up, so these
@@ -689,6 +692,105 @@ public class TestGravitinoDriverPlugin {
client.close();
}
+ /**
+ * Every new session starts with the application's token file in its configuration. A token the
+ * session sets itself must still win, and a session that sets nothing uses the application's.
+ */
+ @Test
+ void testSessionOwnTokenWinsInRealSparkSession(@TempDir Path tempDir) throws IOException {
+ Path appTokenFile = tempDir.resolve("driver.token");
+ Files.write(appTokenFile, "app-file-token\n".getBytes(StandardCharsets.UTF_8));
+ Path userTokenFile = tempDir.resolve("user.token");
+ Files.write(userTokenFile, "user-file-token\n".getBytes(StandardCharsets.UTF_8));
+ SparkSession root =
+ SparkSession.builder()
+ .master("local[1]")
+ .appName("test-session-token-resolution")
+ .config("spark.ui.enabled", "false")
+ .config("spark.driver.host", "127.0.0.1")
+ .config("spark.driver.bindAddress", "127.0.0.1")
+ .config("spark.sql.warehouse.dir", tempDir.resolve("warehouse").toUri().toString())
+ .config(GravitinoSparkConfig.GRAVITINO_AUTH_TYPE, AuthProperties.TOKEN_AUTH_TYPE)
+ .config(GravitinoSparkConfig.GRAVITINO_TOKEN_FILE, appTokenFile.toString())
+ .getOrCreate();
+ try {
+ SparkConf sparkConf = root.sparkContext().conf();
+ // A reused SparkContext would not carry the token file.
+ assertEquals(
+ appTokenFile.toString(), sparkConf.get(GravitinoSparkConfig.GRAVITINO_TOKEN_FILE, null));
+
+ SparkSession valueSession = root.newSession();
+ assertEquals(
+ appTokenFile.toString(),
+ valueSession.conf().get(GravitinoSparkConfig.GRAVITINO_TOKEN_FILE));
+ valueSession.conf().set(GravitinoSparkConfig.GRAVITINO_TOKEN_VALUE, "session-token");
+ SparkSession.setActiveSession(valueSession);
+ assertEquals("session-token", GravitinoDriverPlugin.resolveToken(sparkConf));
+
+ SparkSession fileSession = root.newSession();
+ fileSession.conf().set(GravitinoSparkConfig.GRAVITINO_TOKEN_FILE, userTokenFile.toString());
+ SparkSession.setActiveSession(fileSession);
+ assertEquals("user-file-token", GravitinoDriverPlugin.resolveToken(sparkConf));
+
+ SparkSession.setActiveSession(root.newSession());
+ assertEquals("app-file-token", GravitinoDriverPlugin.resolveToken(sparkConf));
+ } finally {
+ SparkSession.clearActiveSession();
+ SparkSession.clearDefaultSession();
+ root.stop();
+ }
+ }
+
+ /** Within the session's own configuration the token file wins over the literal token. */
+ @Test
+ void testSessionTokenFileWinsOverSessionTokenValue(@TempDir Path tempDir) throws IOException {
+ Path sessionTokenFile = tempDir.resolve("session.token");
+ Files.write(sessionTokenFile, "session-file-token\n".getBytes(StandardCharsets.UTF_8));
+ SparkConf sparkConf = tokenAuthConf();
+ sparkConf.set(GravitinoSparkConfig.GRAVITINO_TOKEN_VALUE, "app-value-token");
+
+ try (MockedStatic<SparkSession> sparkSessions =
+ mockActiveSession(sessionTokenFile.toString(), "session-value-token")) {
+ assertEquals("session-file-token", GravitinoDriverPlugin.resolveToken(sparkConf));
+ }
+ }
+
+ /**
+ * The session inherits the application's token file and sets its own literal token, which wins
+ * although the application also sets a literal token. The session's token is trimmed.
+ */
+ @Test
+ void testSessionTokenValueWinsWhenApplicationSetsBothKeys(@TempDir Path tempDir)
+ throws IOException {
+ Path appTokenFile = tempDir.resolve("driver.token");
+ Files.write(appTokenFile, "app-file-token\n".getBytes(StandardCharsets.UTF_8));
+ SparkConf sparkConf = tokenAuthConf();
+ sparkConf.set(GravitinoSparkConfig.GRAVITINO_TOKEN_FILE, appTokenFile.toString());
+ sparkConf.set(GravitinoSparkConfig.GRAVITINO_TOKEN_VALUE, "app-value-token");
+
+ try (MockedStatic<SparkSession> sparkSessions =
+ mockActiveSession(appTokenFile.toString(), " session-token\n")) {
+ assertEquals("session-token", GravitinoDriverPlugin.resolveToken(sparkConf));
+ }
+ }
+
+ /** An empty token file set by the session fails instead of using the application's token. */
+ @Test
+ void testEmptySessionTokenFileFails(@TempDir Path tempDir) throws IOException {
+ Path appTokenFile = tempDir.resolve("driver.token");
+ Files.write(appTokenFile, "app-file-token\n".getBytes(StandardCharsets.UTF_8));
+ Path sessionTokenFile = tempDir.resolve("session.token");
+ Files.write(sessionTokenFile, new byte[0]);
+ SparkConf sparkConf = tokenAuthConf();
+ sparkConf.set(GravitinoSparkConfig.GRAVITINO_TOKEN_FILE, appTokenFile.toString());
+
+ try (MockedStatic<SparkSession> sparkSessions =
+ mockActiveSession(sessionTokenFile.toString(), null)) {
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> GravitinoDriverPlugin.resolveToken(sparkConf));
+ }
+ }
+
@Test
void testSkipsCatalogAlreadyConfiguredInSpark() {
SparkConf sparkConf =
@@ -767,4 +869,24 @@ public class TestGravitinoDriverPlugin {
sparkConf.set(GravitinoSparkConfig.GRAVITINO_AUTH_TYPE, AuthProperties.TOKEN_AUTH_TYPE);
return sparkConf;
}
+
+ /** Makes a mocked session with the given token settings the active session. */
+ private static MockedStatic<SparkSession> mockActiveSession(
+ @Nullable String tokenFile, @Nullable String tokenValue) {
+ RuntimeConfig sessionConf = mock(RuntimeConfig.class);
+ when(sessionConf.getOption(GravitinoSparkConfig.GRAVITINO_TOKEN_FILE))
+ .thenReturn(Option.apply(tokenFile));
+ when(sessionConf.getOption(GravitinoSparkConfig.GRAVITINO_TOKEN_VALUE))
+ .thenReturn(Option.apply(tokenValue));
+ SparkSession session = mock(SparkSession.class);
+ when(session.conf()).thenReturn(sessionConf);
+ MockedStatic<SparkSession> sparkSessions = Mockito.mockStatic(SparkSession.class);
+ try {
+ sparkSessions.when(SparkSession::getActiveSession).thenReturn(Option.apply(session));
+ } catch (RuntimeException e) {
+ sparkSessions.close();
+ throw e;
+ }
+ return sparkSessions;
+ }
}