From aba5ed1f121a154ff2bd7700b02d0103cf8a2b36 Mon Sep 17 00:00:00 2001 From: atakavci Date: Mon, 10 Mar 2025 11:14:31 +0300 Subject: [PATCH] switch to revelc formatter and format code --- core/pom.xml | 15 +- .../authentication/core/IdentityProvider.java | 2 +- .../authentication/core/RenewalScheduler.java | 3 +- .../authentication/core/SimpleToken.java | 3 +- .../authentication/core/TokenAuthConfig.java | 12 +- .../authentication/core/TokenListener.java | 2 +- .../authentication/core/TokenManager.java | 6 +- .../core/TokenRequestException.java | 3 +- .../CoreAuthenticationUnitTests.java | 404 +++++++++--------- entraid/pom.xml | 15 +- .../entraid/AzureIdentityProvider.java | 9 +- .../entraid/AzureTokenAuthConfigBuilder.java | 17 +- .../entraid/EntraIDIdentityProvider.java | 28 +- .../EntraIDIdentityProviderConfig.java | 3 +- .../EntraIDTokenAuthConfigBuilder.java | 28 +- .../entraid/ManagedIdentityInfo.java | 6 +- .../entraid/ServicePrincipalInfo.java | 3 +- ...AzureIdentityProviderIntegrationTests.java | 34 +- .../AzureIdentityProviderUnitTests.java | 33 +- .../EntraIDIntegrationTests.java | 36 +- .../authentication/EntraIDUnitTests.java | 117 +++-- .../clients/authentication/TestContext.java | 9 +- hbase-formatter.xml | 20 +- 23 files changed, 381 insertions(+), 427 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 843b73d..ce822fb 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -193,12 +193,19 @@ - com.googlecode.maven-java-formatter-plugin - maven-java-formatter-plugin - 0.4 + net.revelc.code.formatter + formatter-maven-plugin + 2.16.0 - ${project.basedir}/hbase-formatter.xml + ${project.basedir}/../hbase-formatter.xml + + + + validate + + + maven-jar-plugin diff --git a/core/src/main/java/redis/clients/authentication/core/IdentityProvider.java b/core/src/main/java/redis/clients/authentication/core/IdentityProvider.java index be9717d..ac37036 100644 --- a/core/src/main/java/redis/clients/authentication/core/IdentityProvider.java +++ b/core/src/main/java/redis/clients/authentication/core/IdentityProvider.java @@ -7,6 +7,6 @@ package redis.clients.authentication.core; public interface IdentityProvider { - + Token requestToken(); } \ No newline at end of file diff --git a/core/src/main/java/redis/clients/authentication/core/RenewalScheduler.java b/core/src/main/java/redis/clients/authentication/core/RenewalScheduler.java index e42a5ad..f2ecd0c 100644 --- a/core/src/main/java/redis/clients/authentication/core/RenewalScheduler.java +++ b/core/src/main/java/redis/clients/authentication/core/RenewalScheduler.java @@ -33,8 +33,7 @@ public RenewalScheduler(Supplier renewToken) { */ public RenewalTask scheduleNext(long delay) { // Schedule the task to run after the given delay - lastTask = new RenewalTask( - scheduler.schedule(() -> renewToken.get(), delay, TimeUnit.MILLISECONDS)); + lastTask = new RenewalTask(scheduler.schedule(() -> renewToken.get(), delay, TimeUnit.MILLISECONDS)); return lastTask; } diff --git a/core/src/main/java/redis/clients/authentication/core/SimpleToken.java b/core/src/main/java/redis/clients/authentication/core/SimpleToken.java index e9ae58a..432dfe5 100644 --- a/core/src/main/java/redis/clients/authentication/core/SimpleToken.java +++ b/core/src/main/java/redis/clients/authentication/core/SimpleToken.java @@ -16,8 +16,7 @@ public class SimpleToken implements Token { private long receivedAt; private Map claims; - public SimpleToken(String user, String value, long expiresAt, long receivedAt, - Map claims) { + public SimpleToken(String user, String value, long expiresAt, long receivedAt, Map claims) { this.user = user; this.value = value; this.expiresAt = expiresAt; diff --git a/core/src/main/java/redis/clients/authentication/core/TokenAuthConfig.java b/core/src/main/java/redis/clients/authentication/core/TokenAuthConfig.java index 9fed55c..1c282e6 100644 --- a/core/src/main/java/redis/clients/authentication/core/TokenAuthConfig.java +++ b/core/src/main/java/redis/clients/authentication/core/TokenAuthConfig.java @@ -11,8 +11,7 @@ public class TokenAuthConfig { private TokenManagerConfig tokenManagerConfig; private IdentityProviderConfig identityProviderConfig; - public TokenAuthConfig(TokenManagerConfig tokenManagerConfig, - IdentityProviderConfig identityProviderConfig) { + public TokenAuthConfig(TokenManagerConfig tokenManagerConfig, IdentityProviderConfig identityProviderConfig) { this.tokenManagerConfig = tokenManagerConfig; this.identityProviderConfig = identityProviderConfig; } @@ -68,9 +67,9 @@ public T identityProviderConfig(IdentityProviderConfig identityProviderConfig) { } public TokenAuthConfig build() { - return new TokenAuthConfig(new TokenManagerConfig(expirationRefreshRatio, - lowerRefreshBoundMillis, tokenRequestExecTimeoutInMs, - new TokenManagerConfig.RetryPolicy(maxAttemptsToRetry, delayInMsToRetry)), + return new TokenAuthConfig( + new TokenManagerConfig(expirationRefreshRatio, lowerRefreshBoundMillis, tokenRequestExecTimeoutInMs, + new TokenManagerConfig.RetryPolicy(maxAttemptsToRetry, delayInMsToRetry)), identityProviderConfig); } @@ -78,8 +77,7 @@ public static Builder from(Builder sample) { return new Builder().expirationRefreshRatio(sample.expirationRefreshRatio) .lowerRefreshBoundMillis(sample.lowerRefreshBoundMillis) .tokenRequestExecTimeoutInMs(sample.tokenRequestExecTimeoutInMs) - .maxAttemptsToRetry(sample.maxAttemptsToRetry) - .delayInMsToRetry(sample.delayInMsToRetry) + .maxAttemptsToRetry(sample.maxAttemptsToRetry).delayInMsToRetry(sample.delayInMsToRetry) .identityProviderConfig(sample.identityProviderConfig); } } diff --git a/core/src/main/java/redis/clients/authentication/core/TokenListener.java b/core/src/main/java/redis/clients/authentication/core/TokenListener.java index 9ea8c75..07ba014 100644 --- a/core/src/main/java/redis/clients/authentication/core/TokenListener.java +++ b/core/src/main/java/redis/clients/authentication/core/TokenListener.java @@ -7,7 +7,7 @@ package redis.clients.authentication.core; public interface TokenListener { - + void onTokenRenewed(Token newToken); void onError(Exception reason); diff --git a/core/src/main/java/redis/clients/authentication/core/TokenManager.java b/core/src/main/java/redis/clients/authentication/core/TokenManager.java index 1966207..26bc81e 100644 --- a/core/src/main/java/redis/clients/authentication/core/TokenManager.java +++ b/core/src/main/java/redis/clients/authentication/core/TokenManager.java @@ -28,8 +28,7 @@ public TokenManager(IdentityProvider identityProvider, TokenManagerConfig tokenM maxRetries = tokenManagerConfig.getRetryPolicy().getMaxAttempts(); retryDelay = tokenManagerConfig.getRetryPolicy().getdelayInMs(); renewalScheduler = new RenewalScheduler(this::renewToken); - dispatcher = new Dispatcher(identityProvider, - tokenManagerConfig.getTokenRequestExecTimeoutInMs()); + dispatcher = new Dispatcher(identityProvider, tokenManagerConfig.getTokenRequestExecTimeoutInMs()); } /** @@ -158,8 +157,7 @@ protected long ttlForLowerRefresh(long expireDate) { */ protected long ttlForRatioRefresh(long expireDate, long issueDate) { long totalLifetime = expireDate - issueDate; - long intendedUsageDuration = (long) (totalLifetime - * tokenManagerConfig.getExpirationRefreshRatio()); + long intendedUsageDuration = (long) (totalLifetime * tokenManagerConfig.getExpirationRefreshRatio()); long startOfRenewalZone = issueDate + intendedUsageDuration; return startOfRenewalZone - System.currentTimeMillis(); // TTL to renewal zone } diff --git a/core/src/main/java/redis/clients/authentication/core/TokenRequestException.java b/core/src/main/java/redis/clients/authentication/core/TokenRequestException.java index 14b9f13..cd1c74d 100644 --- a/core/src/main/java/redis/clients/authentication/core/TokenRequestException.java +++ b/core/src/main/java/redis/clients/authentication/core/TokenRequestException.java @@ -24,8 +24,7 @@ private static String getMessage(Exception identityProviderFailedWith) { if (identityProviderFailedWith == null) { return msg; } - return msg + " Identity provider request failed!" - + identityProviderFailedWith.getMessage(); + return msg + " Identity provider request failed!" + identityProviderFailedWith.getMessage(); } } diff --git a/core/src/test/java/redis/clients/authentication/CoreAuthenticationUnitTests.java b/core/src/test/java/redis/clients/authentication/CoreAuthenticationUnitTests.java index aacc2f0..f193717 100644 --- a/core/src/test/java/redis/clients/authentication/CoreAuthenticationUnitTests.java +++ b/core/src/test/java/redis/clients/authentication/CoreAuthenticationUnitTests.java @@ -41,225 +41,223 @@ public class CoreAuthenticationUnitTests { - public static class TokenManagerConfigWrapper extends TokenManagerConfig { - int lower; - float ratio; - - public TokenManagerConfigWrapper() { - super(0, 0, 0, null); + public static class TokenManagerConfigWrapper extends TokenManagerConfig { + int lower; + float ratio; + + public TokenManagerConfigWrapper() { + super(0, 0, 0, null); + } + + @Override + public int getLowerRefreshBoundMillis() { + return lower; + } + + @Override + public float getExpirationRefreshRatio() { + return ratio; + } + + @Override + public RetryPolicy getRetryPolicy() { + return new RetryPolicy(1, 1); + } } - @Override - public int getLowerRefreshBoundMillis() { - return lower; - } + @Test + public void testCalculateRenewalDelay() { + long delay = 0; + long duration = 0; + long issueDate; + long expireDate; - @Override - public float getExpirationRefreshRatio() { - return ratio; - } + TokenManagerConfigWrapper config = new TokenManagerConfigWrapper(); + TokenManager manager = new TokenManager(() -> null, config); + + duration = 5000; + config.lower = 2000; + config.ratio = 0.5F; + issueDate = System.currentTimeMillis(); + expireDate = issueDate + duration; + + delay = manager.calculateRenewalDelay(expireDate, issueDate); + + assertThat(delay, + Matchers.greaterThanOrEqualTo(Math.min(duration - config.lower, (long) (duration * config.ratio)))); + + duration = 10000; + config.lower = 8000; + config.ratio = 0.2F; + issueDate = System.currentTimeMillis(); + expireDate = issueDate + duration; + + delay = manager.calculateRenewalDelay(expireDate, issueDate); + + assertThat(delay, + Matchers.greaterThanOrEqualTo(Math.min(duration - config.lower, (long) (duration * config.ratio)))); + + duration = 10000; + config.lower = 10000; + config.ratio = 0.2F; + issueDate = System.currentTimeMillis(); + expireDate = issueDate + duration; + + delay = manager.calculateRenewalDelay(expireDate, issueDate); + + assertEquals(0, delay); + + duration = 0; + config.lower = 5000; + config.ratio = 0.2F; + issueDate = System.currentTimeMillis(); + expireDate = issueDate + duration; + + delay = manager.calculateRenewalDelay(expireDate, issueDate); + + assertEquals(0, delay); - @Override - public RetryPolicy getRetryPolicy() { - return new RetryPolicy(1, 1); + duration = 10000; + config.lower = 1000; + config.ratio = 0.00001F; + issueDate = System.currentTimeMillis(); + expireDate = issueDate + duration; + + delay = manager.calculateRenewalDelay(expireDate, issueDate); + + assertEquals(0, delay); + + duration = 10000; + config.lower = 1000; + config.ratio = 0.0001F; + issueDate = System.currentTimeMillis(); + expireDate = issueDate + duration; + + delay = manager.calculateRenewalDelay(expireDate, issueDate); + + assertThat(delay, either(is(0L)).or(is(1L))); } - } - @Test - public void testCalculateRenewalDelay() { - long delay = 0; - long duration = 0; - long issueDate; - long expireDate; + @Test + public void testTokenManagerStart() throws InterruptedException, ExecutionException, TimeoutException { + + IdentityProvider identityProvider = () -> new SimpleToken("user1", "tokenVal", + System.currentTimeMillis() + 5 * 1000, System.currentTimeMillis(), null); + + TokenManager tokenManager = new TokenManager(identityProvider, + new TokenManagerConfig(0.7F, 200, 2000, new RetryPolicy(1, 1))); - TokenManagerConfigWrapper config = new TokenManagerConfigWrapper(); - TokenManager manager = new TokenManager(() -> null, config); + TokenListener listener = mock(TokenListener.class); + final Token[] tokenHolder = new Token[1]; + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + tokenHolder[0] = (Token) args[0]; + return null; + }).when(listener).onTokenRenewed(any()); - duration = 5000; - config.lower = 2000; - config.ratio = 0.5F; - issueDate = System.currentTimeMillis(); - expireDate = issueDate + duration; + tokenManager.start(listener, true); + assertEquals(tokenHolder[0].getValue(), "tokenVal"); + } + + @Test + public void testBlockForInitialToken() { + IdentityProvider identityProvider = () -> { + throw new RuntimeException("Test exception from identity provider!"); + }; - delay = manager.calculateRenewalDelay(expireDate, issueDate); + TokenManager tokenManager = new TokenManager(identityProvider, + new TokenManagerConfig(0.7F, 200, 2000, new TokenManagerConfig.RetryPolicy(5, 100))); - assertThat(delay, Matchers - .greaterThanOrEqualTo(Math.min(duration - config.lower, (long) (duration * config.ratio)))); + TokenRequestException e = assertThrows(TokenRequestException.class, + () -> tokenManager.start(mock(TokenListener.class), true)); - duration = 10000; - config.lower = 8000; - config.ratio = 0.2F; - issueDate = System.currentTimeMillis(); - expireDate = issueDate + duration; + assertEquals("Test exception from identity provider!", e.getCause().getMessage()); + } - delay = manager.calculateRenewalDelay(expireDate, issueDate); + @Test + public void testNoBlockForInitialToken() throws InterruptedException, ExecutionException, TimeoutException { + int numberOfRetries = 5; + CountDownLatch requesLatch = new CountDownLatch(numberOfRetries); + IdentityProvider identityProvider = () -> { + requesLatch.countDown(); + throw new RuntimeException("Test exception from identity provider!"); + }; - assertThat(delay, Matchers - .greaterThanOrEqualTo(Math.min(duration - config.lower, (long) (duration * config.ratio)))); + TokenManager tokenManager = new TokenManager(identityProvider, + new TokenManagerConfig(0.7F, 200, 2000, new TokenManagerConfig.RetryPolicy(numberOfRetries - 1, 100))); - duration = 10000; - config.lower = 10000; - config.ratio = 0.2F; - issueDate = System.currentTimeMillis(); - expireDate = issueDate + duration; + TokenListener listener = mock(TokenListener.class); + tokenManager.start(listener, false); - delay = manager.calculateRenewalDelay(expireDate, issueDate); + requesLatch.await(); + verify(listener, atLeastOnce()).onError(any()); + verify(listener, never()).onTokenRenewed(any()); + } - assertEquals(0, delay); - - duration = 0; - config.lower = 5000; - config.ratio = 0.2F; - issueDate = System.currentTimeMillis(); - expireDate = issueDate + duration; - - delay = manager.calculateRenewalDelay(expireDate, issueDate); - - assertEquals(0, delay); + @Test + public void testTokenManagerWithFailingTokenRequest() + throws InterruptedException, ExecutionException, TimeoutException { + int numberOfRetries = 5; + CountDownLatch requesLatch = new CountDownLatch(numberOfRetries); + + IdentityProvider identityProvider = mock(IdentityProvider.class); + when(identityProvider.requestToken()).thenAnswer(invocation -> { + requesLatch.countDown(); + if (requesLatch.getCount() > 0) { + throw new RuntimeException("Test exception from identity provider!"); + } + return new SimpleToken("user1", "tokenValX", System.currentTimeMillis() + 50 * 1000, + System.currentTimeMillis(), null); + }); + + ArgumentCaptor argument = ArgumentCaptor.forClass(Token.class); + + TokenManager tokenManager = new TokenManager(identityProvider, + new TokenManagerConfig(0.7F, 200, 2000, new TokenManagerConfig.RetryPolicy(numberOfRetries - 1, 100))); + + TokenListener listener = mock(TokenListener.class); + tokenManager.start(listener, false); + requesLatch.await(); + verify(identityProvider, times(numberOfRetries)).requestToken(); + verify(listener, never()).onError(any()); + verify(listener).onTokenRenewed(argument.capture()); + assertEquals("tokenValX", argument.getValue().getValue()); + } + + @Test + public void testTokenManagerWithHangingTokenRequest() + throws InterruptedException, ExecutionException, TimeoutException { + int delayDuration = 200; + int executionTimeout = 100; + int tokenLifetime = 50 * 1000; + int numberOfRetries = 5; + CountDownLatch requesLatch = new CountDownLatch(numberOfRetries); + + IdentityProvider identityProvider = () -> { + requesLatch.countDown(); + if (requesLatch.getCount() > 0) { + delay(delayDuration); + } + return new SimpleToken("user1", "tokenValX", System.currentTimeMillis() + tokenLifetime, + System.currentTimeMillis(), null); + }; + + TokenManager tokenManager = new TokenManager(identityProvider, new TokenManagerConfig(0.7F, 200, + executionTimeout, new TokenManagerConfig.RetryPolicy(numberOfRetries, 100))); + + TokenListener listener = mock(TokenListener.class); + tokenManager.start(listener, false); + requesLatch.await(); + verify(listener, never()).onError(any()); + await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> { + verify(listener, times(1)).onTokenRenewed(any()); + }); + } - duration = 10000; - config.lower = 1000; - config.ratio = 0.00001F; - issueDate = System.currentTimeMillis(); - expireDate = issueDate + duration; - - delay = manager.calculateRenewalDelay(expireDate, issueDate); - - assertEquals(0, delay); - - duration = 10000; - config.lower = 1000; - config.ratio = 0.0001F; - issueDate = System.currentTimeMillis(); - expireDate = issueDate + duration; - - delay = manager.calculateRenewalDelay(expireDate, issueDate); - - assertThat(delay, either(is(0L)).or(is(1L))); - } - - @Test - public void testTokenManagerStart() - throws InterruptedException, ExecutionException, TimeoutException { - - IdentityProvider identityProvider = () -> new SimpleToken("user1", "tokenVal", - System.currentTimeMillis() + 5 * 1000, System.currentTimeMillis(), null); - - TokenManager tokenManager = new TokenManager(identityProvider, - new TokenManagerConfig(0.7F, 200, 2000, new RetryPolicy(1, 1))); - - TokenListener listener = mock(TokenListener.class); - final Token[] tokenHolder = new Token[1]; - doAnswer(invocation -> { - Object[] args = invocation.getArguments(); - tokenHolder[0] = (Token) args[0]; - return null; - }).when(listener).onTokenRenewed(any()); - - tokenManager.start(listener, true); - assertEquals(tokenHolder[0].getValue(), "tokenVal"); - } - - @Test - public void testBlockForInitialToken() { - IdentityProvider identityProvider = () -> { - throw new RuntimeException("Test exception from identity provider!"); - }; - - TokenManager tokenManager = new TokenManager(identityProvider, - new TokenManagerConfig(0.7F, 200, 2000, new TokenManagerConfig.RetryPolicy(5, 100))); - - TokenRequestException e = assertThrows(TokenRequestException.class, - () -> tokenManager.start(mock(TokenListener.class), true)); - - assertEquals("Test exception from identity provider!", e.getCause().getMessage()); - } - - @Test - public void testNoBlockForInitialToken() - throws InterruptedException, ExecutionException, TimeoutException { - int numberOfRetries = 5; - CountDownLatch requesLatch = new CountDownLatch(numberOfRetries); - IdentityProvider identityProvider = () -> { - requesLatch.countDown(); - throw new RuntimeException("Test exception from identity provider!"); - }; - - TokenManager tokenManager = new TokenManager(identityProvider, new TokenManagerConfig(0.7F, 200, - 2000, new TokenManagerConfig.RetryPolicy(numberOfRetries - 1, 100))); - - TokenListener listener = mock(TokenListener.class); - tokenManager.start(listener, false); - - requesLatch.await(); - verify(listener, atLeastOnce()).onError(any()); - verify(listener, never()).onTokenRenewed(any()); - } - - @Test - public void testTokenManagerWithFailingTokenRequest() - throws InterruptedException, ExecutionException, TimeoutException { - int numberOfRetries = 5; - CountDownLatch requesLatch = new CountDownLatch(numberOfRetries); - - IdentityProvider identityProvider = mock(IdentityProvider.class); - when(identityProvider.requestToken()).thenAnswer(invocation -> { - requesLatch.countDown(); - if (requesLatch.getCount() > 0) { - throw new RuntimeException("Test exception from identity provider!"); - } - return new SimpleToken("user1", "tokenValX", System.currentTimeMillis() + 50 * 1000, - System.currentTimeMillis(), null); - }); - - ArgumentCaptor argument = ArgumentCaptor.forClass(Token.class); - - TokenManager tokenManager = new TokenManager(identityProvider, new TokenManagerConfig(0.7F, 200, - 2000, new TokenManagerConfig.RetryPolicy(numberOfRetries - 1, 100))); - - TokenListener listener = mock(TokenListener.class); - tokenManager.start(listener, false); - requesLatch.await(); - verify(identityProvider, times(numberOfRetries)).requestToken(); - verify(listener, never()).onError(any()); - verify(listener).onTokenRenewed(argument.capture()); - assertEquals("tokenValX", argument.getValue().getValue()); - } - - @Test - public void testTokenManagerWithHangingTokenRequest() - throws InterruptedException, ExecutionException, TimeoutException { - int delayDuration = 200; - int executionTimeout = 100; - int tokenLifetime = 50 * 1000; - int numberOfRetries = 5; - CountDownLatch requesLatch = new CountDownLatch(numberOfRetries); - - IdentityProvider identityProvider = () -> { - requesLatch.countDown(); - if (requesLatch.getCount() > 0) { - delay(delayDuration); - } - return new SimpleToken("user1", "tokenValX", System.currentTimeMillis() + tokenLifetime, - System.currentTimeMillis(), null); - }; - - TokenManager tokenManager = new TokenManager(identityProvider, new TokenManagerConfig(0.7F, 200, - executionTimeout, new TokenManagerConfig.RetryPolicy(numberOfRetries, 100))); - - TokenListener listener = mock(TokenListener.class); - tokenManager.start(listener, false); - requesLatch.await(); - verify(listener, never()).onError(any()); - await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> { - verify(listener, times(1)).onTokenRenewed(any()); - }); - } - - private void delay(long durationInMs) { - try { - Thread.sleep(durationInMs); - } catch (InterruptedException e) { + private void delay(long durationInMs) { + try { + Thread.sleep(durationInMs); + } catch (InterruptedException e) { + } } - } } diff --git a/entraid/pom.xml b/entraid/pom.xml index 4940ecc..c4ff978 100644 --- a/entraid/pom.xml +++ b/entraid/pom.xml @@ -206,12 +206,19 @@ - com.googlecode.maven-java-formatter-plugin - maven-java-formatter-plugin - 0.4 + net.revelc.code.formatter + formatter-maven-plugin + 2.16.0 - ${project.basedir}/hbase-formatter.xml + ${project.basedir}/../hbase-formatter.xml + + + + validate + + + maven-jar-plugin diff --git a/entraid/src/main/java/redis/clients/authentication/entraid/AzureIdentityProvider.java b/entraid/src/main/java/redis/clients/authentication/entraid/AzureIdentityProvider.java index 74ec984..e539324 100644 --- a/entraid/src/main/java/redis/clients/authentication/entraid/AzureIdentityProvider.java +++ b/entraid/src/main/java/redis/clients/authentication/entraid/AzureIdentityProvider.java @@ -53,12 +53,9 @@ public final class AzureIdentityProvider implements IdentityProvider { private Supplier accessTokenSupplier; - public AzureIdentityProvider(DefaultAzureCredential defaultAzureCredential, Set scopes, - int timeout) { - TokenRequestContext ctx = new TokenRequestContext() - .setScopes(new ArrayList(scopes)); - accessTokenSupplier = () -> defaultAzureCredential.getToken(ctx) - .block(Duration.ofMillis(timeout)); + public AzureIdentityProvider(DefaultAzureCredential defaultAzureCredential, Set scopes, int timeout) { + TokenRequestContext ctx = new TokenRequestContext().setScopes(new ArrayList(scopes)); + accessTokenSupplier = () -> defaultAzureCredential.getToken(ctx).block(Duration.ofMillis(timeout)); } @Override diff --git a/entraid/src/main/java/redis/clients/authentication/entraid/AzureTokenAuthConfigBuilder.java b/entraid/src/main/java/redis/clients/authentication/entraid/AzureTokenAuthConfigBuilder.java index 09db995..5c25390 100644 --- a/entraid/src/main/java/redis/clients/authentication/entraid/AzureTokenAuthConfigBuilder.java +++ b/entraid/src/main/java/redis/clients/authentication/entraid/AzureTokenAuthConfigBuilder.java @@ -45,8 +45,8 @@ * @see TokenAuthConfig.Builder * @see DefaultAzureCredential */ -public class AzureTokenAuthConfigBuilder - extends TokenAuthConfig.Builder implements AutoCloseable { +public class AzureTokenAuthConfigBuilder extends TokenAuthConfig.Builder + implements AutoCloseable { public static final float DEFAULT_EXPIRATION_REFRESH_RATIO = 0.75F; public static final int DEFAULT_LOWER_REFRESH_BOUND_MILLIS = 2 * 60 * 1000; public static final int DEFAULT_TOKEN_REQUEST_EXECUTION_TIMEOUT_IN_MS = 1000; @@ -62,12 +62,10 @@ public AzureTokenAuthConfigBuilder() { this.expirationRefreshRatio(DEFAULT_EXPIRATION_REFRESH_RATIO) .lowerRefreshBoundMillis(DEFAULT_LOWER_REFRESH_BOUND_MILLIS) .tokenRequestExecTimeoutInMs(DEFAULT_TOKEN_REQUEST_EXECUTION_TIMEOUT_IN_MS) - .maxAttemptsToRetry(DEFAULT_MAX_ATTEMPTS_TO_RETRY) - .delayInMsToRetry(DEFAULT_DELAY_IN_MS_TO_RETRY); + .maxAttemptsToRetry(DEFAULT_MAX_ATTEMPTS_TO_RETRY).delayInMsToRetry(DEFAULT_DELAY_IN_MS_TO_RETRY); } - public AzureTokenAuthConfigBuilder defaultAzureCredential( - DefaultAzureCredential defaultAzureCredential) { + public AzureTokenAuthConfigBuilder defaultAzureCredential(DefaultAzureCredential defaultAzureCredential) { this.defaultAzureCredential = defaultAzureCredential; return this; } @@ -78,16 +76,15 @@ public AzureTokenAuthConfigBuilder scopes(Set scopes) { } @Override - public AzureTokenAuthConfigBuilder tokenRequestExecTimeoutInMs( - int tokenRequestExecTimeoutInMs) { + public AzureTokenAuthConfigBuilder tokenRequestExecTimeoutInMs(int tokenRequestExecTimeoutInMs) { super.tokenRequestExecTimeoutInMs(tokenRequestExecTimeoutInMs); this.tokenRequestExecTimeoutInMs = tokenRequestExecTimeoutInMs; return this; } public TokenAuthConfig build() { - super.identityProviderConfig(new AzureIdentityProviderConfig(defaultAzureCredential, scopes, - tokenRequestExecTimeoutInMs)); + super.identityProviderConfig( + new AzureIdentityProviderConfig(defaultAzureCredential, scopes, tokenRequestExecTimeoutInMs)); return super.build(); } diff --git a/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProvider.java b/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProvider.java index 74c2b4e..b83715a 100644 --- a/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProvider.java +++ b/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProvider.java @@ -35,31 +35,27 @@ private interface ClientAppFactory { private ClientAppFactory clientAppFactory; private ClientApp clientApp; - public EntraIDIdentityProvider(ServicePrincipalInfo servicePrincipalInfo, Set scopes, - int timeout) { + public EntraIDIdentityProvider(ServicePrincipalInfo servicePrincipalInfo, Set scopes, int timeout) { clientAppFactory = () -> { return createConfidentialClientApp(servicePrincipalInfo, scopes, timeout); }; } - private ClientApp createConfidentialClientApp(ServicePrincipalInfo servicePrincipalInfo, - Set scopes, int timeout) { + private ClientApp createConfidentialClientApp(ServicePrincipalInfo servicePrincipalInfo, Set scopes, + int timeout) { IClientCredential credential = getClientCredential(servicePrincipalInfo); ConfidentialClientApplication app; try { String authority = servicePrincipalInfo.getAuthority(); - authority = authority == null ? ConfidentialClientApplication.DEFAULT_AUTHORITY - : authority; - app = ConfidentialClientApplication - .builder(servicePrincipalInfo.getClientId(), credential).authority(authority) - .readTimeoutForDefaultHttpClient(timeout).build(); + authority = authority == null ? ConfidentialClientApplication.DEFAULT_AUTHORITY : authority; + app = ConfidentialClientApplication.builder(servicePrincipalInfo.getClientId(), credential) + .authority(authority).readTimeoutForDefaultHttpClient(timeout).build(); } catch (MalformedURLException e) { throw new RedisEntraIDException("Failed to init EntraID client!", e); } - ClientCredentialParameters params = ClientCredentialParameters.builder(scopes) - .skipCache(true).build(); + ClientCredentialParameters params = ClientCredentialParameters.builder(scopes).skipCache(true).build(); return () -> requestWithConfidentialClient(app, params); } @@ -71,18 +67,16 @@ public EntraIDIdentityProvider(ManagedIdentityInfo info, Set scopes, int }; } - private ClientApp createManagedIdentityApp(ManagedIdentityInfo info, Set scopes, - int timeout) { + private ClientApp createManagedIdentityApp(ManagedIdentityInfo info, Set scopes, int timeout) { ManagedIdentityApplication app = ManagedIdentityApplication.builder(info.getId()) .readTimeoutForDefaultHttpClient(timeout).build(); - ManagedIdentityParameters params = ManagedIdentityParameters - .builder(scopes.iterator().next()).forceRefresh(true).build(); + ManagedIdentityParameters params = ManagedIdentityParameters.builder(scopes.iterator().next()) + .forceRefresh(true).build(); return () -> requestWithManagedIdentity(app, params); } - public EntraIDIdentityProvider( - Supplier customEntraIdAuthenticationSupplier) { + public EntraIDIdentityProvider(Supplier customEntraIdAuthenticationSupplier) { clientAppFactory = () -> { return () -> customEntraIdAuthenticationSupplier.get(); diff --git a/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProviderConfig.java b/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProviderConfig.java index a9b57f7..021cbb5 100644 --- a/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProviderConfig.java +++ b/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDIdentityProviderConfig.java @@ -26,8 +26,7 @@ public EntraIDIdentityProviderConfig(ManagedIdentityInfo info, Set scope providerSupplier = () -> new EntraIDIdentityProvider(info, scopes, timeout); } - public EntraIDIdentityProviderConfig( - Supplier customEntraIdAuthenticationSupplier) { + public EntraIDIdentityProviderConfig(Supplier customEntraIdAuthenticationSupplier) { providerSupplier = () -> new EntraIDIdentityProvider(customEntraIdAuthenticationSupplier); } diff --git a/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDTokenAuthConfigBuilder.java b/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDTokenAuthConfigBuilder.java index 46942bc..bbd8224 100644 --- a/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDTokenAuthConfigBuilder.java +++ b/entraid/src/main/java/redis/clients/authentication/entraid/EntraIDTokenAuthConfigBuilder.java @@ -72,8 +72,8 @@ * @see AutoCloseable * */ -public class EntraIDTokenAuthConfigBuilder - extends TokenAuthConfig.Builder implements AutoCloseable { +public class EntraIDTokenAuthConfigBuilder extends TokenAuthConfig.Builder + implements AutoCloseable { public static final float DEFAULT_EXPIRATION_REFRESH_RATIO = 0.75F; public static final int DEFAULT_LOWER_REFRESH_BOUND_MILLIS = 2 * 60 * 1000; public static final int DEFAULT_TOKEN_REQUEST_EXECUTION_TIMEOUT_IN_MS = 1000; @@ -95,8 +95,7 @@ public EntraIDTokenAuthConfigBuilder() { this.expirationRefreshRatio(DEFAULT_EXPIRATION_REFRESH_RATIO) .lowerRefreshBoundMillis(DEFAULT_LOWER_REFRESH_BOUND_MILLIS) .tokenRequestExecTimeoutInMs(DEFAULT_TOKEN_REQUEST_EXECUTION_TIMEOUT_IN_MS) - .maxAttemptsToRetry(DEFAULT_MAX_ATTEMPTS_TO_RETRY) - .delayInMsToRetry(DEFAULT_DELAY_IN_MS_TO_RETRY); + .maxAttemptsToRetry(DEFAULT_MAX_ATTEMPTS_TO_RETRY).delayInMsToRetry(DEFAULT_DELAY_IN_MS_TO_RETRY); } public EntraIDTokenAuthConfigBuilder clientId(String clientId) { @@ -127,8 +126,8 @@ public EntraIDTokenAuthConfigBuilder systemAssignedManagedIdentity() { return this; } - public EntraIDTokenAuthConfigBuilder userAssignedManagedIdentity( - UserManagedIdentityType userManagedType, String id) { + public EntraIDTokenAuthConfigBuilder userAssignedManagedIdentity(UserManagedIdentityType userManagedType, + String id) { mii = new ManagedIdentityInfo(userManagedType, id); return this; } @@ -145,8 +144,7 @@ public EntraIDTokenAuthConfigBuilder scopes(Set scopes) { } @Override - public EntraIDTokenAuthConfigBuilder tokenRequestExecTimeoutInMs( - int tokenRequestExecTimeoutInMs) { + public EntraIDTokenAuthConfigBuilder tokenRequestExecTimeoutInMs(int tokenRequestExecTimeoutInMs) { super.tokenRequestExecTimeoutInMs(tokenRequestExecTimeoutInMs); this.tokenRequestExecTimeoutInMs = tokenRequestExecTimeoutInMs; return this; @@ -165,8 +163,7 @@ public TokenAuthConfig build() { } } if (spi != null && mii != null) { - throw new RedisEntraIDException( - "Cannot have both ServicePrincipal and ManagedIdentity!"); + throw new RedisEntraIDException("Cannot have both ServicePrincipal and ManagedIdentity!"); } if (this.customEntraIdAuthenticationSupplier != null && (spi != null || mii != null)) { throw new RedisEntraIDException( @@ -174,20 +171,17 @@ public TokenAuthConfig build() { } if (this.customEntraIdAuthenticationSupplier == null && spi == null && mii == null) { throw new RedisEntraIDException( - "Missing configuration. One of customEntraIdAuthenticationSupplier, ServicePrincipal or ManagedIdentity must be configured!"); + "Missing configuration. One of customEntraIdAuthenticationSupplier, ServicePrincipal or ManagedIdentity must be configured!"); } if (spi != null) { - super.identityProviderConfig( - new EntraIDIdentityProviderConfig(spi, scopes, tokenRequestExecTimeoutInMs)); + super.identityProviderConfig(new EntraIDIdentityProviderConfig(spi, scopes, tokenRequestExecTimeoutInMs)); } if (mii != null) { - super.identityProviderConfig( - new EntraIDIdentityProviderConfig(mii, scopes, tokenRequestExecTimeoutInMs)); + super.identityProviderConfig(new EntraIDIdentityProviderConfig(mii, scopes, tokenRequestExecTimeoutInMs)); } if (customEntraIdAuthenticationSupplier != null) { - super.identityProviderConfig( - new EntraIDIdentityProviderConfig(customEntraIdAuthenticationSupplier)); + super.identityProviderConfig(new EntraIDIdentityProviderConfig(customEntraIdAuthenticationSupplier)); } return super.build(); } diff --git a/entraid/src/main/java/redis/clients/authentication/entraid/ManagedIdentityInfo.java b/entraid/src/main/java/redis/clients/authentication/entraid/ManagedIdentityInfo.java index c90173a..aba7ac8 100644 --- a/entraid/src/main/java/redis/clients/authentication/entraid/ManagedIdentityInfo.java +++ b/entraid/src/main/java/redis/clients/authentication/entraid/ManagedIdentityInfo.java @@ -17,8 +17,7 @@ public enum IdentityType { } public enum UserManagedIdentityType { - CLIENT_ID(ManagedIdentityId::userAssignedClientId), - OBJECT_ID(ManagedIdentityId::userAssignedObjectId), + CLIENT_ID(ManagedIdentityId::userAssignedClientId), OBJECT_ID(ManagedIdentityId::userAssignedObjectId), RESOURCE_ID(ManagedIdentityId::userAssignedResourceId); private final Function func; @@ -50,7 +49,6 @@ public ManagedIdentityId getId() { return userManagedIdentityType.func.apply(id); } // this never happens - throw new UnsupportedOperationException( - "Operation not supported for the given identity type"); + throw new UnsupportedOperationException("Operation not supported for the given identity type"); } } diff --git a/entraid/src/main/java/redis/clients/authentication/entraid/ServicePrincipalInfo.java b/entraid/src/main/java/redis/clients/authentication/entraid/ServicePrincipalInfo.java index 6840b01..91f53b4 100644 --- a/entraid/src/main/java/redis/clients/authentication/entraid/ServicePrincipalInfo.java +++ b/entraid/src/main/java/redis/clients/authentication/entraid/ServicePrincipalInfo.java @@ -29,8 +29,7 @@ public ServicePrincipalInfo(String clientId, String secret, String authority) { accessWith = ServicePrincipalAccess.WithSecret; } - public ServicePrincipalInfo(String clientId, PrivateKey key, X509Certificate cert, - String authority) { + public ServicePrincipalInfo(String clientId, PrivateKey key, X509Certificate cert, String authority) { this.clientId = clientId; this.key = key; this.cert = cert; diff --git a/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderIntegrationTests.java b/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderIntegrationTests.java index 2b62a30..479037b 100644 --- a/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderIntegrationTests.java +++ b/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderIntegrationTests.java @@ -18,22 +18,22 @@ public class AzureIdentityProviderIntegrationTests { - @Test - public void requestTokenWithDefaultAzureCredential() { - // ensure environment variables are set - String client_id = System.getenv(TestContext.AZURE_CLIENT_ID); - assertNotNull(client_id); - assertFalse(client_id.isEmpty()); - String clientSecret = System.getenv(TestContext.AZURE_CLIENT_SECRET); - assertNotNull(clientSecret); - assertFalse(clientSecret.isEmpty()); - String tenantId = System.getenv("AZURE_TENANT_ID"); - assertNotNull(tenantId); - assertFalse(tenantId.isEmpty()); + @Test + public void requestTokenWithDefaultAzureCredential() { + // ensure environment variables are set + String client_id = System.getenv(TestContext.AZURE_CLIENT_ID); + assertNotNull(client_id); + assertFalse(client_id.isEmpty()); + String clientSecret = System.getenv(TestContext.AZURE_CLIENT_SECRET); + assertNotNull(clientSecret); + assertFalse(clientSecret.isEmpty()); + String tenantId = System.getenv("AZURE_TENANT_ID"); + assertNotNull(tenantId); + assertFalse(tenantId.isEmpty()); - DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build(); - Token token = new AzureIdentityProvider(defaultAzureCredential, - AzureTokenAuthConfigBuilder.DEFAULT_SCOPES, 2000).requestToken(); - assertNotNull(token.getValue()); - } + DefaultAzureCredential defaultAzureCredential = new DefaultAzureCredentialBuilder().build(); + Token token = new AzureIdentityProvider(defaultAzureCredential, AzureTokenAuthConfigBuilder.DEFAULT_SCOPES, + 2000).requestToken(); + assertNotNull(token.getValue()); + } } diff --git a/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderUnitTests.java b/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderUnitTests.java index c98879c..ff39417 100644 --- a/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderUnitTests.java +++ b/entraid/src/test/java/redis/clients/authentication/AzureIdentityProviderUnitTests.java @@ -42,12 +42,11 @@ public void testAzureTokenAuthConfigBuilder() { int timeout = 2000; try (MockedConstruction mockedConstructor = mockConstruction( - AzureIdentityProviderConfig.class, - (mock, context) -> { - assertEquals(mockCredential, context.arguments().get(0)); - assertEquals(scopes, context.arguments().get(1)); - assertEquals(timeout, context.arguments().get(2)); - })) { + AzureIdentityProviderConfig.class, (mock, context) -> { + assertEquals(mockCredential, context.arguments().get(0)); + assertEquals(scopes, context.arguments().get(1)); + assertEquals(timeout, context.arguments().get(2)); + })) { AzureTokenAuthConfigBuilder.builder().defaultAzureCredential(mockCredential).scopes(scopes) .tokenRequestExecTimeoutInMs(timeout).build(); } @@ -58,29 +57,27 @@ public void testAzureIdentityProviderConfig() { Set scopes = AzureTokenAuthConfigBuilder.DEFAULT_SCOPES; int timeout = 2000; - try (MockedConstruction mockedConstructor = mockConstruction( - AzureIdentityProvider.class, - (mock, context) -> { - assertEquals(mockCredential, context.arguments().get(0)); - assertEquals(scopes, context.arguments().get(1)); - assertEquals(timeout, context.arguments().get(2)); - })) { + try (MockedConstruction mockedConstructor = mockConstruction(AzureIdentityProvider.class, + (mock, context) -> { + assertEquals(mockCredential, context.arguments().get(0)); + assertEquals(scopes, context.arguments().get(1)); + assertEquals(timeout, context.arguments().get(2)); + })) { new AzureIdentityProviderConfig(mockCredential, scopes, timeout).getProvider(); } } @Test public void testRequestWithMockCredential() { - String token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() - - 1000)) - .withClaim("oid", "user1").sign(Algorithm.none()); + String token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() - 1000)).withClaim("oid", "user1") + .sign(Algorithm.none()); AccessToken t = new AccessToken(token, OffsetDateTime.now()); Mono monoToken = Mono.just(t); DefaultAzureCredential mockCredential = mock(DefaultAzureCredential.class); when(mockCredential.getToken(any(TokenRequestContext.class))).thenReturn(monoToken); - new AzureIdentityProviderConfig(mockCredential, - AzureTokenAuthConfigBuilder.DEFAULT_SCOPES, 0).getProvider().requestToken(); + new AzureIdentityProviderConfig(mockCredential, AzureTokenAuthConfigBuilder.DEFAULT_SCOPES, 0).getProvider() + .requestToken(); ArgumentCaptor argument = ArgumentCaptor.forClass(TokenRequestContext.class); diff --git a/entraid/src/test/java/redis/clients/authentication/EntraIDIntegrationTests.java b/entraid/src/test/java/redis/clients/authentication/EntraIDIntegrationTests.java index ced17c3..9cd1f38 100644 --- a/entraid/src/test/java/redis/clients/authentication/EntraIDIntegrationTests.java +++ b/entraid/src/test/java/redis/clients/authentication/EntraIDIntegrationTests.java @@ -16,27 +16,23 @@ public class EntraIDIntegrationTests { - @Test - public void requestTokenWithSecret() throws MalformedURLException { - TestContext testCtx = TestContext.DEFAULT; - ServicePrincipalInfo servicePrincipalInfo = new ServicePrincipalInfo( - testCtx.getClientId(), testCtx.getClientSecret(), - testCtx.getAuthority()); - Token token = new EntraIDIdentityProvider(servicePrincipalInfo, - testCtx.getRedisScopes(), 1000).requestToken(); + @Test + public void requestTokenWithSecret() throws MalformedURLException { + TestContext testCtx = TestContext.DEFAULT; + ServicePrincipalInfo servicePrincipalInfo = new ServicePrincipalInfo(testCtx.getClientId(), + testCtx.getClientSecret(), testCtx.getAuthority()); + Token token = new EntraIDIdentityProvider(servicePrincipalInfo, testCtx.getRedisScopes(), 1000).requestToken(); - assertNotNull(token.getValue()); - } + assertNotNull(token.getValue()); + } - @Test - public void requestTokenWithCert() throws MalformedURLException { - TestContext testCtx = TestContext.DEFAULT; - ServicePrincipalInfo servicePrincipalInfo = new ServicePrincipalInfo( - testCtx.getClientId(), testCtx.getPrivateKey(), testCtx.getCert(), - testCtx.getAuthority()); - Token token = new EntraIDIdentityProvider(servicePrincipalInfo, - testCtx.getRedisScopes(),1000).requestToken(); - assertNotNull(token.getValue()); - } + @Test + public void requestTokenWithCert() throws MalformedURLException { + TestContext testCtx = TestContext.DEFAULT; + ServicePrincipalInfo servicePrincipalInfo = new ServicePrincipalInfo(testCtx.getClientId(), + testCtx.getPrivateKey(), testCtx.getCert(), testCtx.getAuthority()); + Token token = new EntraIDIdentityProvider(servicePrincipalInfo, testCtx.getRedisScopes(), 1000).requestToken(); + assertNotNull(token.getValue()); + } } diff --git a/entraid/src/test/java/redis/clients/authentication/EntraIDUnitTests.java b/entraid/src/test/java/redis/clients/authentication/EntraIDUnitTests.java index 2a4d322..309d34d 100644 --- a/entraid/src/test/java/redis/clients/authentication/EntraIDUnitTests.java +++ b/entraid/src/test/java/redis/clients/authentication/EntraIDUnitTests.java @@ -87,8 +87,7 @@ public class EntraIDUnitTests { private static final long TOKEN_ISSUE_TIME = System.currentTimeMillis(); private static final String TOKEN_OID = "user1"; - private Token simpleToken = new SimpleToken(TOKEN_OID, TOKEN_VALUE, TOKEN_EXPIRATION_TIME, - TOKEN_ISSUE_TIME, null); + private Token simpleToken = new SimpleToken(TOKEN_OID, TOKEN_VALUE, TOKEN_EXPIRATION_TIME, TOKEN_ISSUE_TIME, null); private TestContext testCtx = TestContext.DEFAULT; @@ -98,9 +97,8 @@ public void testConfigBuilder() { String clientId = "clientId1"; String credential = "credential1"; Set scopes = Collections.singleton("scope1"); - IdentityProviderConfig configWithSecret = EntraIDTokenAuthConfigBuilder.builder() - .authority(authority).clientId(clientId).secret(credential).scopes(scopes).build() - .getIdentityProviderConfig(); + IdentityProviderConfig configWithSecret = EntraIDTokenAuthConfigBuilder.builder().authority(authority) + .clientId(clientId).secret(credential).scopes(scopes).build().getIdentityProviderConfig(); assertNotNull(configWithSecret); try (MockedConstruction mockedConstructor = mockConstruction( EntraIDIdentityProvider.class, (mock, context) -> { @@ -114,9 +112,8 @@ public void testConfigBuilder() { configWithSecret.getProvider(); } - IdentityProviderConfig configWithCert = EntraIDTokenAuthConfigBuilder.builder() - .authority(authority).clientId(clientId) - .key(testCtx.getPrivateKey(), testCtx.getCert()).scopes(scopes).build() + IdentityProviderConfig configWithCert = EntraIDTokenAuthConfigBuilder.builder().authority(authority) + .clientId(clientId).key(testCtx.getPrivateKey(), testCtx.getCert()).scopes(scopes).build() .getIdentityProviderConfig(); assertNotNull(configWithCert); try (MockedConstruction mockedConstructor = mockConstruction( @@ -138,8 +135,7 @@ public void testConfigBuilder() { try (MockedConstruction mockedConstructor = mockConstruction( EntraIDIdentityProvider.class, (mock, context) -> { ManagedIdentityInfo info = (ManagedIdentityInfo) context.arguments().get(0); - assertEquals(ManagedIdentityId.systemAssigned().getIdType(), - info.getId().getIdType()); + assertEquals(ManagedIdentityId.systemAssigned().getIdType(), info.getId().getIdType()); assertEquals(scopes, context.arguments().get(1)); })) { configWithManagedId.getProvider(); @@ -150,23 +146,16 @@ public void testConfigBuilder() { public void testConfigBuilderThrowsErrorIfMissconfigured() { // Missing Configuration - assertThrows(RedisEntraIDException.class,() -> EntraIDTokenAuthConfigBuilder.builder().build()); + assertThrows(RedisEntraIDException.class, () -> EntraIDTokenAuthConfigBuilder.builder().build()); // spi & mpi configured - assertThrows(RedisEntraIDException.class,() -> EntraIDTokenAuthConfigBuilder.builder() - .clientId("clientid") - .secret("secret") - .systemAssignedManagedIdentity() - .build()); - - // spi || mpi && customEntraIdAuthenticationSupplier configured - assertThrows(RedisEntraIDException.class,() -> EntraIDTokenAuthConfigBuilder.builder() - .clientId("clientid") - .secret("secret") - .customEntraIdAuthenticationSupplier(() -> mock(IAuthenticationResult.class)) - .build()); - } + assertThrows(RedisEntraIDException.class, () -> EntraIDTokenAuthConfigBuilder.builder().clientId("clientid") + .secret("secret").systemAssignedManagedIdentity().build()); + // spi || mpi && customEntraIdAuthenticationSupplier configured + assertThrows(RedisEntraIDException.class, () -> EntraIDTokenAuthConfigBuilder.builder().clientId("clientid") + .secret("secret").customEntraIdAuthenticationSupplier(() -> mock(IAuthenticationResult.class)).build()); + } // T.1.2 // Implement a stubbed IdentityProvider and verify that the TokenManager works normally and handles: @@ -204,8 +193,7 @@ public void initialTokenAcquisitionTest() { }; TokenManagerConfig tokenManagerConfig = new TokenManagerConfig(EXPIRATION_REFRESH_RATIO, - LOWER_REFRESH_BOUND_MILLIS, 60 * 60 * 1000, - this.tokenManagerConfig.getRetryPolicy()); + LOWER_REFRESH_BOUND_MILLIS, 60 * 60 * 1000, this.tokenManagerConfig.getRetryPolicy()); TokenListener listener = mock(TokenListener.class); TokenManager tokenManager = new TokenManager(identityProvider, tokenManagerConfig); @@ -288,7 +276,8 @@ public void tokenAcquisitionTimeoutTest() throws InterruptedException, TimeoutEx } // T.2.2 - // Verify that tokens are automatically renewed in the background and listeners are notified asynchronously without user intervention. + // Verify that tokens are automatically renewed in the background and listeners are notified asynchronously without + // user intervention. @Test public void backgroundTokenRenewalTest() throws InterruptedException, TimeoutException { AtomicInteger numberOfTokens = new AtomicInteger(0); @@ -338,8 +327,8 @@ public void onError(Exception e) { tokenManager.start(listener, false); - Awaitility.await().pollInterval(ONE_HUNDRED_MILLISECONDS).atMost(TWO_SECONDS) - .until(() -> numberOfErrors.get(), is(1)); + Awaitility.await().pollInterval(ONE_HUNDRED_MILLISECONDS).atMost(TWO_SECONDS).until(() -> numberOfErrors.get(), + is(1)); } // T.2.3 @@ -379,8 +368,7 @@ public void onError(Exception e) { Integer upper = (int) (tokenManagerConfig.getExpirationRefreshRatio() * 1000 + 10); Awaitility.await().pollInterval(ONE_HUNDRED_MILLISECONDS).atMost(Durations.TWO_SECONDS) .until(() -> numberOfTokens.get(), is(2)); - assertThat((Integer) timeDiff.get(), - both(greaterThanOrEqualTo(lower)).and(lessThanOrEqualTo(upper))); + assertThat((Integer) timeDiff.get(), both(greaterThanOrEqualTo(lower)).and(lessThanOrEqualTo(upper))); } // T.2.3 @@ -395,8 +383,7 @@ public void highPercentage_edgeCaseRenewalTimingTest() { IdentityProvider identityProvider = () -> new SimpleToken(TOKEN_OID, TOKEN_VALUE, System.currentTimeMillis() + validDurationInMs, System.currentTimeMillis(), null); - TokenManagerConfig tokenManagerConfig = new TokenManagerConfig(0.99F, 0, - TOKEN_REQUEST_EXEC_TIMEOUT, + TokenManagerConfig tokenManagerConfig = new TokenManagerConfig(0.99F, 0, TOKEN_REQUEST_EXEC_TIMEOUT, new TokenManagerConfig.RetryPolicy(RETRY_POLICY_MAX_ATTEMPTS, RETRY_POLICY_DELAY)); TokenManager tokenManager = new TokenManager(identityProvider, tokenManagerConfig); @@ -414,8 +401,8 @@ public void onError(Exception e) { tokenManager.start(listener, false); - Awaitility.await().pollInterval(Duration.ofMillis(10)).atMost(Durations.TWO_SECONDS) - .until(() -> tokens.size(), is(2)); + Awaitility.await().pollInterval(Duration.ofMillis(10)).atMost(Durations.TWO_SECONDS).until(() -> tokens.size(), + is(2)); Token initialToken = tokens.get(0); Token secondToken = tokens.get(1); @@ -423,8 +410,7 @@ public void onError(Exception e) { + (long) (validDurationInMs * tokenManagerConfig.getExpirationRefreshRatio()); Long renewalWindowEnd = initialToken.getExpiresAt(); assertThat((Long) secondToken.getReceivedAt(), - both(greaterThanOrEqualTo(renewalWindowStart)) - .and(lessThanOrEqualTo(renewalWindowEnd))); + both(greaterThanOrEqualTo(renewalWindowStart)).and(lessThanOrEqualTo(renewalWindowEnd))); } // T.2.3 @@ -439,8 +425,7 @@ public void lowPercentage_edgeCaseRenewalTimingTest() { IdentityProvider identityProvider = () -> new SimpleToken(TOKEN_OID, TOKEN_VALUE, System.currentTimeMillis() + validDurationInMs, System.currentTimeMillis(), null); - TokenManagerConfig tokenManagerConfig = new TokenManagerConfig(0.01F, 0, - TOKEN_REQUEST_EXEC_TIMEOUT, + TokenManagerConfig tokenManagerConfig = new TokenManagerConfig(0.01F, 0, TOKEN_REQUEST_EXEC_TIMEOUT, new TokenManagerConfig.RetryPolicy(RETRY_POLICY_MAX_ATTEMPTS, RETRY_POLICY_DELAY)); TokenManager tokenManager = new TokenManager(identityProvider, tokenManagerConfig); @@ -458,8 +443,8 @@ public void onError(Exception e) { tokenManager.start(listener, false); - Awaitility.await().pollInterval(ONE_MILLISECOND).atMost(Durations.TWO_SECONDS) - .until(() -> tokens.size(), is(2)); + Awaitility.await().pollInterval(ONE_MILLISECOND).atMost(Durations.TWO_SECONDS).until(() -> tokens.size(), + is(2)); Token initialToken = tokens.get(0); Token secondToken = tokens.get(1); @@ -467,20 +452,19 @@ public void onError(Exception e) { + (long) (validDurationInMs * tokenManagerConfig.getExpirationRefreshRatio()); Long renewalWindowEnd = initialToken.getExpiresAt(); assertThat((Long) secondToken.getReceivedAt(), - both(greaterThanOrEqualTo(renewalWindowStart)) - .and(lessThanOrEqualTo(renewalWindowEnd))); + both(greaterThanOrEqualTo(renewalWindowStart)).and(lessThanOrEqualTo(renewalWindowEnd))); } // T.2.4 // Confirm that the system correctly identifies expired tokens. (isExpired works) @Test public void expiredTokenCheckTest() { - String token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() - 1000)) - .withClaim("oid", "user1").sign(Algorithm.none()); + String token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() - 1000)).withClaim("oid", "user1") + .sign(Algorithm.none()); assertTrue(new JWToken(token).isExpired()); - token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + 1000)) - .withClaim("oid", "user1").sign(Algorithm.none()); + token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + 1000)).withClaim("oid", "user1") + .sign(Algorithm.none()); assertFalse(new JWToken(token).isExpired()); } @@ -497,15 +481,14 @@ public void tokenParserTest() { assertEquals(token, actual.getValue()); assertEquals(aSecondBefore, actual.getExpiresAt()); - assertThat((Long) (System.currentTimeMillis() - actual.getReceivedAt()), - lessThanOrEqualTo((Long) 10L)); + assertThat((Long) (System.currentTimeMillis() - actual.getReceivedAt()), lessThanOrEqualTo((Long) 10L)); } // T.2.5 // Ensure that token objects are immutable and cannot be modified after creation. @Test public void tokenImmutabilityTest() { - // TODO : what is expected exatcly ? + // TODO : what is expected exatcly ? } // T.3.1 @@ -532,8 +515,8 @@ public void cacheUpdateOnRenewalTest() { AtomicInteger numberOfTokens = new AtomicInteger(0); IdentityProvider identityProvider = () -> { - return new SimpleToken("user1", "" + numberOfTokens.incrementAndGet(), - System.currentTimeMillis() + 500, System.currentTimeMillis(), null); + return new SimpleToken("user1", "" + numberOfTokens.incrementAndGet(), System.currentTimeMillis() + 500, + System.currentTimeMillis(), null); }; TokenManager tokenManager = new TokenManager(identityProvider, tokenManagerConfig); assertNull(tokenManager.getCurrentToken()); @@ -553,11 +536,9 @@ public void renewalTimingConfigTest() { int lowerRefreshBoundMillis = 301; int maxAttemptsToRetry = 6; int tokenRequestExecTimeoutInMs = 401; - TokenAuthConfig tokenAuthConfig = EntraIDTokenAuthConfigBuilder.builder() - .clientId("testClientId").secret("testSecret") - .expirationRefreshRatio(refreshRatio).delayInMsToRetry(delayInMsToRetry) - .lowerRefreshBoundMillis(lowerRefreshBoundMillis) - .maxAttemptsToRetry(maxAttemptsToRetry) + TokenAuthConfig tokenAuthConfig = EntraIDTokenAuthConfigBuilder.builder().clientId("testClientId") + .secret("testSecret").expirationRefreshRatio(refreshRatio).delayInMsToRetry(delayInMsToRetry) + .lowerRefreshBoundMillis(lowerRefreshBoundMillis).maxAttemptsToRetry(maxAttemptsToRetry) .tokenRequestExecTimeoutInMs(tokenRequestExecTimeoutInMs).build(); TokenManagerConfig config = tokenAuthConfig.getTokenManagerConfig(); assertEquals(refreshRatio, config.getExpirationRefreshRatio(), 0.00000001F); @@ -583,9 +564,8 @@ public void withKeyCert_azureADConfigTest() { assertEquals(cert, info.getCert()); assertEquals(scopes, context.arguments().get(1)); })) { - TokenAuthConfig config = EntraIDTokenAuthConfigBuilder.builder() - .clientId("testClientId").authority("testAuthority").key(key, cert) - .scopes(scopes).build(); + TokenAuthConfig config = EntraIDTokenAuthConfigBuilder.builder().clientId("testClientId") + .authority("testAuthority").key(key, cert).scopes(scopes).build(); config.getIdentityProviderConfig().getProvider(); } } @@ -602,11 +582,10 @@ public void withUserAssignedManagedId_azureADConfigTest() { assertEquals("testUserManagedId", info.getId().getUserAssignedId()); assertEquals(scopes, context.arguments().get(1)); })) { - TokenAuthConfig config = EntraIDTokenAuthConfigBuilder.builder() - .clientId("testClientId").authority("testAuthority") - .userAssignedManagedIdentity(UserManagedIdentityType.CLIENT_ID, - "testUserManagedId") - .scopes(scopes).build(); + TokenAuthConfig config = EntraIDTokenAuthConfigBuilder.builder().clientId("testClientId") + .authority("testAuthority") + .userAssignedManagedIdentity(UserManagedIdentityType.CLIENT_ID, "testUserManagedId").scopes(scopes) + .build(); config.getIdentityProviderConfig().getProvider(); } } @@ -617,11 +596,11 @@ public void withUserAssignedManagedId_azureADConfigTest() { public void customProviderConfigTest() { IClientSecret secret = ClientCredentialFactory.createFromSecret(testCtx.getClientSecret()); // Choose and configure any type of app with any parameters as needed - ConfidentialClientApplication app = ConfidentialClientApplication - .builder(testCtx.getClientId(), secret).build(); + ConfidentialClientApplication app = ConfidentialClientApplication.builder(testCtx.getClientId(), secret) + .build(); // Customize credential parameters as needed - ClientCredentialParameters parameters = ClientCredentialParameters - .builder(Collections.singleton("testScope")).build(); + ClientCredentialParameters parameters = ClientCredentialParameters.builder(Collections.singleton("testScope")) + .build(); Supplier supplier = () -> { try { return app.acquireToken(parameters).get(); diff --git a/entraid/src/test/java/redis/clients/authentication/TestContext.java b/entraid/src/test/java/redis/clients/authentication/TestContext.java index 070d25f..74c75d9 100644 --- a/entraid/src/test/java/redis/clients/authentication/TestContext.java +++ b/entraid/src/test/java/redis/clients/authentication/TestContext.java @@ -42,12 +42,10 @@ private TestContext() { this.clientId = System.getenv(AZURE_CLIENT_ID); this.authority = System.getenv(AZURE_AUTHORITY); this.clientSecret = System.getenv(AZURE_CLIENT_SECRET); - this.userAssignedManagedIdentityClientId = System - .getenv(AZURE_USER_ASSIGNED_MANAGED_IDENTITY_CLIENT_ID); + this.userAssignedManagedIdentityClientId = System.getenv(AZURE_USER_ASSIGNED_MANAGED_IDENTITY_CLIENT_ID); } - public TestContext(String clientId, String authority, String clientSecret, - Set redisScopes) { + public TestContext(String clientId, String authority, String clientSecret, Set redisScopes) { this.clientId = clientId; this.authority = authority; this.clientSecret = clientSecret; @@ -99,7 +97,8 @@ private PrivateKey getPrivateKey(String privateKey) { // Generate the private key from the decoded byte array using PKCS8EncodedKeySpec PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey); - KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // Use the correct algorithm (e.g., "RSA", "EC", "DSA") + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); // Use the correct algorithm (e.g., "RSA", "EC", + // "DSA") PrivateKey key = keyFactory.generatePrivate(keySpec); return key; } catch (Exception e) { diff --git a/hbase-formatter.xml b/hbase-formatter.xml index cf59372..278a697 100644 --- a/hbase-formatter.xml +++ b/hbase-formatter.xml @@ -28,7 +28,7 @@ - + @@ -74,7 +74,7 @@ - + @@ -82,7 +82,7 @@ - + @@ -145,7 +145,7 @@ - + @@ -155,7 +155,7 @@ - + @@ -204,8 +204,8 @@ - - + + @@ -249,10 +249,10 @@ - + - + @@ -288,4 +288,4 @@ - + \ No newline at end of file