Skip to content

Commit

Permalink
Merge pull request #13208 from IsuruMaduranga/custom-api-key-header
Browse files Browse the repository at this point in the history
Integration tests for custom api key header feature
  • Loading branch information
IsuruMaduranga authored Aug 20, 2023
2 parents 221327f + ae2b74c commit 4444f95
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8707,6 +8707,12 @@ components:
Name of the Authorization header used for invoking the API. If it is not set, Authorization header name specified
in tenant or system level will be used.
example: Authorization
apiKeyHeader:
type: string
pattern: '(^[^~!@#;:%^*()+={}|\\<>"'',&$\s+]*$)'
description: |
Name of the API key header used for invoking the API. If it is not set, default value `apiKey` will be used.
example: apiKey
securityScheme:
type: array
description: |
Expand Down Expand Up @@ -9354,6 +9360,12 @@ components:
Name of the Authorization header used for invoking the API. If it is not set, Authorization header name specified
in tenant or system level will be used.
example: Authorization
apiKeyHeader:
type: string
pattern: '(^[^~!@#;:%^*()+={}|\\<>"'',&$\s+]*$)'
description: |
Name of the API key header used for invoking the API. If it is not set, default value `apiKey` will be used.
example: apiKey
securityScheme:
type: array
description: |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ public class CORSHeadersTestCase extends APIManagerLifecycleBaseTest {
private static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER_VALUE = "DELETE,POST,PUT,PATCH,GET";
private static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER = "Access-Control-Allow-Headers";
private static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER_VALUE
= "authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction,Authorization";
= "authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction,Authorization,ApiKey";
private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER = "Access-Control-Allow-Credentials";

private String accessToken;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.APIKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.ApplicationKeyGenerateRequestDTO;
Expand All @@ -38,6 +40,7 @@
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.wso2.am.integration.tests.restapi.RESTAPITestConstants.APPLICATION_JSON_CONTENT;
import static org.wso2.am.integration.tests.restapi.RESTAPITestConstants.AUTHORIZATION_KEY;

Expand All @@ -46,24 +49,23 @@
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CustomHeaderTestCase extends APIManagerLifecycleBaseTest {

private ServerConfigurationManager serverConfigurationManager;
private final String CUSTOM_AUTHORIZATION_HEADER = "Test-Custom-Header";
private final String DEFAULT_API_KEY_HEADER = "ApiKey";
private final String CUSTOM_API_KEY_HEADER = "Custom-ApiKey-Header";
private final String API1_NAME = "CustomAuthHeaderTestAPI1";
private final String API1_CONTEXT = "customAuthHeaderTest1";
private final String API1_VERSION = "1.0.0";
private final String APPLICATION1_NAME = "CustomHeaderTest-Application";
private final String API_END_POINT_METHOD = "customers/123";

private final String API2_NAME = "CustomAuthHeaderTestAPI2";
private final String API2_CONTEXT = "customAuthHeaderTest2";
private final String API2_VERSION = "1.0.0";
private String accessToken;
private String applicationId;
private String apiId;
String invocationUrl;

@Factory(dataProvider = "userModeDataProvider")
public CustomHeaderTestCase(TestUserMode userMode) {
Expand Down Expand Up @@ -94,22 +96,25 @@ public void setEnvironment() throws Exception {
APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED,
ApplicationDTO.TokenTypeEnum.JWT);
applicationId = applicationResponse.getData();
}

@Test(groups = {"wso2.am"}, description = "Set a customer Auth header for all APIs in the system. (Test ID: 3.1.1.5, 3.1.1.14)")
public void testSystemWideCustomAuthHeader() throws Exception {

APIIdentifier apiIdentifier1 = new APIIdentifier(user.getUserName(), API1_NAME, API1_VERSION);

// Create API
String url = getGatewayURLHttp() + "jaxrs_basic/services/customers/customerservice";
APIRequest apiRequest = new APIRequest(API1_NAME, API1_CONTEXT, new URL(url), new URL(url));
apiRequest.setVersion(API1_VERSION);
apiRequest.setProvider(user.getUserName());
apiRequest.setTiersCollection(TIER_UNLIMITED);
String invocationUrl = getAPIInvocationURLHttps(API1_CONTEXT, API1_VERSION) + "/" + API_END_POINT_METHOD;
List<String> securitySchemes = new ArrayList<>();
securitySchemes.add("oauth2");
securitySchemes.add("api_key");
apiRequest.setSecurityScheme(securitySchemes);
invocationUrl = getAPIInvocationURLHttps(API1_CONTEXT, API1_VERSION) + "/" + API_END_POINT_METHOD;
apiId = createPublishAndSubscribeToAPIUsingRest(apiRequest, restAPIPublisher, restAPIStore, applicationId,
APIMIntegrationConstants.API_TIER.UNLIMITED);
waitForAPIDeploymentSync(user.getUserName(), API1_NAME, API1_VERSION, APIMIntegrationConstants.IS_API_EXISTS);
}

@Test(groups = {"wso2.am"}, description = "Set a customer Auth header for all APIs in the system. (Test ID: 3.1.1.5, 3.1.1.14)")
public void testSystemWideCustomAuthHeader() throws Exception {

//get access token
ArrayList<String> grantTypes = new ArrayList<>();
Expand Down Expand Up @@ -138,6 +143,69 @@ public void testSystemWideCustomAuthHeader() throws Exception {
"Response code mismatched");
}

@Test(groups = {"wso2.am"}, description = "Invoke an API with default API Key header",
dependsOnMethods = "testSystemWideCustomAuthHeader")
public void testInvokeAPIWIthDefaultApiKeyHeader() throws Exception {

// Genarate API Keys for the application
APIKeyDTO apiKeyDTO = restAPIStore
.generateAPIKeys(applicationId, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION.toString(),
-1, null, null);
assertNotNull(apiKeyDTO, "API Key generation failed");
String apiKey = apiKeyDTO.getApikey();

// Test whether a request can be made with the default API Key header
Map<String, String> requestHeaders1 = new HashMap<>();
requestHeaders1.put("accept", APPLICATION_JSON_CONTENT);
requestHeaders1.put(DEFAULT_API_KEY_HEADER, apiKey);
HttpResponse apiResponse1 = HttpRequestUtil.doGet(invocationUrl, requestHeaders1);
assertEquals(apiResponse1.getResponseCode(), Response.Status.OK.getStatusCode(),
"Response code mismatched");

// Test whether the 401 Unauthorized Response is returned with incorrect API Key header
Map<String, String> requestHeaders2 = new HashMap<>();
requestHeaders2.put("accept", APPLICATION_JSON_CONTENT);
requestHeaders2.put(CUSTOM_API_KEY_HEADER, apiKey);
HttpResponse apiResponse2 = HttpRequestUtil.doGet(invocationUrl, requestHeaders2);
assertEquals(apiResponse2.getResponseCode(), Response.Status.UNAUTHORIZED.getStatusCode(),
"Response code mismatched");
}

@Test(groups = {"wso2.am"}, description = "Invoke an API with custom API Key header",
dependsOnMethods = "testInvokeAPIWIthDefaultApiKeyHeader")
public void testInvokeAPIWIthCustomApiKeyHeader() throws Exception {

// Genarate API Keys for the application
APIKeyDTO apiKeyDTO = restAPIStore
.generateAPIKeys(applicationId, ApplicationKeyGenerateRequestDTO.KeyTypeEnum.PRODUCTION.toString(),
-1, null, null);
assertNotNull(apiKeyDTO, "API Key generation failed");
String apiKey = apiKeyDTO.getApikey();

// Update the API with custom API Key header
APIDTO apidto = restAPIPublisher.getAPIByID(apiId);
apidto.setApiKeyHeader(CUSTOM_API_KEY_HEADER);
restAPIPublisher.updateAPI(apidto);
createAPIRevisionAndDeployUsingRest(apiId, restAPIPublisher);
Thread.sleep(10000);

// Test whether a request can be made with the custom API Key header
Map<String, String> requestHeaders1 = new HashMap<>();
requestHeaders1.put("accept", APPLICATION_JSON_CONTENT);
requestHeaders1.put(CUSTOM_API_KEY_HEADER, apiKey);
HttpResponse apiResponse1 = HttpRequestUtil.doGet(invocationUrl, requestHeaders1);
assertEquals(apiResponse1.getResponseCode(), Response.Status.OK.getStatusCode(),
"Response code mismatched");

// Test whether the 401 Unauthorized Response is returned with default API Key header
Map<String, String> requestHeaders2 = new HashMap<>();
requestHeaders2.put("accept", APPLICATION_JSON_CONTENT);
requestHeaders2.put(DEFAULT_API_KEY_HEADER, apiKey);
HttpResponse apiResponse2 = HttpRequestUtil.doGet(invocationUrl, requestHeaders2);
assertEquals(apiResponse2.getResponseCode(), Response.Status.UNAUTHORIZED.getStatusCode(),
"Response code mismatched");
}

@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
SubscriptionListDTO subsDTO = restAPIStore.getAllSubscriptionsOfApplication(applicationId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
}
}
},
"x-wso2-api-key-header": "ApiKey",
"securityDefinitions" : {
"default" : {
"type" : "oauth2",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
}
}
},
"x-wso2-api-key-header": "ApiKey",
"x-throttling-tier" : "Unlimited",
"x-wso2-cors" : {
"corsConfigurationEnabled" : true,
Expand Down

0 comments on commit 4444f95

Please sign in to comment.