-
Notifications
You must be signed in to change notification settings - Fork 35
Refresh service account tokens #154 #271
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
phani0207
wants to merge
1
commit into
jgroups-extras:main
Choose a base branch
from
phani0207:main
base: main
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
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
50 changes: 50 additions & 0 deletions
50
src/main/java/org/jgroups/protocols/kubernetes/stream/TokenProvider.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,50 @@ | ||
| package org.jgroups.protocols.kubernetes.stream; | ||
|
|
||
| import mjson.Json; | ||
|
|
||
| import java.io.IOException; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.util.Base64; | ||
| import java.util.logging.Logger; | ||
|
|
||
| import static org.jgroups.protocols.kubernetes.Utils.readFileToString; | ||
|
|
||
| public class TokenProvider | ||
| { | ||
| private static final Logger log = Logger.getLogger(TokenProvider.class.getName()); | ||
| private final String tokenFile; | ||
| private volatile long tokenExpiry; | ||
| private volatile String token; | ||
|
|
||
| public TokenProvider(String tokenFile) { | ||
| this.tokenFile = tokenFile; | ||
| } | ||
|
|
||
| public String getToken() throws IOException { | ||
| long currentTime = System.currentTimeMillis() / 1000; | ||
| if (token == null || (tokenExpiry > 0 && tokenExpiry < currentTime)) { | ||
| synchronized (this) { | ||
| if (token == null || (tokenExpiry > 0 && tokenExpiry < currentTime)) { | ||
| log.info("Refreshing token from file " + tokenFile); | ||
| token = readFileToString(tokenFile).trim(); | ||
| tokenExpiry = getExpiry(token); | ||
| } | ||
| } | ||
| } | ||
| return token; | ||
| } | ||
|
|
||
| static long getExpiry(String jwtToken) throws IOException { | ||
| try { | ||
| String[] parts = jwtToken.split("\\."); | ||
| if (parts.length < 2) throw new IOException("Invalid JWT token"); | ||
| String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); | ||
| Json payload = Json.read(payloadJson); | ||
| if (payload.has("exp")) return payload.at("exp").asLong(); | ||
| log.info("No 'exp' claim found."); | ||
| } catch (Exception e) { | ||
| throw new IOException("Error decoding JWT: " + e.getMessage()); | ||
| } | ||
| return -1; | ||
| } | ||
| } | ||
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
112 changes: 112 additions & 0 deletions
112
src/test/java/org/jgroups/protocols/kubernetes/stream/TokenProviderTest.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,112 @@ | ||
| package org.jgroups.protocols.kubernetes.stream; | ||
|
|
||
| import mjson.Json; | ||
| import org.junit.Before; | ||
| import org.junit.Test; | ||
|
|
||
| import java.io.File; | ||
| import java.io.IOException; | ||
| import java.net.URISyntaxException; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.Files; | ||
| import java.util.Base64; | ||
|
|
||
| import static org.jgroups.protocols.kubernetes.Utils.readFileToString; | ||
| import static org.junit.Assert.*; | ||
|
|
||
| public class TokenProviderTest | ||
| { | ||
| private static final String JWT_PREFIX = "eyJhbGciOiJIUzI1NiJ9."; | ||
| private String validJwtWithExpiry; | ||
| private String validJwtWithoutExpiry; | ||
| private static final String INVALID_JWT = "invalid.jwt.token"; | ||
| private File tempTokenFile; | ||
| private TokenProvider tokenProvider; | ||
|
|
||
| @Before | ||
| public void setUp() throws IOException, URISyntaxException { | ||
| validJwtWithExpiry = readFileToString(new File(TokenProvider.class.getResource("/tokenWithExpiry.txt").toURI())); | ||
| validJwtWithoutExpiry = readFileToString(new File(TokenProvider.class.getResource("/tokenWithoutExpiry.txt").toURI())); | ||
| tempTokenFile = File.createTempFile("token", ".txt"); | ||
| tempTokenFile.deleteOnExit(); | ||
| tokenProvider = new TokenProvider(tempTokenFile.getAbsolutePath()); | ||
| } | ||
|
|
||
| @Test | ||
| public void returnsTokenWhenFileContainsValidJWT() throws IOException { | ||
| Files.writeString(tempTokenFile.toPath(), validJwtWithExpiry); | ||
| String token = tokenProvider.getToken(); | ||
| assertEquals(validJwtWithExpiry, token); | ||
| } | ||
|
|
||
| @Test | ||
| public void throwsIOExceptionWhenFileContainsInvalidJWT() throws IOException { | ||
| Files.writeString(tempTokenFile.toPath(), INVALID_JWT); | ||
| assertThrows(IOException.class, () -> tokenProvider.getToken()); | ||
| } | ||
|
|
||
| @Test | ||
| public void returnsSameTokenIfNotExpired() throws IOException { | ||
| Files.writeString(tempTokenFile.toPath(), validJwtWithExpiry); | ||
| String token1 = tokenProvider.getToken(); | ||
| String token2 = tokenProvider.getToken(); | ||
| assertEquals(token1, token2); | ||
| } | ||
|
|
||
| @Test | ||
| public void refreshesTokenWhenExpired() throws IOException, InterruptedException { | ||
| Files.writeString(tempTokenFile.toPath(), validJwtWithExpiry); | ||
| updateTokenExpiryInFile(tempTokenFile, (System.currentTimeMillis() + 1000) / 1000); // Set expiry in the past | ||
| String token1 = tokenProvider.getToken(); | ||
| Thread.sleep(2000L); | ||
| updateTokenExpiryInFile(tempTokenFile, (System.currentTimeMillis() + 1000) / 1000); // Set expiry in the past | ||
| String toekn2 = tokenProvider.getToken(); | ||
| assertNotEquals(token1, toekn2); | ||
| } | ||
|
|
||
| @Test | ||
| public void throwsIOExceptionForInvalidJWTExpiry() { | ||
| assertThrows(IOException.class, () -> TokenProvider.getExpiry(INVALID_JWT)); | ||
| } | ||
|
|
||
| @Test | ||
| public void returnsExpiryForValidJWT() throws IOException { | ||
| Files.writeString(tempTokenFile.toPath(), validJwtWithExpiry); | ||
| long tokenExpiry = (System.currentTimeMillis() + 10000) / 1000; | ||
| updateTokenExpiryInFile(tempTokenFile, tokenExpiry); // JWT 'exp' is in seconds | ||
| long expiry = TokenProvider.getExpiry(tokenProvider.getToken()); | ||
| assertEquals(tokenExpiry, expiry); | ||
| } | ||
|
|
||
| @Test | ||
| public void returnsMinusOneForJWTWithoutExpiry() throws IOException { | ||
| Files.writeString(tempTokenFile.toPath(), validJwtWithoutExpiry); | ||
| long expiry = TokenProvider.getExpiry(tokenProvider.getToken()); | ||
| assertEquals(-1, expiry); | ||
| } | ||
|
|
||
| public static void updateTokenExpiryInFile(File tokenFile, long newExpiry) throws IOException { | ||
| String token = Files.readString(tokenFile.toPath()).trim(); | ||
| String[] parts = token.split("\\."); | ||
| if (parts.length < 3) throw new IOException("Invalid JWT token format"); | ||
|
|
||
| // Decode payload | ||
| String payloadJson = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); | ||
| Json payload = Json.read(payloadJson); | ||
|
|
||
| // Update expiry | ||
| payload.set("exp", newExpiry); | ||
|
|
||
| // Re-encode payload | ||
| String newPayload = Base64.getUrlEncoder().withoutPadding() | ||
| .encodeToString(payload.toString().getBytes(StandardCharsets.UTF_8)); | ||
|
|
||
| // Reconstruct token | ||
| String newToken = parts[0] + "." + newPayload + "." + parts[2]; | ||
|
|
||
| // Save to file | ||
| Files.write(tokenFile.toPath(), newToken.getBytes(StandardCharsets.UTF_8)); | ||
| } | ||
|
|
||
| } | ||
|
|
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 @@ | ||
| eyJhbGciOiJSUzI1NiIsImtpZCI6ImQyNWM2ZjQyODRhMTZlNzA0N2JkOWEwMWNmOWIxNGFkOWFmNWY3NzUifQ.eyJhdWQiOlsiaHR0cHM6Ly9rdWJlcm5ldGVzLmRlZmF1bHQuc3ZjIl0sImV4cCI6MTc5MjY1ODc5MywiaWF0IjoxNzYxMTIyNzkzLCJpc3MiOiJodHRwczovL29pZGMuZWtzLnVzLXdlc3QtMi5hbWF6b25hd3MuY29tL2lkLzFDMEU0M0U4QUZBOTI2RDg4REUyMUJCMUI5QkU3QzlCIiwianRpIjoiMjkwNjViNWItYTg4ZC00ZGE2LWJhNjktZGRjYzA2OTdiZGQ1Iiwia3ViZXJuZXRlcy5pbyI6eyJuYW1lc3BhY2UiOiJjYWktcWEtbWwiLCJub2RlIjp7Im5hbWUiOiJpcC0xMC0yMC0yMDQtMjkudXMtd2VzdC0yLmNvbXB1dGUuaW50ZXJuYWwiLCJ1aWQiOiJkMzE5ZmYwYi03YjAxLTQxYWMtOWMxYS1hODc2NmNmMzFjYWMifSwicG9kIjp7Im5hbWUiOiJhcHBsaWNhdGlvbi1pbnRlZ3JhdGlvbi1vYm0tMCIsInVpZCI6IjNiNjM3MjBhLTc1YTctNDllNS1iOTFhLTZmNTZhNjJhZDJjMiJ9LCJzZXJ2aWNlYWNjb3VudCI6eyJuYW1lIjoiY2Fpc2VydmljZS1zZXJ2aWNlLWFjY291bnQiLCJ1aWQiOiJkMzE1MWE1My1mODk4LTQ5MTMtYjczNC00MTU1ZmY0MWY0NjAifSwid2FybmFmdGVyIjoxNzYxMTI2NDAwfSwibmJmIjoxNzYxMTIyNzkzLCJzdWIiOiJzeXN0ZW06c2VydmljZWFjY291bnQ6Y2FpLXFhLW1sOmNhaXNlcnZpY2Utc2VydmljZS1hY2NvdW50In0.dW2Ekvy9ltpmLGHrE7JrS7F4VE2lqdY2PtKiQqdbca9ED7s7njq9QnP8STolxT7z3MNlee7ayZC2RGIoz_Hs84dKncQZDvxmVgHTgWI9ohaA2tFLUWBfEwx1WTGrlN6pL_DN_7kJlxZkAQeTAmmCPTYI6-mFyqZ9sjCuavzVvQBJ5cH7sqRg7R8FQDMaq45GF-G8I2QfWg7Pqz298F8AU8891AtxTh5K2jawFoWBqcp5BieozNgmdR76amktcL45AxvKj1nW5zW53zSEPRVxUgYoEq8r6rnRGULRW2mqohpFLS-ZbPfRJZM9FPpRA4LYNX_84tlaKdUqB8t4BjQfTQa |
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 @@ | ||
| eyJhbGciOiJSUzI1NiIsImtpZCI6IlJIeHZ6Z1d5NWFiekhLakFGczBwYjlxemNIdjdhWVN5S0ZfdTF3czFENVkifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJjYWktcHJvZC1hemNhYzIiLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlY3JldC5uYW1lIjoiY2FpLXNlcnZpY2UtYWNjb3VudC1rdWJlcGluZyIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50Lm5hbWUiOiJjYWktc2VydmljZS1hY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQudWlkIjoiOTEwYzk5OTMtOTZmMS00OTQ4LTk2OWMtM2ZiNjZmNDk4NDRmIiwic3ViIjoic3lzdGVtOnNlcnZpY2VhY2NvdW50OmNhaS1wcm9kLWF6Y2FjMjpjYWktc2VydmljZS1hY2NvdW50In0.Ko3nOwk-aumtdCMomNcunV_7GD1_gK2pbR1L9IKRsfs_0srgzc3UyqNL-XrbdFhuy-VHF708299ArjSpUzhkdaD1zx1PvoHzMLS5ivgTPfnhSYrAmBOSFTFQjgUZzndDkxHcxwDhq3x7yRZsizKJ5V000cgHT5JGPWEpGmwPQkY4GsaT5ZLv324ZxtggUHoqXWeYYWciZKERenVtz1V5TJofEpmmau7fitb2iM5DnpJH_W6KYaEzQozDBqJ-EhaWjQn8bFJgi08N_ZA_qDOsCtNwIphrLPiUnmLS6F2TU_584njNawBE_vrcJL82J7M2f2g6eroE_DeEoDMmd9d77ZCF3Zy94fW_9x_CFF242g2EbD6yLGNZXvsNrf0qA6-DMA2Ihft6QxeNJX9ETDDroJ6IPUc13Zq_SmZdqLeCCwAQpajBbCCyU6ih8xsyxa1Os_bjmTdT2OUGQ8FBIkmJfTFnmMCrqsd60CZ--cPY9OGBmloJbZ3OEDNWPmb75pTulIgAy1b79bzco3y4qSiWeQ1-WI6hNaogf-sIVlkm1Q7Sh0IczlalJGcqIHbkFjYezY3ZR6PnjUKjGXDqqDpFMwjGo-F-tNwt3AgPjEJD0LdhUBFtnsW5T38RQIYFEuHyJT4YHKOCQ3iSDMyb1EY_sm3qnj6vEnjdRh_jthat3e8 |
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.
@phani0207 This is relying on the fact that the system clock time is in sync between the pod and the k8s control plane and that the token is updated in time on the pod. I am assuming this is normally handled by refreshing the token early or leeway on the server – none of which seem to be an option here.
Any chance you have given some thought to this? I am wondering whether we need to retry a 401 to address this situation.
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.
Ok to give some background, we use KUBE_PING in our production for cluster discovery and communication. This started failing when we migrated to k8s on azure as azure refreshes the token every hour. In aws we never faced the issue as the token expiry is 1 year and we restart the pod before the token expires. We have this code currently deployed in our environment as we could not wait for this commit.
Retry already happens at the Utils.openStream call. So even if a call fails intermittently. it will recover in the next attempt. The responsibility of refreshing the token is with the k8s service and client does not have any control on that. As far as clock sync is concerned, I am not sure if there is a way we can handle it.
When considering the implementation, I also considered relying on the token file modified time, but it did not feel logical. Hence went with the current approach.
As far as I have investigated, there is a buffer of 7 secs on the azure before the token expires.
Uh oh!
There was an error while loading. Please reload this page.
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.
Cool stuff @phani0207 Out of curiosity, is this within WildFly or Infinispan or something else? Since I will be back-porting this to older branches.
Right, good point, the retry there is 1 second (controlled by KUBERNETES_OPERATION_SLEEP) and attempts is 3 (KUBERNETES_OPERATION_ATTEMPTS) so that might address majority of time skew well enough.
Right, that's what I meant by 'none of which seem to be an option here.'; I should have been more clear.
I was thinking about that too but I wonder how reliable that is across different implementors/vendors.
OK so there appears to be some leeway in this case.
So I think this all checks!
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.
@rhusar Neither. We use jgroups as a TPL and have logic for cluster initialization and communication in multiple microservices in our deployment.