-
Notifications
You must be signed in to change notification settings - Fork 4k
Implement gRFC A97: xDS JWT Call Credentials #12951
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
khush2520
wants to merge
10
commits into
grpc:master
Choose a base branch
from
khush2520:a97-revised
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6bc5e3e
Implement Core JWT Call Credentials (Task 1)
khush2520 86b77fb
Implement xDS Bootstrap Parsing and Transport Integration (Task 2)
khush2520 c97e6b5
Implement Integration Verification (Task 3)
khush2520 e5863c6
Add gson in bazel BUILD
khush2520 3a6229c
Fix JwtTokenFileCallCredentials BACKOFF cache and imports
khush2520 be8f911
Make enableXdsBootstrapCallCreds public and fix jwt_token_file refere…
khush2520 c048696
Make enableXdsBootstrapCallCreds public and fix jwt_token_file refere…
khush2520 e934d90
Merge branch 'a97-revised' of github.com:khush2520/grpc-java-retro in…
khush2520 b7a25c0
Update auth/src/main/java/io/grpc/auth/JwtTokenFileCallCredentials.java
khush2520 c9803c2
Address Gemini review: bounded file read & JsonParser null check
khush2520 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
336 changes: 336 additions & 0 deletions
336
auth/src/main/java/io/grpc/auth/JwtTokenFileCallCredentials.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,336 @@ | ||
| /* | ||
| * Copyright 2026 The gRPC Authors | ||
| * | ||
| * Licensed 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 io.grpc.auth; | ||
|
|
||
| import static com.google.common.base.Preconditions.checkNotNull; | ||
|
|
||
| import com.google.common.annotations.VisibleForTesting; | ||
| import com.google.common.io.BaseEncoding; | ||
| import com.google.gson.JsonElement; | ||
| import com.google.gson.JsonObject; | ||
| import com.google.gson.JsonParser; | ||
| import com.google.gson.JsonSyntaxException; | ||
| import io.grpc.CallCredentials; | ||
| import io.grpc.Metadata; | ||
| import io.grpc.SecurityLevel; | ||
| import io.grpc.Status; | ||
| import java.io.File; | ||
| import java.io.FileInputStream; | ||
| import java.io.IOException; | ||
| import java.io.InputStream; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.concurrent.Executor; | ||
| import java.util.concurrent.RejectedExecutionException; | ||
| import java.util.logging.Level; | ||
| import java.util.logging.Logger; | ||
|
|
||
| /** | ||
| * A {@link CallCredentials} implementation that loads a JWT token from a file, | ||
| * parses it to extract its expiration time, and caches/refreshes it. | ||
| */ | ||
| public final class JwtTokenFileCallCredentials extends CallCredentials { | ||
|
|
||
| private static final Logger log = Logger.getLogger(JwtTokenFileCallCredentials.class.getName()); | ||
|
|
||
| private static final Metadata.Key<String> AUTHORIZATION_HEADER = | ||
| Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER); | ||
|
|
||
| private static final long INITIAL_BACKOFF_MS = 1000; | ||
| private static final long MAX_BACKOFF_MS = 60000; | ||
| private static final double BACKOFF_MULTIPLIER = 2.0; | ||
|
|
||
| private final String filePath; | ||
| private final TimeProvider timeProvider; | ||
| private final Object lock = new Object(); | ||
|
|
||
| private enum ReadState { | ||
| IDLE, | ||
| READING, | ||
| BACKOFF | ||
| } | ||
|
|
||
| private String cachedToken; | ||
| private long expirationTimeMillis; | ||
| private ReadState readState = ReadState.IDLE; | ||
| private Status lastReadFailureStatus; | ||
| private long currentBackoffMs; | ||
| private long nextAttemptTimeMillis; | ||
| private final List<MetadataApplier> queuedAppliers = new ArrayList<>(); | ||
|
|
||
| interface TimeProvider { | ||
| long currentTimeMillis(); | ||
| } | ||
|
|
||
| private static final TimeProvider SYSTEM_TIME_PROVIDER = new TimeProvider() { | ||
| @Override | ||
| public long currentTimeMillis() { | ||
| return System.currentTimeMillis(); | ||
| } | ||
| }; | ||
|
|
||
| public JwtTokenFileCallCredentials(String filePath) { | ||
| this(filePath, SYSTEM_TIME_PROVIDER); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| JwtTokenFileCallCredentials(String filePath, TimeProvider timeProvider) { | ||
| this.filePath = checkNotNull(filePath, "filePath"); | ||
| this.timeProvider = checkNotNull(timeProvider, "timeProvider"); | ||
| } | ||
|
|
||
| @Override | ||
| public void applyRequestMetadata( | ||
| RequestInfo requestInfo, Executor appExecutor, MetadataApplier applier) { | ||
| checkNotNull(requestInfo, "requestInfo"); | ||
| checkNotNull(appExecutor, "appExecutor"); | ||
| checkNotNull(applier, "applier"); | ||
|
|
||
| if (requestInfo.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY) { | ||
| applier.fail(Status.UNAUTHENTICATED | ||
| .withDescription("Channel security level is not PRIVACY_AND_INTEGRITY")); | ||
| return; | ||
| } | ||
|
|
||
| long now = timeProvider.currentTimeMillis(); | ||
| TokenInfo tokenToApply = null; | ||
| boolean triggerRead = false; | ||
| Status failStatus = null; | ||
|
|
||
| synchronized (lock) { | ||
| if (readState == ReadState.BACKOFF && now >= nextAttemptTimeMillis) { | ||
| readState = ReadState.IDLE; | ||
| } | ||
|
|
||
| boolean hasValidCache = cachedToken != null && now < expirationTimeMillis; | ||
| boolean expiringSoon = hasValidCache && (expirationTimeMillis - now <= 60000); | ||
|
|
||
| if (hasValidCache) { | ||
| tokenToApply = new TokenInfo(cachedToken, expirationTimeMillis); | ||
| if (expiringSoon && readState == ReadState.IDLE) { | ||
| readState = ReadState.READING; | ||
| triggerRead = true; | ||
| } | ||
| } else { | ||
| if (readState == ReadState.BACKOFF) { | ||
| failStatus = lastReadFailureStatus != null ? lastReadFailureStatus : Status.UNAVAILABLE; | ||
| } else { | ||
| if (readState == ReadState.IDLE) { | ||
| readState = ReadState.READING; | ||
| triggerRead = true; | ||
| } | ||
| queuedAppliers.add(applier); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (failStatus != null) { | ||
| applier.fail(failStatus); | ||
| return; | ||
| } | ||
|
|
||
| if (tokenToApply != null) { | ||
| Metadata headers = new Metadata(); | ||
| headers.put(AUTHORIZATION_HEADER, "Bearer " + tokenToApply.token); | ||
| applier.apply(headers); | ||
| } | ||
|
|
||
| if (triggerRead) { | ||
| try { | ||
| appExecutor.execute(new Runnable() { | ||
| @Override | ||
| public void run() { | ||
| loadToken(); | ||
| } | ||
| }); | ||
| } catch (RejectedExecutionException e) { | ||
| handleExecutorRejection(e, tokenToApply != null); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private void handleExecutorRejection( | ||
| RejectedExecutionException e, boolean isBackgroundReload) { | ||
| log.log(Level.WARNING, "Executor rejected token read task", e); | ||
| List<MetadataApplier> appliersToFail = new ArrayList<>(); | ||
| synchronized (lock) { | ||
| readState = ReadState.IDLE; | ||
| if (!isBackgroundReload) { | ||
| appliersToFail.addAll(queuedAppliers); | ||
| queuedAppliers.clear(); | ||
| } | ||
| } | ||
| for (MetadataApplier applier : appliersToFail) { | ||
| try { | ||
| applier.fail(Status.UNAVAILABLE | ||
| .withDescription("Executor rejected token read task") | ||
| .withCause(e)); | ||
| } catch (Throwable t) { | ||
| log.log(Level.WARNING, "Error calling fail on applier", t); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private void loadToken() { | ||
| TokenInfo tokenInfo = null; | ||
| Status status = null; | ||
| try { | ||
| tokenInfo = readAndParseTokenFile(); | ||
| } catch (IOException e) { | ||
| status = Status.UNAVAILABLE | ||
| .withDescription("Failed to read token file") | ||
| .withCause(e); | ||
| } catch (IllegalArgumentException e) { | ||
| status = Status.UNAUTHENTICATED | ||
| .withDescription("Malformed token or invalid claims") | ||
| .withCause(e); | ||
| } catch (Throwable e) { | ||
| status = Status.UNAVAILABLE | ||
| .withDescription("Unexpected error loading token") | ||
| .withCause(e); | ||
| } | ||
|
|
||
| List<MetadataApplier> appliersToApply = new ArrayList<>(); | ||
| List<MetadataApplier> appliersToFail = new ArrayList<>(); | ||
|
|
||
| synchronized (lock) { | ||
| if (status == null) { | ||
| cachedToken = tokenInfo.token; | ||
| expirationTimeMillis = tokenInfo.expirationTimeMillis; | ||
| readState = ReadState.IDLE; | ||
| lastReadFailureStatus = null; | ||
| currentBackoffMs = 0; | ||
| nextAttemptTimeMillis = 0; | ||
|
|
||
| appliersToApply.addAll(queuedAppliers); | ||
| queuedAppliers.clear(); | ||
| } else { | ||
| lastReadFailureStatus = status; | ||
| readState = ReadState.BACKOFF; | ||
|
|
||
| if (currentBackoffMs == 0) { | ||
| currentBackoffMs = INITIAL_BACKOFF_MS; | ||
| } else { | ||
| currentBackoffMs = Math.min( | ||
| (long) (currentBackoffMs * BACKOFF_MULTIPLIER), MAX_BACKOFF_MS); | ||
| } | ||
| nextAttemptTimeMillis = timeProvider.currentTimeMillis() + currentBackoffMs; | ||
|
|
||
| appliersToFail.addAll(queuedAppliers); | ||
| queuedAppliers.clear(); | ||
| } | ||
| } | ||
|
|
||
| if (status == null) { | ||
| Metadata headers = new Metadata(); | ||
| headers.put(AUTHORIZATION_HEADER, "Bearer " + tokenInfo.token); | ||
| for (MetadataApplier applier : appliersToApply) { | ||
| try { | ||
| applier.apply(headers); | ||
| } catch (Throwable t) { | ||
| log.log(Level.WARNING, "Error applying credentials", t); | ||
| } | ||
| } | ||
| } else { | ||
| log.log(Level.WARNING, "Failed to load token: " + status.getDescription(), status.getCause()); | ||
| for (MetadataApplier applier : appliersToFail) { | ||
| try { | ||
| applier.fail(status); | ||
| } catch (Throwable t) { | ||
| log.log(Level.WARNING, "Error calling fail on applier", t); | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private TokenInfo readAndParseTokenFile() throws IOException { | ||
| File file = new File(filePath); | ||
| long length = file.length(); | ||
| if (length > 1048576) { | ||
| throw new IOException("File size exceeds 1 MB limit: " + length); | ||
| } | ||
| byte[] bytes; | ||
| try (InputStream in = new FileInputStream(file)) { | ||
| bytes = com.google.common.io.ByteStreams.toByteArray( | ||
| com.google.common.io.ByteStreams.limit(in, 1048577)); | ||
| } | ||
| if (bytes.length > 1048576) { | ||
| throw new IOException("File size exceeds 1 MB limit: " + bytes.length); | ||
| } | ||
|
khush2520 marked this conversation as resolved.
|
||
| String token = new String(bytes, StandardCharsets.UTF_8).trim(); | ||
| if (token.isEmpty()) { | ||
| throw new IllegalArgumentException("Token file is empty"); | ||
| } | ||
| String[] segments = token.split("\\.", -1); | ||
| if (segments.length != 3) { | ||
| throw new IllegalArgumentException("JWT must have 3 segments"); | ||
| } | ||
| byte[] payloadBytes; | ||
| try { | ||
| payloadBytes = BaseEncoding.base64Url() | ||
| .omitPadding().decode(segments[1]); | ||
| } catch (IllegalArgumentException e) { | ||
| throw new IllegalArgumentException("Invalid Base64URL encoding in payload", e); | ||
| } | ||
| String payloadJson = new String(payloadBytes, StandardCharsets.UTF_8); | ||
| JsonObject jsonObject; | ||
| try { | ||
| JsonElement jsonElement = JsonParser.parseString(payloadJson); | ||
| if (jsonElement == null || !jsonElement.isJsonObject()) { | ||
| throw new IllegalArgumentException("Payload is not a JSON object"); | ||
| } | ||
|
khush2520 marked this conversation as resolved.
|
||
| jsonObject = jsonElement.getAsJsonObject(); | ||
| } catch (JsonSyntaxException e) { | ||
| throw new IllegalArgumentException("Invalid JSON payload", e); | ||
| } | ||
| if (!jsonObject.has("exp")) { | ||
| throw new IllegalArgumentException("Payload does not contain 'exp' claim"); | ||
| } | ||
| JsonElement expElement = jsonObject.get("exp"); | ||
| if (!expElement.isJsonPrimitive() || !expElement.getAsJsonPrimitive().isNumber()) { | ||
| throw new IllegalArgumentException("'exp' claim is not a number"); | ||
| } | ||
| long expSeconds = expElement.getAsLong(); | ||
| if (expSeconds <= 0) { | ||
| throw new IllegalArgumentException("Invalid 'exp' claim value: " + expSeconds); | ||
| } | ||
| long expirationTimeMillis; | ||
| if (expSeconds > Long.MAX_VALUE / 1000) { | ||
| expirationTimeMillis = Long.MAX_VALUE; | ||
| } else { | ||
| expirationTimeMillis = (expSeconds - 30) * 1000; | ||
| } | ||
| return new TokenInfo(token, expirationTimeMillis); | ||
|
khush2520 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| @Override | ||
| @SuppressWarnings("deprecation") | ||
| public void thisUsesUnstableApi() { | ||
| // Yes | ||
| } | ||
|
|
||
| private static class TokenInfo { | ||
| final String token; | ||
| final long expirationTimeMillis; | ||
|
|
||
| TokenInfo(String token, long expirationTimeMillis) { | ||
| this.token = token; | ||
| this.expirationTimeMillis = expirationTimeMillis; | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical Bug: Valid cached token is ignored and requests fail during backoff
When a background refresh fails (e.g., due to a transient file read error), the credential enters the
BACKOFFstate. Under the current implementation, any request made during the backoff window will fail immediately becausereadState == ReadState.BACKOFFis checked first and causes an immediate failure, completely ignoring the fact that a perfectly valid cached token still exists incachedToken.This can cause severe availability issues where healthy, unexpired tokens are not used simply because a background refresh attempt failed.
We should check if a valid cache exists first. If it does, we should always use it and only trigger/skip background refreshes based on the backoff state. If no valid cache exists, only then should we fail-fast during the backoff window.