Skip to content

Commit

Permalink
fix(java-sdk): fix token validity check for expiry (#282)
Browse files Browse the repository at this point in the history
  • Loading branch information
rhamzeh authored Jan 25, 2024
2 parents 899ebaf + e03a16d commit 7a066a1
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
4 changes: 4 additions & 0 deletions config/clients/java/config.overrides.json
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,10 @@
"destinationFilename": "src/main/java/dev/openfga/sdk/api/auth/AccessToken.java",
"templateType": "SupportingFiles"
},
"creds-AccessTokenTest.java.mustache" : {
"destinationFilename": "src/test/java/dev/openfga/sdk/api/auth/AccessTokenTest.java",
"templateType": "SupportingFiles"
},
"creds-CredentialsFlowRequest.java.mustache" : {
"destinationFilename": "src/main/java/dev/openfga/sdk/api/auth/CredentialsFlowRequest.java",
"templateType": "SupportingFiles"
Expand Down
6 changes: 3 additions & 3 deletions config/clients/java/template/creds-AccessToken.java.mustache
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ class AccessToken {
public boolean isValid() {
return !isNullOrWhitespace(token)
&& (expiresAt == null
|| expiresAt.isBefore(Instant.now()
.plusSeconds(TOKEN_EXPIRY_BUFFER_THRESHOLD_IN_SEC)
.plusSeconds(random.nextLong() % TOKEN_EXPIRY_JITTER_IN_SEC)));
|| expiresAt.isAfter(Instant.now()
.minusSeconds(TOKEN_EXPIRY_BUFFER_THRESHOLD_IN_SEC)
.minusSeconds(random.nextLong() % TOKEN_EXPIRY_JITTER_IN_SEC)));
}

public String getToken() {
Expand Down
34 changes: 34 additions & 0 deletions config/clients/java/template/creds-AccessTokenTest.java.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{{>licenseInfo}}
package {{authPackage}};

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;

class AccessTokenTest {
private static Stream<Arguments> expTimeAndResults() {
return Stream.of(
Arguments.of(Instant.now().plus(1, ChronoUnit.HOURS), true),
Arguments.of(Instant.now().minus(1, ChronoUnit.HOURS), false),
Arguments.of(Instant.now().minus(10, ChronoUnit.MINUTES), false),
Arguments.of(Instant.now().plus(10, ChronoUnit.MINUTES), true),
Arguments.of(Instant.now(), true)
);
}

@MethodSource("expTimeAndResults")
@ParameterizedTest
public void testTokenValid(Instant exp, boolean valid) {
AccessToken accessToken = new AccessToken();
accessToken.setToken("token");
accessToken.setExpiresAt(exp);
assertEquals(valid, accessToken.isValid());
}
}

0 comments on commit 7a066a1

Please sign in to comment.