HyukjinKwon commented on code in PR #57387:
URL: https://github.com/apache/spark/pull/57387#discussion_r3627521286


##########
core/src/main/scala/org/apache/spark/deploy/security/UserCredentialManager.scala:
##########
@@ -0,0 +1,433 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.deploy.security
+
+import java.io.{ByteArrayOutputStream, ObjectInputFilter, ObjectInputStream, 
ObjectOutputStream}
+import java.net.URI
+import java.nio.file.Paths
+import java.time.Instant
+import java.util.concurrent.{RejectedExecutionException, 
ScheduledExecutorService, TimeUnit}
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.collection.mutable
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.SparkConf
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys
+import org.apache.spark.internal.config._
+import org.apache.spark.security._
+import org.apache.spark.ui.UIUtils
+import org.apache.spark.util.ThreadUtils
+
+/**
+ * Manager for OIDC-based credential propagation on the driver.
+ *
+ * This class is a sibling of [[HadoopDelegationTokenManager]] and handles the 
OIDC credential
+ * propagation path independently. Both managers run on independent threads 
and can both be
+ * active simultaneously (e.g., a cluster accessing HDFS via Kerberos and S3 
via OIDC).
+ *
+ * Responsibilities:
+ *   1. Reads the current identity token via a [[TokenIngestor]]
+ *   2. Calls [[CredentialProvider#resolve]] for each configured scheme
+ *   3. Serializes the resulting [[UserCredentials]] and invokes the 
propagation callback
+ *   4. Schedules renewal based on `min(identity token expiry, service 
credential expiry) -
+ *      safetyMargin`
+ *   5. Retries with exponential backoff on failure
+ *
+ * Started from `CoarseGrainedSchedulerBackend.start()` when
+ * `spark.security.credentials.enabled=true`, independently of
+ * `UserGroupInformation.isSecurityEnabled()`.
+ *
+ * Lifecycle: call `start()` exactly once, then `stop()` to shut down.
+ * Calling `start()` after `stop()` is not supported.
+ */
+private[spark] class UserCredentialManager(
+    sparkConf: SparkConf,
+    tokenIngestor: TokenIngestor,
+    onCredentialsUpdate: Array[Byte] => Unit) extends Logging {
+
+  private val safetyMargin = 
sparkConf.get(SECURITY_CREDENTIALS_RENEWAL_SAFETY_MARGIN)
+  private val minInterval = 
sparkConf.get(SECURITY_CREDENTIALS_RENEWAL_MIN_INTERVAL)
+
+  // Thread-safe counter for exponential backoff calculation.
+  // Accessed from both the caller of start() and the scheduled renewal thread.
+  private val consecutiveFailures = new AtomicInteger(0)
+  private val maxBackoffMs: Long = TimeUnit.MINUTES.toMillis(10)

Review Comment:
   `maxBackoffMs` is a hardcoded 10-minute magic constant, while its scheduling 
peers `safetyMargin` and `minInterval` are both configs 
(`SECURITY_CREDENTIALS_RENEWAL_*`). For consistency, consider making this a 
config too, or at least a named constant on the companion `object` beside 
`DEFAULT_RENEWAL_INTERVAL_NO_EXPIRY_MS`. Non-blocking.



##########
core/src/main/scala/org/apache/spark/deploy/security/UserCredentialManager.scala:
##########
@@ -0,0 +1,433 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.deploy.security
+
+import java.io.{ByteArrayOutputStream, ObjectInputFilter, ObjectInputStream, 
ObjectOutputStream}
+import java.net.URI
+import java.nio.file.Paths
+import java.time.Instant
+import java.util.concurrent.{RejectedExecutionException, 
ScheduledExecutorService, TimeUnit}
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.collection.mutable
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.SparkConf
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys
+import org.apache.spark.internal.config._
+import org.apache.spark.security._
+import org.apache.spark.ui.UIUtils
+import org.apache.spark.util.ThreadUtils
+
+/**
+ * Manager for OIDC-based credential propagation on the driver.
+ *
+ * This class is a sibling of [[HadoopDelegationTokenManager]] and handles the 
OIDC credential
+ * propagation path independently. Both managers run on independent threads 
and can both be
+ * active simultaneously (e.g., a cluster accessing HDFS via Kerberos and S3 
via OIDC).
+ *
+ * Responsibilities:
+ *   1. Reads the current identity token via a [[TokenIngestor]]
+ *   2. Calls [[CredentialProvider#resolve]] for each configured scheme
+ *   3. Serializes the resulting [[UserCredentials]] and invokes the 
propagation callback
+ *   4. Schedules renewal based on `min(identity token expiry, service 
credential expiry) -
+ *      safetyMargin`
+ *   5. Retries with exponential backoff on failure
+ *
+ * Started from `CoarseGrainedSchedulerBackend.start()` when
+ * `spark.security.credentials.enabled=true`, independently of
+ * `UserGroupInformation.isSecurityEnabled()`.
+ *
+ * Lifecycle: call `start()` exactly once, then `stop()` to shut down.
+ * Calling `start()` after `stop()` is not supported.
+ */
+private[spark] class UserCredentialManager(
+    sparkConf: SparkConf,
+    tokenIngestor: TokenIngestor,
+    onCredentialsUpdate: Array[Byte] => Unit) extends Logging {
+
+  private val safetyMargin = 
sparkConf.get(SECURITY_CREDENTIALS_RENEWAL_SAFETY_MARGIN)
+  private val minInterval = 
sparkConf.get(SECURITY_CREDENTIALS_RENEWAL_MIN_INTERVAL)
+
+  // Thread-safe counter for exponential backoff calculation.
+  // Accessed from both the caller of start() and the scheduled renewal thread.
+  private val consecutiveFailures = new AtomicInteger(0)
+  private val maxBackoffMs: Long = TimeUnit.MINUTES.toMillis(10)
+
+  @volatile private var renewalExecutor: ScheduledExecutorService = _
+
+  // Pre-compute the filtered credential configuration map (SparkConf is 
immutable).
+  private val credentialConfMap: java.util.Map[String, String] = 
sparkConf.getAll
+    .filter(_._1.startsWith("spark.security.credentials."))
+    .toMap.asJava
+
+  /**
+   * Start the credential manager. Acquires initial credentials and schedules 
renewal.
+   *
+   * The initial credential acquisition is fail-fast: if the token cannot be 
loaded or
+   * no credentials can be resolved, an exception is thrown. Subsequent 
renewal failures
+   * are handled with exponential backoff.
+   *
+   * @return The serialized initial [[UserCredentials]].
+   * @throws IllegalStateException if the initial credential acquisition fails.
+   */
+  def start(): Array[Byte] = {
+    require(renewalExecutor == null, "start() must not be called more than 
once")

Review Comment:
   `start()` assigns `renewalExecutor` (next line) *before* the fail-fast 
acquisition, which can throw at line 101 (token missing) or via 
`resolveCredentials` at line 232 (no credentials resolved). On that throw, the 
daemon-thread executor has been created but is never returned or stopped, and 
because `start()` opens with this `require(renewalExecutor == null, ...)`, a 
caller that catches the exception can never retry — the guard now trips.
   
   The analogue `HadoopDelegationTokenManager` avoids this: its 
`updateTokensTask()` catches and reschedules rather than throwing out of 
`start()`, so it never leaves `start()` with a live unmanaged executor.
   
   Since the executor isn't used for the synchronous initial acquisition, the 
cleanest fix is to create it *after* the acquisition succeeds, just before 
`scheduleRenewal(renewalDelay)`. Alternatively, wrap the acquisition in a `try` 
that calls `renewalExecutor.shutdownNow()` and nulls the field before 
rethrowing.



##########
core/src/main/java/org/apache/spark/security/CredentialProviderLoader.java:
##########
@@ -221,10 +221,38 @@ private static List<CredentialProvider> loadProviders() {
     return result;
   }
 
+  /**
+   * Discovers all URI schemes supported by providers on the classpath.
+   * <p>
+   * This method queries all discovered {@link CredentialProvider} instances 
and collects
+   * their {@link CredentialProvider#supportedSchemes()} into a single set. 
Unlike
+   * {@link #providerFor(String, Map)}, this does not initialize providers or 
apply
+   * explicit selection rules -- it only reports what schemes are potentially 
available.
+   * <p>
+   * Intended for use by {@code UserCredentialManager} when no explicit scheme 
configuration
+   * (e.g., {@code spark.security.credentials.provider.<scheme>}) is provided.
+   *
+   * @param conf Spark configuration properties (used for potential future 
filtering)
+   * @return a set of all supported scheme names (lowercased), possibly empty
+   */
+  public static Set<String> discoverAllSchemes(Map<String, String> conf) {

Review Comment:
   The `conf` parameter is never used in this method body — the Javadoc notes 
it's "used for potential future filtering." An unused parameter is YAGNI: 
consider dropping it until the filtering actually lands (the caller 
`discoverSchemes()` can add it back with the feature). Non-blocking.



##########
core/src/main/scala/org/apache/spark/deploy/security/UserCredentialManager.scala:
##########
@@ -0,0 +1,433 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.deploy.security
+
+import java.io.{ByteArrayOutputStream, ObjectInputFilter, ObjectInputStream, 
ObjectOutputStream}
+import java.net.URI
+import java.nio.file.Paths
+import java.time.Instant
+import java.util.concurrent.{RejectedExecutionException, 
ScheduledExecutorService, TimeUnit}
+import java.util.concurrent.atomic.AtomicInteger
+
+import scala.collection.mutable
+import scala.jdk.CollectionConverters._
+
+import org.apache.spark.SparkConf
+import org.apache.spark.internal.Logging
+import org.apache.spark.internal.LogKeys
+import org.apache.spark.internal.config._
+import org.apache.spark.security._
+import org.apache.spark.ui.UIUtils
+import org.apache.spark.util.ThreadUtils
+
+/**
+ * Manager for OIDC-based credential propagation on the driver.
+ *
+ * This class is a sibling of [[HadoopDelegationTokenManager]] and handles the 
OIDC credential
+ * propagation path independently. Both managers run on independent threads 
and can both be
+ * active simultaneously (e.g., a cluster accessing HDFS via Kerberos and S3 
via OIDC).
+ *
+ * Responsibilities:
+ *   1. Reads the current identity token via a [[TokenIngestor]]
+ *   2. Calls [[CredentialProvider#resolve]] for each configured scheme
+ *   3. Serializes the resulting [[UserCredentials]] and invokes the 
propagation callback
+ *   4. Schedules renewal based on `min(identity token expiry, service 
credential expiry) -
+ *      safetyMargin`
+ *   5. Retries with exponential backoff on failure
+ *
+ * Started from `CoarseGrainedSchedulerBackend.start()` when

Review Comment:
   Nit: this cites `CoarseGrainedSchedulerBackend.start()` as the caller, but 
no such call site exists yet on this branch (this is a WIP subtask). It reads 
as accurate to someone holding the full SPIP context, but is misleading on 
`master` today. Consider softening to "intended to be started from ..." or 
deferring the claim to the subtask that adds the wiring.



##########
core/src/main/java/org/apache/spark/security/CredentialProviderLoader.java:
##########
@@ -221,10 +221,38 @@ private static List<CredentialProvider> loadProviders() {
     return result;
   }
 
+  /**
+   * Discovers all URI schemes supported by providers on the classpath.
+   * <p>
+   * This method queries all discovered {@link CredentialProvider} instances 
and collects
+   * their {@link CredentialProvider#supportedSchemes()} into a single set. 
Unlike
+   * {@link #providerFor(String, Map)}, this does not initialize providers or 
apply
+   * explicit selection rules -- it only reports what schemes are potentially 
available.
+   * <p>
+   * Intended for use by {@code UserCredentialManager} when no explicit scheme 
configuration
+   * (e.g., {@code spark.security.credentials.provider.<scheme>}) is provided.
+   *
+   * @param conf Spark configuration properties (used for potential future 
filtering)
+   * @return a set of all supported scheme names (lowercased), possibly empty
+   */
+  public static Set<String> discoverAllSchemes(Map<String, String> conf) {
+    List<CredentialProvider> providers = getProviders();
+    Set<String> schemes = new java.util.HashSet<>();
+    for (CredentialProvider provider : providers) {
+      Set<String> providerSchemes = provider.supportedSchemes();
+      if (providerSchemes != null) {
+        for (String s : providerSchemes) {
+          schemes.add(s.toLowerCase(Locale.ROOT));
+        }
+      }
+    }
+    return schemes;
+  }
+
   /**
    * Resets the cached provider list and initialization tracking. Intended for 
testing only.
    */
-  static void resetForTesting() {
+  public static void resetForTesting() {

Review Comment:
   Nit: `resetForTesting()` is widened from package-private to `public` here. 
This is needed because the suite lives in a different package 
(`o.a.s.deploy.security` vs this class's `o.a.s.security`), and it's defensible 
on a `@Private` class — but annotating it `@VisibleForTesting` (used elsewhere 
in core) would document that the widened visibility is for tests, not general 
use.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to