You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@polaris.apache.org by yu...@apache.org on 2026/09/04 23:17:18 UTC

(polaris) branch main updated: fix(auth): bind internal JWTs to principal secret generation (#5053)

This is an automated email from the ASF dual-hosted git repository.

flyrain pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/polaris.git


The following commit(s) were added to refs/heads/main by this push:
     new 8775ef417e fix(auth): bind internal JWTs to principal secret generation (#5053)
8775ef417e is described below

commit 8775ef417eece1dd7433d186775682be54d40f21
Author: vignesh_A <16...@users.noreply.github.com>
AuthorDate: Sat Sep 5 04:47:12 2026 +0530

    fix(auth): bind internal JWTs to principal secret generation (#5053)
---
 CHANGELOG.md                                       |   4 +
 .../java/org/apache/polaris/core/DigestUtils.java  |  12 +
 .../core/entity/PolarisPrincipalSecrets.java       |  88 +++++-
 .../org/apache/polaris/core/DigestUtilsTest.java   |  45 +++
 .../service/auth/internal/broker/JWTBroker.java    | 154 +++++++--
 .../InternalAuthenticationMechanismTest.java       |  15 +-
 .../broker/JWTBrokerCredentialsBindingTest.java    | 344 +++++++++++++++++++++
 .../broker/JWTSymmetricKeyGeneratorTest.java       |   3 +
 8 files changed, 624 insertions(+), 41 deletions(-)

diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5085cc7dc0..9a71874046 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -71,6 +71,7 @@ request adding CHANGELOG notes for breaking (!) changes and possibly other secti
   and a subsequent `bootstrap` would create a second, empty set of tables in the other schema.
   Either remove the setting from the URL, or point it at the schema that already holds your
   Polaris tables.
+- Internal JWTs minted before credentials-generation binding (tokens without the `polaris-cv` claim) can no longer be used as subject tokens in token exchange; they remain valid as bearer tokens until expiry. During a rolling upgrade, an old node may still mint claim-less tokens: exchanging such a token on any already-upgraded node fails with `invalid_grant`, so clients can see intermittent exchange failures until the last old node is gone; after that, rejection is consistent.
 
 ### New Features
 
@@ -148,6 +149,9 @@ request adding CHANGELOG notes for breaking (!) changes and possibly other secti
   directly under an allowed location, at `s3://b1/ns`, and rejected it as a custom location even
   though the request asked for none. The namespace location is now compared against the
   catalog's `default-base-location`, which is what it is derived from.
+- Internal JWTs are bound to principal secret generation via `polaris-cv` (no secret material in the
+  token). Credential-generation is enforced on token exchange; bearer verify is signature and claims
+  only. Secrets-load failures during exchange return service unavailable.
 
 ### Commits
 
diff --git a/polaris-core/src/main/java/org/apache/polaris/core/DigestUtils.java b/polaris-core/src/main/java/org/apache/polaris/core/DigestUtils.java
index 7b95628002..219b3e7033 100644
--- a/polaris-core/src/main/java/org/apache/polaris/core/DigestUtils.java
+++ b/polaris-core/src/main/java/org/apache/polaris/core/DigestUtils.java
@@ -20,6 +20,8 @@ package org.apache.polaris.core;
 
 import com.google.common.hash.Hashing;
 import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.Objects;
 
 public final class DigestUtils {
   private DigestUtils() {
@@ -29,4 +31,14 @@ public final class DigestUtils {
   public static String sha256Hex(String input) {
     return Hashing.sha256().hashString(input, StandardCharsets.UTF_8).toString();
   }
+
+  /**
+   * Constant-time equality check for secret material. Both arguments must be non-null; callers are
+   * expected to guard nullable inputs before comparing.
+   */
+  public static boolean constantTimeEquals(String a, String b) {
+    return MessageDigest.isEqual(
+        Objects.requireNonNull(a).getBytes(StandardCharsets.UTF_8),
+        Objects.requireNonNull(b).getBytes(StandardCharsets.UTF_8));
+  }
 }
diff --git a/polaris-core/src/main/java/org/apache/polaris/core/entity/PolarisPrincipalSecrets.java b/polaris-core/src/main/java/org/apache/polaris/core/entity/PolarisPrincipalSecrets.java
index f0d8128e5a..15d515adfd 100644
--- a/polaris-core/src/main/java/org/apache/polaris/core/entity/PolarisPrincipalSecrets.java
+++ b/polaris-core/src/main/java/org/apache/polaris/core/entity/PolarisPrincipalSecrets.java
@@ -21,6 +21,7 @@ package org.apache.polaris.core.entity;
 import com.fasterxml.jackson.annotation.JsonCreator;
 import com.fasterxml.jackson.annotation.JsonProperty;
 import java.security.SecureRandom;
+import java.util.Optional;
 import org.apache.polaris.core.DigestUtils;
 import org.jspecify.annotations.Nullable;
 
@@ -167,10 +168,45 @@ public class PolarisPrincipalSecrets {
     return principalClientId;
   }
 
+  /**
+   * @deprecated no longer used for authentication; kept for compatibility and will be removed in a
+   *     future release. Use {@link #getCredentialsVersionForSecret(String)} instead.
+   */
+  @Deprecated
   public boolean matchesSecret(String potentialSecret) {
+    return getCredentialsVersionForSecret(potentialSecret).isPresent();
+  }
+
+  /**
+   * Credentials-generation fingerprint corresponding to the secret that matches {@code
+   * potentialSecret}: the main generation when it matches the main secret hash, the secondary
+   * generation when it matches the secondary secret hash, or empty when it matches neither. Newly
+   * minted tokens carry this fingerprint in the {@code polaris-cv} claim. That claim gates
+   * <em>token-exchange</em> eligibility against the current (and secondary) generation; bearer
+   * verify checks only the JWT signature and claims, so a token remains usable as a bearer until
+   * JWT expiry even after its generation is no longer current.
+   *
+   * <p>Comparisons are constant-time, as in {@link #matchesCredentialsVersion(String)}.
+   */
+  public Optional<String> getCredentialsVersionForSecret(String potentialSecret) {
     String potentialSecretHash = hashSecret(potentialSecret);
-    return potentialSecretHash.equals(this.mainSecretHash)
-        || potentialSecretHash.equals(this.secondarySecretHash);
+    Optional<String> mainVersion = credentialsVersionForHash(mainSecretHash);
+    Optional<String> secondaryVersion = credentialsVersionForHash(secondarySecretHash);
+    // Always compare against both hashes and combine the flags, so the amount of comparison work
+    // does not reveal which generation matched.
+    boolean matchesMain =
+        mainSecretHash != null
+            && DigestUtils.constantTimeEquals(potentialSecretHash, mainSecretHash);
+    boolean matchesSecondary =
+        secondarySecretHash != null
+            && DigestUtils.constantTimeEquals(potentialSecretHash, secondarySecretHash);
+    if (matchesMain) {
+      return mainVersion;
+    }
+    if (matchesSecondary) {
+      return secondaryVersion;
+    }
+    return Optional.empty();
   }
 
   public String getMainSecret() {
@@ -185,6 +221,54 @@ public class PolarisPrincipalSecrets {
     return mainSecretHash;
   }
 
+  /**
+   * Credentials-generation fingerprint for tokens minted against the <em>current</em> main secret.
+   * Derived from existing fields with the principal's secret salt, so no schema change is required.
+   * The value is not itself a credential and is safe to embed in signed (but not encrypted) JWTs.
+   *
+   * @return the main credentials version; never {@code null} since the main secret hash is always
+   *     set by the constructors
+   */
+  public String getCredentialsVersion() {
+    return credentialsVersionForHash(mainSecretHash).orElseThrow();
+  }
+
+  /**
+   * Returns true when {@code credentialsVersion} matches the salted fingerprint of the current main
+   * secret hash <em>or</em> the secondary secret hash. After a single rotate, the previous main
+   * hash is kept as secondary so client secrets and bound JWTs both remain valid for that
+   * generation; a further rotate/reset advances secondary and invalidates the older fingerprint.
+   *
+   * <p>Comparisons are constant-time against each candidate fingerprint.
+   */
+  public boolean matchesCredentialsVersion(@Nullable String credentialsVersion) {
+    if (credentialsVersion == null || credentialsVersion.isEmpty()) {
+      return false;
+    }
+    boolean matches = false;
+    Optional<String> mainVersion = credentialsVersionForHash(mainSecretHash);
+    if (mainVersion.isPresent()) {
+      matches |= DigestUtils.constantTimeEquals(credentialsVersion, mainVersion.get());
+    }
+    Optional<String> secondaryVersion = credentialsVersionForHash(secondarySecretHash);
+    if (secondaryVersion.isPresent()) {
+      matches |= DigestUtils.constantTimeEquals(credentialsVersion, secondaryVersion.get());
+    }
+    return matches;
+  }
+
+  /**
+   * Salted, non-reversible fingerprint of a secret-verification hash for embedding in JWTs. Uses
+   * the same per-principal {@link #secretSalt} already stored for secret hashing, which is always
+   * set by the constructors.
+   */
+  private Optional<String> credentialsVersionForHash(@Nullable String secretHash) {
+    if (secretHash == null || secretHash.isEmpty()) {
+      return Optional.empty();
+    }
+    return Optional.of(DigestUtils.sha256Hex(secretHash + ":" + secretSalt));
+  }
+
   public String getSecondarySecretHash() {
     return secondarySecretHash;
   }
diff --git a/polaris-core/src/test/java/org/apache/polaris/core/DigestUtilsTest.java b/polaris-core/src/test/java/org/apache/polaris/core/DigestUtilsTest.java
new file mode 100644
index 0000000000..9b930363a7
--- /dev/null
+++ b/polaris-core/src/test/java/org/apache/polaris/core/DigestUtilsTest.java
@@ -0,0 +1,45 @@
+/*
+ * 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.polaris.core;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import org.junit.jupiter.api.Test;
+
+public class DigestUtilsTest {
+
+  @Test
+  void constantTimeEquals() {
+    assertThat(DigestUtils.constantTimeEquals("abc", "abc")).isTrue();
+    assertThat(DigestUtils.constantTimeEquals("abc", "abd")).isFalse();
+    assertThat(DigestUtils.constantTimeEquals("abc", "abcd")).isFalse();
+    assertThat(DigestUtils.constantTimeEquals("", "")).isTrue();
+  }
+
+  @Test
+  void constantTimeEqualsRejectsNull() {
+    assertThatThrownBy(() -> DigestUtils.constantTimeEquals(null, "a"))
+        .isInstanceOf(NullPointerException.class);
+    assertThatThrownBy(() -> DigestUtils.constantTimeEquals("a", null))
+        .isInstanceOf(NullPointerException.class);
+    assertThatThrownBy(() -> DigestUtils.constantTimeEquals(null, null))
+        .isInstanceOf(NullPointerException.class);
+  }
+}
diff --git a/runtime/service/src/main/java/org/apache/polaris/service/auth/internal/broker/JWTBroker.java b/runtime/service/src/main/java/org/apache/polaris/service/auth/internal/broker/JWTBroker.java
index f828894952..b4664fa306 100644
--- a/runtime/service/src/main/java/org/apache/polaris/service/auth/internal/broker/JWTBroker.java
+++ b/runtime/service/src/main/java/org/apache/polaris/service/auth/internal/broker/JWTBroker.java
@@ -22,6 +22,7 @@ import com.auth0.jwt.JWT;
 import com.auth0.jwt.algorithms.Algorithm;
 import com.auth0.jwt.interfaces.DecodedJWT;
 import com.auth0.jwt.interfaces.JWTVerifier;
+import com.google.common.annotations.VisibleForTesting;
 import java.time.Instant;
 import java.time.temporal.ChronoUnit;
 import java.util.Optional;
@@ -29,13 +30,16 @@ import java.util.Set;
 import java.util.UUID;
 import org.apache.iceberg.exceptions.NotAuthorizedException;
 import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.entity.PolarisPrincipalSecrets;
 import org.apache.polaris.core.entity.PrincipalEntity;
+import org.apache.polaris.core.exceptions.PolarisServiceUnavailableException;
 import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
 import org.apache.polaris.core.persistence.dao.entity.PrincipalSecretsResult;
 import org.apache.polaris.service.auth.DefaultAuthenticator;
 import org.apache.polaris.service.auth.PolarisCredential;
 import org.apache.polaris.service.auth.internal.service.OAuthError;
 import org.apache.polaris.service.types.TokenType;
+import org.jspecify.annotations.Nullable;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -49,6 +53,15 @@ public class JWTBroker implements TokenBroker {
   private static final String CLAIM_KEY_PRINCIPAL_ID = "principalId";
   private static final String CLAIM_KEY_SCOPE = "scope";
 
+  /**
+   * Credentials-generation fingerprint carried on newly minted tokens (see {@link
+   * PolarisPrincipalSecrets#getCredentialsVersion()}). When secrets are rotated or reset, the
+   * version changes and tokens carrying a prior value are rejected on <em>token exchange</em> only.
+   * Bearer verify checks only the JWT signature and claims, so those tokens remain usable as
+   * bearers until JWT expiry. The claim name is collision-resistant per RFC 7519.
+   */
+  @VisibleForTesting static final String CLAIM_KEY_CREDENTIALS_VERSION = "polaris-cv";
+
   private final PolarisMetaStoreManager metaStoreManager;
   private final PolarisCallContext polarisCallContext;
   private final int maxTokenGenerationInSeconds;
@@ -78,22 +91,51 @@ public class JWTBroker implements TokenBroker {
 
   @Override
   public PolarisCredential verify(String token) {
-    return verifyInternal(token);
+    return verifyInternal(token).token();
   }
 
-  private InternalPolarisToken verifyInternal(String token) {
+  private VerifiedToken verifyInternal(String token) {
+    // Bearer verify is signature + claims only — no metastore IO. Credential-generation binding is
+    // enforced on the token-exchange path. Token construction stays inside the try: a well-signed
+    // token that misses a mandatory claim must not surface as a raw NPE.
+    final DecodedJWT decodedJWT;
+    final InternalPolarisToken internalToken;
     try {
-      DecodedJWT decodedJWT = verifier.verify(token);
-      return InternalPolarisToken.of(
-          decodedJWT.getSubject(),
-          decodedJWT.getClaim(CLAIM_KEY_PRINCIPAL_ID).asLong(),
-          decodedJWT.getClaim(CLAIM_KEY_CLIENT_ID).asString(),
-          decodedJWT.getClaim(CLAIM_KEY_SCOPE).asString());
-
+      decodedJWT = verifier.verify(token);
+      internalToken =
+          InternalPolarisToken.of(
+              decodedJWT.getSubject(),
+              decodedJWT.getClaim(CLAIM_KEY_PRINCIPAL_ID).asLong(),
+              decodedJWT.getClaim(CLAIM_KEY_CLIENT_ID).asString(),
+              decodedJWT.getClaim(CLAIM_KEY_SCOPE).asString());
     } catch (Exception e) {
       throw (NotAuthorizedException)
           new NotAuthorizedException("Failed to verify the token").initCause(e);
     }
+    String credentialsVersion = decodedJWT.getClaim(CLAIM_KEY_CREDENTIALS_VERSION).asString();
+    return new VerifiedToken(internalToken, credentialsVersion);
+  }
+
+  /**
+   * Loads principal secrets and rejects a credentials-generation claim that is no longer current.
+   * Accepts the main or secondary generation fingerprint so dual-secret rotate grace matches
+   * client-secret matching. Used only on the token-exchange path.
+   */
+  private void requireCredentialsVersionCurrent(String clientId, String credentialsVersion) {
+    final PrincipalSecretsResult secretsResult;
+    try {
+      secretsResult = metaStoreManager.loadPrincipalSecrets(polarisCallContext, clientId);
+    } catch (RuntimeException e) {
+      // Transient backend failure must not look like bad credentials.
+      LOGGER.error("Unable to load principal secrets during token exchange", e);
+      throw new PolarisServiceUnavailableException(0, "Service unavailable");
+    }
+    if (!secretsResult.isSuccess() || secretsResult.getPrincipalSecrets() == null) {
+      throw new NotAuthorizedException("Failed to verify the token");
+    }
+    if (!secretsResult.getPrincipalSecrets().matchesCredentialsVersion(credentialsVersion)) {
+      throw new NotAuthorizedException("Failed to verify the token");
+    }
   }
 
   @Override
@@ -112,13 +154,28 @@ public class JWTBroker implements TokenBroker {
     if (subjectToken == null || subjectToken.isBlank()) {
       return TokenResponse.of(OAuthError.invalid_request);
     }
-    InternalPolarisToken decodedToken;
+    VerifiedToken verified;
     try {
-      decodedToken = verifyInternal(subjectToken);
+      verified = verifyInternal(subjectToken);
     } catch (NotAuthorizedException e) {
       LOGGER.error("Failed to verify the token", e.getCause());
       return TokenResponse.of(OAuthError.invalid_client);
     }
+    // Claim-less (pre-binding) tokens may still be used as bearer tokens until they expire, but
+    // exchange must not re-mint them onto the current credentials generation with a fresh
+    // lifetime; per RFC 6749 section 5.2 the subject grant is invalid in that case.
+    String credentialsVersion = verified.subjectCredentialsVersion();
+    if (credentialsVersion == null) {
+      return TokenResponse.of(OAuthError.invalid_grant);
+    }
+    try {
+      // Credential-generation binding is enforced only here (not on bearer verify).
+      requireCredentialsVersionCurrent(verified.token().getClientId(), credentialsVersion);
+    } catch (NotAuthorizedException e) {
+      LOGGER.error("Failed to validate credentials generation for token exchange", e.getCause());
+      return TokenResponse.of(OAuthError.invalid_client);
+    }
+    InternalPolarisToken decodedToken = verified.token();
     Optional<PrincipalEntity> principalLookup =
         metaStoreManager.findPrincipalById(polarisCallContext, decodedToken.getPrincipalId());
     if (principalLookup.isEmpty()) {
@@ -138,12 +195,15 @@ public class JWTBroker implements TokenBroker {
       }
       tokenScope = scope;
     }
+    // Preserve the subject token's credentials generation on the re-minted token so later exchanges
+    // keep checking the same generation fingerprint.
     String tokenString =
         generateTokenString(
             decodedToken.getPrincipalName(),
             decodedToken.getPrincipalId(),
             decodedToken.getClientId(),
-            tokenScope);
+            tokenScope,
+            credentialsVersion);
     return TokenResponse.of(
         tokenString, TokenType.ACCESS_TOKEN.getValue(), maxTokenGenerationInSeconds);
   }
@@ -163,30 +223,43 @@ public class JWTBroker implements TokenBroker {
       return TokenResponse.of(initialValidationResponse.get());
     }
 
-    Optional<PrincipalEntity> principal = findPrincipalEntity(clientId, clientSecret);
-    if (principal.isEmpty()) {
+    Optional<AuthenticatedPrincipal> authenticated =
+        authenticateWithClientSecrets(clientId, clientSecret);
+    if (authenticated.isEmpty()) {
       return TokenResponse.of(OAuthError.unauthorized_client);
     }
+    AuthenticatedPrincipal principal = authenticated.get();
     String tokenString =
-        generateTokenString(principal.get().getName(), principal.get().getId(), clientId, scope);
+        generateTokenString(
+            principal.entity().getName(),
+            principal.entity().getId(),
+            clientId,
+            scope,
+            principal.credentialsVersion());
     return TokenResponse.of(
         tokenString, TokenType.ACCESS_TOKEN.getValue(), maxTokenGenerationInSeconds);
   }
 
   private String generateTokenString(
-      String principalName, long principalId, String clientId, String scope) {
+      String principalName,
+      long principalId,
+      String clientId,
+      String scope,
+      String credentialsVersion) {
     Instant now = Instant.now();
-    return JWT.create()
-        .withIssuer(ISSUER_KEY)
-        .withSubject(principalName)
-        .withIssuedAt(now)
-        .withExpiresAt(now.plus(maxTokenGenerationInSeconds, ChronoUnit.SECONDS))
-        .withJWTId(UUID.randomUUID().toString())
-        .withClaim(CLAIM_KEY_ACTIVE, true)
-        .withClaim(CLAIM_KEY_CLIENT_ID, clientId)
-        .withClaim(CLAIM_KEY_PRINCIPAL_ID, principalId)
-        .withClaim(CLAIM_KEY_SCOPE, scopes(scope))
-        .sign(algorithm);
+    var builder =
+        JWT.create()
+            .withIssuer(ISSUER_KEY)
+            .withSubject(principalName)
+            .withIssuedAt(now)
+            .withExpiresAt(now.plus(maxTokenGenerationInSeconds, ChronoUnit.SECONDS))
+            .withJWTId(UUID.randomUUID().toString())
+            .withClaim(CLAIM_KEY_ACTIVE, true)
+            .withClaim(CLAIM_KEY_CLIENT_ID, clientId)
+            .withClaim(CLAIM_KEY_PRINCIPAL_ID, principalId)
+            .withClaim(CLAIM_KEY_SCOPE, scopes(scope))
+            .withClaim(CLAIM_KEY_CREDENTIALS_VERSION, credentialsVersion);
+    return builder.sign(algorithm);
   }
 
   @Override
@@ -203,17 +276,32 @@ public class JWTBroker implements TokenBroker {
     return scope == null || scope.isBlank() ? DefaultAuthenticator.PRINCIPAL_ROLE_ALL : scope;
   }
 
-  private Optional<PrincipalEntity> findPrincipalEntity(String clientId, String clientSecret) {
-    // Validate the principal is present and secrets match
+  private Optional<AuthenticatedPrincipal> authenticateWithClientSecrets(
+      String clientId, String clientSecret) {
     PrincipalSecretsResult principalSecrets =
         metaStoreManager.loadPrincipalSecrets(polarisCallContext, clientId);
-    if (!principalSecrets.isSuccess()) {
+    if (!principalSecrets.isSuccess() || principalSecrets.getPrincipalSecrets() == null) {
       return Optional.empty();
     }
-    if (!principalSecrets.getPrincipalSecrets().matchesSecret(clientSecret)) {
+    PolarisPrincipalSecrets secrets = principalSecrets.getPrincipalSecrets();
+    // Bind the token to the generation of the secret that actually matched, so a token minted
+    // with the secondary (pre-rotation) secret expires with that generation.
+    Optional<String> credentialsVersion = secrets.getCredentialsVersionForSecret(clientSecret);
+    if (credentialsVersion.isEmpty()) {
       return Optional.empty();
     }
-    return metaStoreManager.findPrincipalById(
-        polarisCallContext, principalSecrets.getPrincipalSecrets().getPrincipalId());
+    Optional<PrincipalEntity> principal =
+        metaStoreManager.findPrincipalById(polarisCallContext, secrets.getPrincipalId());
+    return principal.map(p -> new AuthenticatedPrincipal(p, credentialsVersion.get()));
   }
+
+  private record AuthenticatedPrincipal(PrincipalEntity entity, String credentialsVersion) {}
+
+  /**
+   * Result of JWT verification (signature + claims only). {@code subjectCredentialsVersion} is the
+   * token's credentials-generation claim, or {@code null} for legacy tokens without it. Binding is
+   * enforced later on the exchange path.
+   */
+  private record VerifiedToken(
+      InternalPolarisToken token, @Nullable String subjectCredentialsVersion) {}
 }
diff --git a/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/InternalAuthenticationMechanismTest.java b/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/InternalAuthenticationMechanismTest.java
index 447e28e5c9..379b575a9a 100644
--- a/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/InternalAuthenticationMechanismTest.java
+++ b/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/InternalAuthenticationMechanismTest.java
@@ -31,6 +31,7 @@ import io.quarkus.security.identity.IdentityProviderManager;
 import io.quarkus.security.identity.SecurityIdentity;
 import io.smallrye.mutiny.Uni;
 import io.vertx.ext.web.RoutingContext;
+import java.time.Duration;
 import org.apache.iceberg.exceptions.NotAuthorizedException;
 import org.apache.polaris.service.auth.AuthenticationRealmConfiguration;
 import org.apache.polaris.service.auth.AuthenticationType;
@@ -43,6 +44,8 @@ import org.junit.jupiter.params.provider.CsvSource;
 
 public class InternalAuthenticationMechanismTest {
 
+  private static final Duration AWAIT_TIMEOUT = Duration.ofSeconds(5);
+
   private InternalAuthenticationMechanism mechanism;
   private AuthenticationRealmConfiguration configuration;
   private TokenBroker tokenBroker;
@@ -80,7 +83,7 @@ public class InternalAuthenticationMechanismTest {
 
     Uni<SecurityIdentity> result = mechanism.authenticate(routingContext, identityProviderManager);
 
-    assertThat(result.await().indefinitely()).isNull();
+    assertThat(result.await().atMost(AWAIT_TIMEOUT)).isNull();
     verify(tokenBroker, never()).verify(any());
   }
 
@@ -92,7 +95,7 @@ public class InternalAuthenticationMechanismTest {
 
     Uni<SecurityIdentity> result = mechanism.authenticate(routingContext, identityProviderManager);
 
-    assertThat(result.await().indefinitely()).isNull();
+    assertThat(result.await().atMost(AWAIT_TIMEOUT)).isNull();
     verify(tokenBroker, never()).verify(any());
   }
 
@@ -104,7 +107,7 @@ public class InternalAuthenticationMechanismTest {
 
     Uni<SecurityIdentity> result = mechanism.authenticate(routingContext, identityProviderManager);
 
-    assertThat(result.await().indefinitely()).isNull();
+    assertThat(result.await().atMost(AWAIT_TIMEOUT)).isNull();
     verify(tokenBroker, never()).verify(any());
   }
 
@@ -123,7 +126,7 @@ public class InternalAuthenticationMechanismTest {
 
     Uni<SecurityIdentity> result = mechanism.authenticate(routingContext, identityProviderManager);
 
-    assertThatThrownBy(() -> result.await().indefinitely())
+    assertThatThrownBy(() -> result.await().atMost(AWAIT_TIMEOUT))
         .isInstanceOf(AuthenticationFailedException.class)
         .hasCause(cause);
     verify(tokenBroker).verify("invalidToken");
@@ -145,7 +148,7 @@ public class InternalAuthenticationMechanismTest {
 
     Uni<SecurityIdentity> result = mechanism.authenticate(routingContext, identityProviderManager);
 
-    assertThat(result.await().indefinitely()).isNull();
+    assertThat(result.await().atMost(AWAIT_TIMEOUT)).isNull();
     verify(tokenBroker).verify("invalidToken");
     verify(identityProviderManager, never()).authenticate(any(InternalAuthenticationRequest.class));
   }
@@ -165,7 +168,7 @@ public class InternalAuthenticationMechanismTest {
 
     Uni<SecurityIdentity> result = mechanism.authenticate(routingContext, identityProviderManager);
 
-    assertThat(result.await().indefinitely()).isSameAs(securityIdentity);
+    assertThat(result.await().atMost(AWAIT_TIMEOUT)).isSameAs(securityIdentity);
     verify(tokenBroker).verify("validToken");
     verify(identityProviderManager).authenticate(any(InternalAuthenticationRequest.class));
   }
diff --git a/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/broker/JWTBrokerCredentialsBindingTest.java b/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/broker/JWTBrokerCredentialsBindingTest.java
new file mode 100644
index 0000000000..d5e8d79217
--- /dev/null
+++ b/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/broker/JWTBrokerCredentialsBindingTest.java
@@ -0,0 +1,344 @@
+/*
+ * 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.polaris.service.auth.internal.broker;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.algorithms.Algorithm;
+import com.auth0.jwt.interfaces.DecodedJWT;
+import java.util.Optional;
+import org.apache.polaris.core.DigestUtils;
+import org.apache.polaris.core.PolarisCallContext;
+import org.apache.polaris.core.entity.PolarisPrincipalSecrets;
+import org.apache.polaris.core.entity.PrincipalEntity;
+import org.apache.polaris.core.exceptions.PolarisServiceUnavailableException;
+import org.apache.polaris.core.persistence.PolarisMetaStoreManager;
+import org.apache.polaris.core.persistence.dao.entity.PrincipalSecretsResult;
+import org.apache.polaris.service.auth.internal.service.OAuthError;
+import org.apache.polaris.service.types.TokenType;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+/**
+ * Credential-generation binding ({@code polaris-cv}) is enforced on token exchange only. Bearer
+ * verify is signature + claims only: stale-generation and claim-less tokens still verify until
+ * expiry by design. Exchange rejects claim-less and stale-generation subject tokens.
+ */
+public class JWTBrokerCredentialsBindingTest {
+
+  private static final long PRINCIPAL_ID = 99L;
+  private static final String CLIENT_ID = "client-abc";
+  private static final String MAIN_SECRET = "main-secret-value";
+  private static final String SECONDARY_SECRET = "secondary-secret-value";
+  private static final String SCOPE = "PRINCIPAL_ROLE:ALL";
+
+  private PolarisCallContext callContext;
+  private PolarisMetaStoreManager metaStore;
+  private Algorithm algorithm;
+  private JWTBroker broker;
+  private PolarisPrincipalSecrets secrets;
+
+  @BeforeEach
+  void setUp() {
+    callContext = Mockito.mock(PolarisCallContext.class);
+    metaStore = Mockito.mock(PolarisMetaStoreManager.class);
+    algorithm = Algorithm.HMAC256("test-hmac-key");
+    secrets = new PolarisPrincipalSecrets(PRINCIPAL_ID, CLIENT_ID, MAIN_SECRET, SECONDARY_SECRET);
+    broker =
+        new JWTBroker(metaStore, callContext, 3600, algorithm, JWTBroker.buildVerifier(algorithm));
+
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+    when(metaStore.findPrincipalById(callContext, PRINCIPAL_ID))
+        .thenReturn(
+            Optional.of(
+                new PrincipalEntity.Builder().setId(PRINCIPAL_ID).setName("alice").build()));
+  }
+
+  @Test
+  void mintedTokenCarriesSaltedCredentialsVersion() {
+    TokenResponse response =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            MAIN_SECRET,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(response.getError()).isNull();
+    DecodedJWT jwt = JWT.decode(response.getAccessToken());
+    String claim = jwt.getClaim(JWTBroker.CLAIM_KEY_CREDENTIALS_VERSION).asString();
+    assertThat(claim).isEqualTo(secrets.getCredentialsVersion());
+    // Must not expose the raw secret-verification hash, nor an unsalted hash of it.
+    assertThat(claim).isNotEqualTo(secrets.getMainSecretHash());
+    assertThat(claim).isNotEqualTo(DigestUtils.sha256Hex(secrets.getMainSecretHash()));
+    assertThat(secrets.matchesCredentialsVersion(claim)).isTrue();
+  }
+
+  @Test
+  void verifySucceedsForTokenBoundToCurrentSecrets() {
+    TokenResponse response =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            MAIN_SECRET,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    Mockito.clearInvocations(metaStore);
+
+    assertThat(broker.verify(response.getAccessToken()).getPrincipalId()).isEqualTo(PRINCIPAL_ID);
+    // Bearer verify is signature/claims only — no secrets load on the hot path.
+    verify(metaStore, never()).loadPrincipalSecrets(callContext, CLIENT_ID);
+  }
+
+  @Test
+  void verifyAcceptsStaleGenerationBearerTokenUntilExpiry() {
+    // Intended: after credentials advance past the token's generation, bearer verify still
+    // succeeds until expiry. Only exchange rejects. Do not "fix" this back to verify-time
+    // rejection.
+    TokenResponse response =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            MAIN_SECRET,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    String accessToken = response.getAccessToken();
+
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+
+    assertThat(broker.verify(accessToken).getPrincipalId()).isEqualTo(PRINCIPAL_ID);
+  }
+
+  @Test
+  void tokenExchangeFailsAfterSecondRotate() {
+    TokenResponse original =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            MAIN_SECRET,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+
+    TokenResponse exchanged =
+        broker.generateFromToken(
+            TokenType.ACCESS_TOKEN,
+            original.getAccessToken(),
+            TokenRequestValidator.TOKEN_EXCHANGE,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(exchanged.getError()).isEqualTo(OAuthError.invalid_client);
+  }
+
+  @Test
+  void tokenExchangeSucceedsAfterOneRotate() {
+    TokenResponse original =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            MAIN_SECRET,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+    Mockito.clearInvocations(metaStore);
+
+    TokenResponse exchanged =
+        broker.generateFromToken(
+            TokenType.ACCESS_TOKEN,
+            original.getAccessToken(),
+            TokenRequestValidator.TOKEN_EXCHANGE,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(exchanged.getError()).isNull();
+    // Re-minted token keeps the subject token's generation (secondary grace), not the new main.
+    String originalClaim =
+        JWT.decode(original.getAccessToken())
+            .getClaim(JWTBroker.CLAIM_KEY_CREDENTIALS_VERSION)
+            .asString();
+    assertThat(
+            JWT.decode(exchanged.getAccessToken())
+                .getClaim(JWTBroker.CLAIM_KEY_CREDENTIALS_VERSION)
+                .asString())
+        .isEqualTo(originalClaim)
+        .isNotEqualTo(secrets.getCredentialsVersion());
+    // Secrets load happens once on the exchange path (not during bearer verify).
+    verify(metaStore, Mockito.times(1)).loadPrincipalSecrets(callContext, CLIENT_ID);
+  }
+
+  @Test
+  void legacyTokenExchangeIsRejected() {
+    // Claim-less tokens must not be re-minted via exchange onto the current generation.
+    TokenResponse exchanged =
+        broker.generateFromToken(
+            TokenType.ACCESS_TOKEN,
+            legacyToken(),
+            TokenRequestValidator.TOKEN_EXCHANGE,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(exchanged.getError()).isEqualTo(OAuthError.invalid_grant);
+  }
+
+  @Test
+  void verifyAcceptsLegacyTokenWithoutCredentialsVersionClaim() {
+    // Intended upgrade soft-landing: claim-less bearers verify until expiry; exchange rejects.
+    String legacy = legacyToken();
+    assertThat(broker.verify(legacy).getPrincipalId()).isEqualTo(PRINCIPAL_ID);
+    verify(metaStore, never()).loadPrincipalSecrets(callContext, CLIENT_ID);
+  }
+
+  @Test
+  void legacyTokenWithoutClaimIsNotBoundByRotateOnVerify() {
+    String legacy = legacyToken();
+
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+
+    assertThat(broker.verify(legacy).getPrincipalId()).isEqualTo(PRINCIPAL_ID);
+  }
+
+  @Test
+  void tokenExchangeSurfacesPersistenceFailureAsServiceUnavailable() {
+    TokenResponse original =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            MAIN_SECRET,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(original.getError()).isNull();
+
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenThrow(new RuntimeException("simulated metastore outage"));
+
+    assertThatThrownBy(
+            () ->
+                broker.generateFromToken(
+                    TokenType.ACCESS_TOKEN,
+                    original.getAccessToken(),
+                    TokenRequestValidator.TOKEN_EXCHANGE,
+                    SCOPE,
+                    TokenType.ACCESS_TOKEN))
+        .isInstanceOfSatisfying(
+            PolarisServiceUnavailableException.class,
+            e -> {
+              assertThat(e.getMessage()).isEqualTo("Service unavailable");
+              assertThat(e.getRetryAfterSeconds()).isZero();
+            });
+  }
+
+  @Test
+  void newTokenAfterRotateUsesNewMainVersion() {
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    String newMain = secrets.getMainSecret();
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+
+    TokenResponse after =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            newMain,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(after.getError()).isNull();
+    assertThat(
+            JWT.decode(after.getAccessToken())
+                .getClaim(JWTBroker.CLAIM_KEY_CREDENTIALS_VERSION)
+                .asString())
+        .isEqualTo(secrets.getCredentialsVersion());
+    assertThat(broker.verify(after.getAccessToken()).getPrincipalId()).isEqualTo(PRINCIPAL_ID);
+  }
+
+  @Test
+  void tokenMintedWithSecondarySecretKeepsSecondaryGenerationOnExchangeUntilDropped() {
+    // After one rotate, the previous main secret still authenticates via secondary grace.
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+
+    TokenResponse response =
+        broker.generateFromClientSecrets(
+            CLIENT_ID,
+            MAIN_SECRET,
+            TokenRequestValidator.CLIENT_CREDENTIALS,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(response.getError()).isNull();
+    String claim =
+        JWT.decode(response.getAccessToken())
+            .getClaim(JWTBroker.CLAIM_KEY_CREDENTIALS_VERSION)
+            .asString();
+    assertThat(claim).isNotEqualTo(secrets.getCredentialsVersion());
+    assertThat(secrets.matchesCredentialsVersion(claim)).isTrue();
+    // Bearer verify does not consult secrets generation.
+    assertThat(broker.verify(response.getAccessToken()).getPrincipalId()).isEqualTo(PRINCIPAL_ID);
+
+    // Exchange still succeeds while secondary grace holds.
+    TokenResponse exchangedWhileGrace =
+        broker.generateFromToken(
+            TokenType.ACCESS_TOKEN,
+            response.getAccessToken(),
+            TokenRequestValidator.TOKEN_EXCHANGE,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(exchangedWhileGrace.getError()).isNull();
+
+    // A second rotate drops the secondary generation: bearer verify still passes; exchange fails.
+    secrets.rotateSecrets(secrets.getMainSecretHash());
+    when(metaStore.loadPrincipalSecrets(callContext, CLIENT_ID))
+        .thenReturn(new PrincipalSecretsResult(secrets));
+    assertThat(broker.verify(response.getAccessToken()).getPrincipalId()).isEqualTo(PRINCIPAL_ID);
+    TokenResponse exchangedAfterDrop =
+        broker.generateFromToken(
+            TokenType.ACCESS_TOKEN,
+            response.getAccessToken(),
+            TokenRequestValidator.TOKEN_EXCHANGE,
+            SCOPE,
+            TokenType.ACCESS_TOKEN);
+    assertThat(exchangedAfterDrop.getError()).isEqualTo(OAuthError.invalid_client);
+  }
+
+  private String legacyToken() {
+    return JWT.create()
+        .withIssuer("polaris")
+        .withSubject("alice")
+        .withClaim("active", true)
+        .withClaim("client_id", CLIENT_ID)
+        .withClaim("principalId", PRINCIPAL_ID)
+        .withClaim("scope", SCOPE)
+        .sign(algorithm);
+  }
+}
diff --git a/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/broker/JWTSymmetricKeyGeneratorTest.java b/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/broker/JWTSymmetricKeyGeneratorTest.java
index 5ec26b77bb..41083bda66 100644
--- a/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/broker/JWTSymmetricKeyGeneratorTest.java
+++ b/runtime/service/src/test/java/org/apache/polaris/service/auth/internal/broker/JWTSymmetricKeyGeneratorTest.java
@@ -78,6 +78,9 @@ public class JWTSymmetricKeyGeneratorTest {
     assertThat(token.getExpiresIn()).isEqualTo(666);
     assertThat(decodedJWT.getClaim("scope").asString()).isEqualTo("PRINCIPAL_ROLE:TEST");
     assertThat(decodedJWT.getClaim("client_id").asString()).isEqualTo(clientId);
+    assertThat(decodedJWT.getClaim(JWTBroker.CLAIM_KEY_CREDENTIALS_VERSION).asString())
+        .isEqualTo(principalSecrets.getCredentialsVersion());
+    assertThat(generator.verify(token.getAccessToken()).getPrincipalId()).isEqualTo(principalId);
   }
 
   @Test