Skip to content

Commit

Permalink
W-17604924: add unit tests for package org.mule.runtime.module.extens…
Browse files Browse the repository at this point in the history
…ion.internal.runtime.connectivity.oauth
  • Loading branch information
akshaysonvane committed Jan 23, 2025
1 parent fa25d66 commit 0db5769
Show file tree
Hide file tree
Showing 12 changed files with 1,099 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ public AuthorizationCodeConnectionProviderWrapper(ConnectionProvider<C> delegate
super(delegate, reconnectionConfig, callbackValues);
this.oauthConfig = oauthConfig;
this.oauthHandler = oauthHandler;
authCodeStateSetter =
getOAuthStateSetter(getDelegateForInjection(), AUTHORIZATION_CODE_STATE_INTERFACES, oauthConfig.getGrantType());
authCodeStateSetter = resolveOauthStateSetter(oauthConfig);
dance = Once.of(this::updateAuthState);
this.forceInvalidateStatusRetrievalSupplier = forceInvalidateStatusRetrievalSupplier;
}
Expand Down Expand Up @@ -111,4 +110,8 @@ public void start() throws MuleException {
dancer = oauthHandler.register(oauthConfig);
super.start();
}

protected FieldSetter<Object, Object> resolveOauthStateSetter(AuthorizationCodeConfig oauthConfig) {
return getOAuthStateSetter(getDelegateForInjection(), AUTHORIZATION_CODE_STATE_INTERFACES, oauthConfig.getGrantType());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,12 @@
import org.mule.runtime.module.extension.internal.runtime.connectivity.oauth.OAuthConfig;
import org.mule.runtime.module.extension.internal.runtime.connectivity.oauth.OAuthHandler;
import org.mule.runtime.module.extension.internal.store.LazyObjectStoreToMapAdapter;
import org.mule.runtime.oauth.api.OAuthService;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Function;
Expand All @@ -79,7 +81,7 @@ public class AuthorizationCodeOAuthHandler extends OAuthHandler<AuthorizationCod
private Registry registry;

// TODO: MULE-10837 this should be a plain old @Inject
private LazyValue<HttpService> httpService;
protected LazyValue<HttpService> httpService;

private boolean forceInvalidateStatusRetrieval;

Expand Down Expand Up @@ -157,16 +159,16 @@ protected void setForceInvalidateStatusRetrieval(boolean forceInvalidateStatusRe
this.forceInvalidateStatusRetrieval = forceInvalidateStatusRetrieval;
}

private AuthorizationCodeOAuthDancer createDancer(AuthorizationCodeConfig config, List<AuthorizationCodeListener> listeners)
AuthorizationCodeOAuthDancer createDancer(AuthorizationCodeConfig config, List<AuthorizationCodeListener> listeners)
throws MuleException {
checkArgument(listeners != null, "listeners cannot be null");

OAuthAuthorizationCodeDancerBuilder dancerBuilder =
oauthService.get().authorizationCodeGrantTypeDancerBuilder(lockFactory,
new LazyObjectStoreToMapAdapter(
() -> objectStoreLocator
.apply(config)),
expressionEvaluator);
getOAuthService().get().authorizationCodeGrantTypeDancerBuilder(lockFactory,
new LazyObjectStoreToMapAdapter(
() -> objectStoreLocator
.apply(config)),
expressionEvaluator);
final AuthorizationCodeGrantType grantType = config.getGrantType();
final OAuthCallbackConfig callbackConfig = config.getCallbackConfig();

Expand Down Expand Up @@ -313,4 +315,12 @@ public void initialise() throws InitialisationException {
super.initialise();
httpService = new LazyLookup<>(HttpService.class, muleContext);
}

protected Map<String, AuthorizationCodeOAuthDancer> getDancers() {
return dancers;
}

protected LazyValue<OAuthService> getOAuthService() {
return oauthService;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,19 @@
import org.mule.oauth.client.api.builder.OAuthClientCredentialsDancerBuilder;
import org.mule.oauth.client.api.listener.ClientCredentialsListener;
import org.mule.oauth.client.api.state.ResourceOwnerOAuthContext;
import org.mule.runtime.api.config.ArtifactEncoding;
import org.mule.runtime.api.exception.MuleException;
import org.mule.runtime.api.exception.MuleRuntimeException;
import org.mule.runtime.api.util.LazyValue;
import org.mule.runtime.core.api.util.func.CheckedFunction;
import org.mule.runtime.extension.api.connectivity.oauth.ClientCredentialsGrantType;
import org.mule.runtime.module.extension.internal.runtime.connectivity.oauth.OAuthHandler;
import org.mule.runtime.module.extension.internal.store.LazyObjectStoreToMapAdapter;
import org.mule.runtime.oauth.api.OAuthService;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;

/**
* {@link OAuthHandler} implementation for the client credentials grant type
*
Expand Down Expand Up @@ -116,16 +116,16 @@ public void invalidate(ClientCredentialsConfig config) {
dancer.invalidateContext();
}

private ClientCredentialsOAuthDancer createDancer(ClientCredentialsConfig config, List<ClientCredentialsListener> listeners)
ClientCredentialsOAuthDancer createDancer(ClientCredentialsConfig config, List<ClientCredentialsListener> listeners)
throws MuleException {
checkArgument(listeners != null, "listeners cannot be null");

OAuthClientCredentialsDancerBuilder dancerBuilder =
oauthService.get().clientCredentialsGrantTypeDancerBuilder(lockFactory,
new LazyObjectStoreToMapAdapter(
() -> objectStoreLocator
.apply(config)),
expressionEvaluator);
getOAuthService().get().clientCredentialsGrantTypeDancerBuilder(lockFactory,
new LazyObjectStoreToMapAdapter(
() -> objectStoreLocator
.apply(config)),
expressionEvaluator);

final ClientCredentialsGrantType grantType = config.getGrantType();

Expand Down Expand Up @@ -163,8 +163,16 @@ private ClientCredentialsOAuthDancer createDancer(ClientCredentialsConfig config
return dancer;
}

private Integer generateId(ClientCredentialsConfig config) {
protected Integer generateId(ClientCredentialsConfig config) {
return Objects.hash(config.getOwnerConfigName(), config.getClientId(), config.getClientSecret(), config.getTokenUrl(),
config.getScope(), config.getCustomQueryParameters(), config.getCustomHeaders());
}

protected Map<String, ClientCredentialsOAuthDancer> getDancers() {
return dancers;
}

protected LazyValue<OAuthService> getOAuthService() {
return oauthService;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import static org.mockito.ArgumentCaptor.forClass;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
Expand Down Expand Up @@ -52,7 +51,14 @@ public class UpdatingAuthorizationCodeStateTestCase extends AbstractMuleTestCase
private static final String REFRESH_TOKEN = "myRefreshToken";
private static final String NEW_TOKEN = "newToken";
private static final String NEW_REFRESH_TOKEN = "newRefresh";
private static final String RESOURCE_OWNER_ID = "id";
private static final String RESOURCE_OWNER_ID = "exp";
private static final String EXPIRES_IN = "expires_in";
private static final String STATE = "state";
private static final String CONSUMER_KEY = "key";
private static final String CONSUMER_SECRET = "secret";
private static final String EXTERNAL_CALLBACK_URL = "externalCallbackUrl";
private static final String ACCESS_TOKEN_URL = "accesstokenurl";
private static final String AUTHORIZATION_URL = "AuthorizationUrl";

@Rule
public MockitoRule mockitorule = MockitoJUnit.rule();
Expand All @@ -68,23 +74,32 @@ public class UpdatingAuthorizationCodeStateTestCase extends AbstractMuleTestCase
@Mock
private ResourceOwnerOAuthContext refreshedContext;

@Mock
private OAuthCallbackConfig mockOAuthCallbackConfig;

@Before
public void before() {
oAuthConfig = new AuthorizationCodeConfig("configName",
empty(),
new CustomOAuthParameters(),
emptyMap(),
new AuthorizationCodeGrantType("url", "url", "#[s]", "reg", "#[x]", "sd"),
mock(OAuthCallbackConfig.class),
"key", "secret", "url", "url", "scope", RESOURCE_OWNER_ID, null, null);
new AuthorizationCodeGrantType(ACCESS_TOKEN_URL, AUTHORIZATION_URL, "#[s]", "reg",
"#[x]", "sd"),
new OAuthCallbackConfig("", "", "", EXTERNAL_CALLBACK_URL),
CONSUMER_KEY, CONSUMER_SECRET, AUTHORIZATION_URL, ACCESS_TOKEN_URL, "scope",
RESOURCE_OWNER_ID, null,
null);

when(initialContext.getAccessToken()).thenReturn(ACCESS_TOKEN);
when(initialContext.getRefreshToken()).thenReturn(REFRESH_TOKEN);
when(initialContext.getResourceOwnerId()).thenReturn(RESOURCE_OWNER_ID);
when(initialContext.getExpiresIn()).thenReturn(EXPIRES_IN);
when(initialContext.getState()).thenReturn(STATE);

when(refreshedContext.getAccessToken()).thenReturn(NEW_TOKEN);
when(refreshedContext.getRefreshToken()).thenReturn(NEW_REFRESH_TOKEN);
when(refreshedContext.getResourceOwnerId()).thenReturn(RESOURCE_OWNER_ID);
when(refreshedContext.getExpiresIn()).thenReturn(EXPIRES_IN);
}

@Test
Expand All @@ -101,6 +116,13 @@ public void onRefreshToken() {

assertThat(state.getAccessToken(), equalTo(ACCESS_TOKEN));
assertThat(state.getRefreshToken().get(), equalTo(REFRESH_TOKEN));
assertThat(state.getExternalCallbackUrl().get(), equalTo(EXTERNAL_CALLBACK_URL));
assertThat(state.getState().get(), equalTo(STATE));
assertThat(state.getExpiresIn().get(), equalTo(EXPIRES_IN));
assertThat(state.getConsumerKey(), equalTo("key"));
assertThat(state.getConsumerSecret(), equalTo("secret"));
assertThat(state.getAuthorizationUrl(), equalTo(AUTHORIZATION_URL));
assertThat(state.getAccessTokenUrl(), equalTo(ACCESS_TOKEN_URL));

AuthorizationCodeListener listener = listenerCaptor.getValue();
assertTokenRefreshed(newContext, state, listener);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
/*
* Copyright 2023 Salesforce, Inc. All rights reserved.
* The software in this package is published under the terms of the CPAL v1.0
* license, a copy of which has been included with this distribution in the
* LICENSE.txt file.
*/
package org.mule.runtime.module.extension.internal.runtime.connectivity.oauth.authcode;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.mock;

import org.mule.runtime.extension.api.connectivity.oauth.AuthorizationCodeGrantType;
import org.mule.runtime.module.extension.internal.runtime.connectivity.oauth.CustomOAuthParameters;
import org.mule.runtime.module.extension.internal.runtime.connectivity.oauth.OAuthObjectStoreConfig;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Optional;

import org.junit.Before;
import org.junit.Test;

public class AuthorizationCodeConfigTest {

private static final String OWNER_CONFIG_NAME = "ownerConfig";
private static final String CONSUMER_KEY = "consumerKey";
private static final String CONSUMER_SECRET = "consumerSecret";
private static final String AUTH_URL = "https://auth.url";
private static final String TOKEN_URL = "https://token.url";
private static final String SCOPE = "read write";
private static final String BEFORE = "before";
private static final String AFTER = "after";
private static final String RESOURCE_OWNER_ID = "resourceOwnerId";

private AuthorizationCodeGrantType grantType;
private Optional<OAuthObjectStoreConfig> storeConfig;
private CustomOAuthParameters customOAuthParameters;
private Map<Field, String> parameterExtractors;
private OAuthCallbackConfig callbackConfig;

private AuthorizationCodeConfig config;

@Before
public void setUp() {
grantType = mock(AuthorizationCodeGrantType.class);
storeConfig = Optional.of(mock(OAuthObjectStoreConfig.class));
customOAuthParameters = mock(CustomOAuthParameters.class);
parameterExtractors = mock(Map.class);
callbackConfig = mock(OAuthCallbackConfig.class);

config = new AuthorizationCodeConfig(
OWNER_CONFIG_NAME,
storeConfig,
customOAuthParameters,
parameterExtractors,
grantType,
callbackConfig,
CONSUMER_KEY,
CONSUMER_SECRET,
AUTH_URL,
TOKEN_URL,
SCOPE,
RESOURCE_OWNER_ID,
BEFORE,
AFTER);
}

@Test
public void testGetConsumerKey() {
assertThat(config.getConsumerKey(), is(CONSUMER_KEY));
}

@Test
public void testGetConsumerSecret() {
assertThat(config.getConsumerSecret(), is(CONSUMER_SECRET));
}

@Test
public void testGetAccessTokenUrl() {
assertThat(config.getAccessTokenUrl(), is(TOKEN_URL));
}

@Test
public void testGetAuthorizationUrl() {
assertThat(config.getAuthorizationUrl(), is(AUTH_URL));
}

@Test
public void testGetScope() {
assertThat(config.getScope().isPresent(), is(true));
assertThat(config.getScope().get(), is(SCOPE));
}

@Test
public void testGetScopeWhenNull() {
AuthorizationCodeConfig configWithNullScope = new AuthorizationCodeConfig(
OWNER_CONFIG_NAME,
storeConfig,
customOAuthParameters,
parameterExtractors,
grantType,
callbackConfig,
CONSUMER_KEY,
CONSUMER_SECRET,
AUTH_URL,
TOKEN_URL,
null,
RESOURCE_OWNER_ID,
BEFORE,
AFTER);
assertThat(configWithNullScope.getScope().isPresent(), is(false));
}

@Test
public void testGetGrantType() {
assertThat(config.getGrantType(), is(grantType));
}

@Test
public void testGetResourceOwnerId() {
assertThat(config.getResourceOwnerId(), is(RESOURCE_OWNER_ID));
}

@Test
public void testGetCallbackConfig() {
assertThat(config.getCallbackConfig(), is(callbackConfig));
}

@Test
public void testGetBefore() {
assertThat(config.getBefore().isPresent(), is(true));
assertThat(config.getBefore().get(), is(BEFORE));
}

@Test
public void testGetAfter() {
assertThat(config.getAfter().isPresent(), is(true));
assertThat(config.getAfter().get(), is(AFTER));
}
}
Loading

0 comments on commit 0db5769

Please sign in to comment.