Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHeaders;
import org.apache.synapse.ManagedLifecycle;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.SynapseEnvironment;
Expand Down Expand Up @@ -727,56 +726,6 @@ public boolean handleResponse(MessageContext messageContext) {
private void handleAuthFailure(MessageContext messageContext, APISecurityException e) {
GatewayUtils.handleAuthFailure(messageContext, e, this.authorizationHeader, this.apiKeyHeader,
getAuthenticatorsChallengeString(), apiType);
try {
// If this is an MCP API, try to add DCR resource metadata to WWW-Authenticate header
if (APIConstants.API_TYPE_MCP.equalsIgnoreCase(this.apiType) && this.apiUUID != null) {
if(log.isDebugEnabled()) {
log.debug("Adding DCR resource metadata to WWW-Authenticate header for MCP API: " + this.apiUUID);
}
org.apache.axis2.context.MessageContext axis2MC =
((Axis2MessageContext) messageContext).getAxis2MessageContext();
@SuppressWarnings("unchecked")
Map<String, String> transportHeaders = (Map<String, String>)
axis2MC.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

if (transportHeaders == null) {
transportHeaders = new java.util.TreeMap<>();
axis2MC.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, transportHeaders);
}

java.util.List<String> keyManagers = org.wso2.carbon.apimgt.gateway.internal.DataHolder.getInstance()
.getKeyManagersFromUUID(this.apiUUID);
if (keyManagers != null && !keyManagers.isEmpty()) {
String existing = transportHeaders.get("WWW-Authenticate");
StringBuilder sb = new StringBuilder();
if (existing != null) {
sb.append(existing);
}
for (String kmName : keyManagers) {
// pass an empty tenant domain string to match mocks that use Mockito.anyString()
KeyManagerDto kmDto = KeyManagerHolder.getKeyManagerByName("", kmName);
KeyManager keyManager = kmDto != null ? kmDto.getKeyManager() : null;
KeyManagerConfiguration kmConfig = keyManager != null ? keyManager.getKeyManagerConfiguration() : null;
if (kmConfig == null) continue;

Object dcrEndpointParam = kmConfig.getParameter(
APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT);
String dcrEndpoint = dcrEndpointParam != null ? dcrEndpointParam.toString() : null;
if (dcrEndpoint != null) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append("resource_metadata=").append(dcrEndpoint);
}
}
if (sb.length() > 0) {
transportHeaders.put(HttpHeaders.WWW_AUTHENTICATE, sb.toString());
}
}
}
} catch (Exception ex) {
log.info("Error while adding DCR metadata to WWW-Authenticate header", ex);
}
}

protected void sendFault(MessageContext messageContext, int status) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ public class GatewayUtils {
private static final String HTTP_SC_DESC = "HTTP_SC_DESC";
private static final Gson gson = new Gson();
private static String apiUUID;
private static final String apiType = String.valueOf(APIConstants.ApiTypes.API);
private static final Pattern validHostHeaderPattern =
Pattern.compile("^[A-Za-z0-9][A-Za-z0-9.-]*(:\\d{1,5})?$");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,12 @@
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.wso2.carbon.apimgt.api.model.KeyManager;
import org.wso2.carbon.apimgt.api.model.KeyManagerConfiguration;
import org.wso2.carbon.apimgt.common.gateway.extensionlistener.ExtensionListener;
import org.wso2.carbon.apimgt.gateway.APIMgtGatewayConstants;
import org.wso2.carbon.apimgt.gateway.internal.DataHolder;
import org.wso2.carbon.apimgt.gateway.utils.GatewayUtils;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.apimgt.impl.dto.KeyManagerDto;
import org.wso2.carbon.apimgt.impl.factory.KeyManagerHolder;
import org.wso2.carbon.apimgt.impl.dto.ExtendedJWTConfigurationDto;
import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
Expand All @@ -51,10 +46,7 @@
import org.wso2.carbon.metrics.manager.Timer;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

Expand All @@ -63,8 +55,8 @@
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({Util.class, MetricManager.class, Timer.Context.class, APIUtil.class, GatewayUtils.class,
ServiceReferenceHolder.class, MultitenantUtils.class, APIKeyValidator.class, KeyManagerHolder.class,
DataHolder.class, org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder.class})
ServiceReferenceHolder.class, MultitenantUtils.class, APIKeyValidator.class,
org.wso2.carbon.apimgt.gateway.internal.ServiceReferenceHolder.class})
public class APIAuthenticationHandlerTestCase {

private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(APIAuthenticationHandlerTestCase.class);
Expand Down Expand Up @@ -255,79 +247,12 @@ public void testDestroy() {
apiAuthenticationHandler.destroy();
}

@Test
public void testHandleRequestForMCPNoAuth() {
APIAuthenticationHandler apiAuthenticationHandler = createAPIAuthenticationHandler();
apiAuthenticationHandler.setApiType(APIConstants.API_TYPE_MCP);
apiAuthenticationHandler.init(synapseEnvironment);

Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.MCP_NO_AUTH_REQUEST)).thenReturn(true);
Mockito.when(messageContext.getProperty(APIMgtGatewayConstants.MCP_METHOD)).thenReturn("initialize");

Options options = Mockito.mock(Options.class);
Mockito.when(options.getMessageId()).thenReturn("1");
Mockito.when(axis2MsgCntxt.getOptions()).thenReturn(options);

TreeMap transportHeaders = new TreeMap();
Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
log.info("Testing MCP no-auth request handling");

Assert.assertTrue(apiAuthenticationHandler.handleRequest(messageContext));
Mockito.verify(messageContext).setProperty(APIMgtGatewayConstants.API_TYPE, APIConstants.API_TYPE_MCP);
}

@Test
public void testHandleAuthFailureForMCPWithDCR() throws Exception {
APIAuthenticationHandler apiAuthenticationHandler = createAPIAuthenticationHandlerForExceptionTest();
apiAuthenticationHandler.setApiType(APIConstants.API_TYPE_MCP);
String apiUUID = "1234-5678";
apiAuthenticationHandler.setApiUUID(apiUUID);
apiAuthenticationHandler.init(synapseEnvironment);

log.info("Testing MCP auth failure handling with DCR endpoint");

PowerMockito.mockStatic(DataHolder.class);
DataHolder dataHolder = Mockito.mock(DataHolder.class);
Mockito.when(DataHolder.getInstance()).thenReturn(dataHolder);
List<String> keyManagers = new ArrayList<>();
keyManagers.add("default");
Mockito.when(dataHolder.getKeyManagersFromUUID(apiUUID)).thenReturn(keyManagers);

PowerMockito.mockStatic(KeyManagerHolder.class);
KeyManagerDto keyManagerDto = Mockito.mock(KeyManagerDto.class);
Mockito.when(KeyManagerHolder.getKeyManagerByName(Mockito.anyString(), Mockito.eq("default"))).thenReturn(keyManagerDto);

KeyManager keyManager = Mockito.mock(KeyManager.class);
Mockito.when(keyManagerDto.getKeyManager()).thenReturn(keyManager);
KeyManagerConfiguration kmConfig = Mockito.mock(KeyManagerConfiguration.class);
Mockito.when(keyManager.getKeyManagerConfiguration()).thenReturn(kmConfig);
String dcrEndpoint = "https://localhost:9443/client-registration/v0.17/register";
Mockito.when(kmConfig.getParameter(APIConstants.KeyManager.CLIENT_REGISTRATION_ENDPOINT)).thenReturn(dcrEndpoint);

Options options = Mockito.mock(Options.class);
Mockito.when(options.getMessageId()).thenReturn("1");
Mockito.when(axis2MsgCntxt.getOptions()).thenReturn(options);

TreeMap transportHeaders = new TreeMap();
PowerMockito.mockStatic(APIUtil.class);
Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
Mockito.when(messageContext.getProperty(RESTConstants.REST_API_CONTEXT)).thenReturn("/mcp/1.0.0");
PowerMockito.when(APIUtil.getHostAddress()).thenReturn("localhost");
PowerMockito.when(APIUtil.getPortOffset()).thenReturn(0);

Assert.assertFalse(apiAuthenticationHandler.handleRequest(messageContext));

String wwwAuthenticate = (String) transportHeaders.get("WWW-Authenticate");
Assert.assertNotNull(wwwAuthenticate);
Assert.assertTrue(wwwAuthenticate.contains("resource_metadata="));
}

/*
* This method will create an instance of APIAuthenticationHandler
* */
private APIAuthenticationHandler createAPIAuthenticationHandler() {
return new APIAuthenticationHandler() {
Comment thread
e19166 marked this conversation as resolved.

@Override
protected APIManagerConfigurationService getApiManagerConfigurationService() {
return Mockito.mock(APIManagerConfigurationService.class);
Expand Down Expand Up @@ -399,7 +324,7 @@ protected void initializeAuthenticators() {}

@Override
protected boolean isAuthenticate(MessageContext messageContext) throws APISecurityException {
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "test");
throw new APISecurityException(1000, "test");
Comment thread
e19166 marked this conversation as resolved.
}
Comment thread
e19166 marked this conversation as resolved.

@Override
Expand Down Expand Up @@ -442,16 +367,17 @@ public void testStartMetricTimer(){
.thenReturn("org.wso2.amAPIAuthenticationHandler");
PowerMockito.when(MetricManager.timer(org.wso2.carbon.metrics.manager.Level.INFO, "org.wso2.amAPIAuthenticationHandler"))
.thenReturn(timer);
apiAuthenticationHandler.startMetricTimer();
Mockito.verify(timer).start();
Timer.Context returned = apiAuthenticationHandler.startMetricTimer();
Assert.assertSame(localCtx, returned); // assert return
Mockito.verify(timer, Mockito.times(1)).start();
}

@Test
public void testStopMetricTimer(){
APIAuthenticationHandler apiAuthenticationHandler = new APIAuthenticationHandler();
Mockito.when(context.stop()).thenReturn(1000L);
apiAuthenticationHandler.stopMetricTimer(context);
Mockito.verify(context).stop();
Assert.assertTrue(true);
Comment thread
e19166 marked this conversation as resolved.
Outdated
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated
}

}
Expand Down
Loading