Skip to content

Commit

Permalink
[Working] added security scheams
Browse files Browse the repository at this point in the history
  • Loading branch information
thisaltennakoon committed Sep 13, 2023
1 parent d13fdfc commit b22cbf6
Show file tree
Hide file tree
Showing 22 changed files with 112 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public class API implements CacheableEntity<String> {
private String status;
private String revision;
private String organization;
private String securityScheme = null;

public String getRevision() {

Expand Down Expand Up @@ -199,4 +200,12 @@ public String getOrganization() {
public void setOrganization(String organization) {
this.organization = organization;
}

public void setSecurityScheme(String securityScheme) {
this.securityScheme = securityScheme;
}

public String getSecurityScheme() {
return securityScheme;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public boolean deployAPI(DeployAPIInGatewayEvent gatewayEvent) throws ArtifactSy
MessageContext.setCurrentMessageContext(
org.wso2.carbon.apimgt.gateway.utils.GatewayUtils.createAxis2MessageContext());
unDeployAPI(apiGatewayAdmin, gatewayEvent);
apiGatewayAdmin.deployAPI(gatewayAPIDTO);
apiGatewayAdmin.deployAPI(gatewayAPIDTO);//
addDeployedCertificatesToAPIAssociation(gatewayAPIDTO);
addDeployedGraphqlQLToAPI(gatewayAPIDTO);
DataHolder.getInstance().addKeyManagerToAPIMapping(apiId, gatewayAPIDTO.getKeyManagers());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,18 @@ public static TreeMap<String, org.wso2.carbon.apimgt.keymgt.model.entity.API> ge

return selectedAPIMap;
}

public static List<String> getSecuritySchemeOfWebSocketAPI(String context, String version, String tenantDomain) {

List<String> securitySchemeList = new ArrayList<>();
SubscriptionDataStore tenantSubscriptionStore =
SubscriptionDataHolder.getInstance().getTenantSubscriptionStore(tenantDomain);
if (tenantSubscriptionStore != null) {
securitySchemeList = Arrays.asList(tenantSubscriptionStore.getApiByContextAndVersion(context, version).getSecurityScheme().split(","));
}
return securitySchemeList;
}

private static class ContextLengthSorter implements Comparator<String> {

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,7 @@

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.*;

/**
* The util class to handle inbound websocket processor execution.
Expand Down Expand Up @@ -329,10 +326,13 @@ public static InboundProcessorResponseDTO authenticateToken(InboundMessageContex
public static InboundProcessorResponseDTO authenticateToken(InboundMessageContext inboundMessageContext,
String authenticationType) throws APISecurityException {

if (inboundMessageContext.getRequestHeaders().get(WebsocketUtil.authorizationHeader) != null) {
List<String> securitySchemeList = Utils.getSecuritySchemeOfWebSocketAPI(inboundMessageContext.getApiContext(),
inboundMessageContext.getVersion(), inboundMessageContext.getTenantDomain());
if (securitySchemeList.contains("oauth2") && inboundMessageContext.getRequestHeaders().get(WebsocketUtil.
authorizationHeader) != null) {
return new OAuthAuthenticator().authenticate(inboundMessageContext, authenticationType);
} else if (inboundMessageContext.getRequestHeaders().get(APIConstants.API_KEY_HEADER_QUERY_PARAM) != null ||
inboundMessageContext.getApiKeyFromQueryParams() != null) {
} else if (securitySchemeList.contains("api_key") && (inboundMessageContext.getRequestHeaders().
get(APIConstants.API_KEY_HEADER_QUERY_PARAM) != null || inboundMessageContext.getApiKeyFromQueryParams() != null)) {
return new ApiKeyAuthenticator().authenticate(inboundMessageContext);
} else {
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,7 @@ public boolean deployAPI(GatewayAPIDTO gatewayAPIDTO) throws AxisFault {
}
// Add API
if (StringUtils.isNotEmpty(gatewayAPIDTO.getApiDefinition())) {
restapiAdminServiceProxy.addApi(gatewayAPIDTO.getApiDefinition());
restapiAdminServiceProxy.addApi(gatewayAPIDTO.getApiDefinition());//
}
if (log.isDebugEnabled()) {
log.debug(gatewayAPIDTO.getName() + ":" + gatewayAPIDTO.getVersion() + " API Definition deployed");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public boolean addApi(String apiConfig) throws AxisFault {

try {
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
return restApiAdmin.addApiFromString(apiConfig);
return restApiAdmin.addApiFromString(apiConfig);//last
} else {
return restApiAdmin.addApiForTenant(apiConfig, tenantDomain);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ private void sendDeploymentEvent(API api, String tenantDomain, Set<String> publi
System.currentTimeMillis(), APIConstants.EventType.DEPLOY_API_IN_GATEWAY.name(), api.getOrganization(),
api.getId().getId(), api.getUuid(), publishedGateways, apiIdentifier.getName(), apiIdentifier.getVersion(),
apiIdentifier.getProviderName(),api.getType(),api.getContext());
deployAPIInGatewayEvent.setSecurityScheme(api.getApiSecurity());
APIUtil.sendNotification(deployAPIInGatewayEvent, APIConstants.NotifierType.GATEWAY_PUBLISHED_API.name());
if (debugEnabled) {
log.debug("Event sent to Gateway with eventID " + deployAPIInGatewayEvent.getEventId() + " for api "
Expand All @@ -86,6 +87,7 @@ private void sendDeploymentEvent(APIProduct api, String tenantDomain, Set<String
System.currentTimeMillis(), APIConstants.EventType.DEPLOY_API_IN_GATEWAY.name(), api.getOrganization(),
api.getProductId(),api.getUuid(), publishedGateways, apiIdentifier.getName(), apiIdentifier.getVersion(),
PRODUCT_PREFIX, api.getType(),api.getContext());
deployAPIInGatewayEvent.setSecurityScheme(api.getApiSecurity());
APIUtil.sendNotification(deployAPIInGatewayEvent, APIConstants.NotifierType.GATEWAY_PUBLISHED_API.name());
if (debugEnabled) {
log.debug("Event sent to Gateway with eventID " + deployAPIInGatewayEvent.getEventId() + " for api "
Expand All @@ -101,6 +103,7 @@ private void sendUnDeploymentEvent(API api, String tenantDomain, Set<String> rem
System.currentTimeMillis(), APIConstants.EventType.REMOVE_API_FROM_GATEWAY.name(),
api.getOrganization(), api.getId().getId(), api.getUuid(), removedGateways, apiIdentifier.getName(),
apiIdentifier.getVersion(), apiIdentifier.getProviderName(), api.getType(), api.getContext());
deployAPIInGatewayEvent.setSecurityScheme(api.getApiSecurity());
APIUtil.sendNotification(deployAPIInGatewayEvent,
APIConstants.NotifierType.GATEWAY_PUBLISHED_API.name());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@ private void addAPI(API api, int tenantId) throws APIManagementException {
APIConstants.EventType.API_CREATE.name(), tenantId, api.getOrganization(), api.getId().getApiName(),
apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(),
APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
apiEvent.setSecurityScheme(api.getApiSecurity());
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}

Expand Down Expand Up @@ -882,6 +883,7 @@ public API updateAPI(API api, API existingAPI) throws APIManagementException {
APIConstants.EventType.API_UPDATE.name(), tenantId, organization, api.getId().getApiName(), apiId,
api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(),
APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus(), action);
apiEvent.setSecurityScheme(api.getApiSecurity());
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());

// Extracting API details for the recommendation system
Expand Down Expand Up @@ -2235,6 +2237,7 @@ public void deleteAPI(String apiUuid, String organization) throws APIManagementE
api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(),
APIUtil.replaceEmailDomainBack(api.getId().getProviderName()),
api.getStatus());
apiEvent.setSecurityScheme(api.getApiSecurity());
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
} else {
log.debug("Event has not published to gateways due to API id has failed to retrieve from DB for API "
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class APIEvent extends Event {
private String apiStatus;
private String logLevel;
private APIConstants.EventAction action;
private String securityScheme;

public APIEvent(String uuid, String logLevel, String type, String apiContext) {
this.uuid = uuid;
Expand Down Expand Up @@ -106,6 +107,7 @@ public String toString() {
", apiType='" + apiType + '\'' +
", apiStatus='" + apiStatus + '\'' +
", action='" + action + '\'' +
", securityScheme='" + securityScheme + '\'' +
'}';
}

Expand Down Expand Up @@ -222,4 +224,12 @@ public APIConstants.EventAction getAction() {
public void setAction(APIConstants.EventAction action) {
this.action = action;
}

public String getSecurityScheme() {
return securityScheme;
}

public void setSecurityScheme(String securityScheme) {
this.securityScheme = securityScheme;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public class DeployAPIInGatewayEvent extends Event {
private Set<String> gatewayLabels;
private Set<APIEvent> associatedApis;
private String context;
private String securityScheme;

public DeployAPIInGatewayEvent(String eventId, long timestamp, String type, String tenantDomain, int apiId,
String uuid, Set<String> gatewayLabels, String name, String version, String provider,
Expand Down Expand Up @@ -155,4 +156,12 @@ public void setUuid(String uuid) {

this.uuid = uuid;
}

public String getSecurityScheme() {
return securityScheme;
}

public void setSecurityScheme(String securityScheme) {
this.securityScheme = securityScheme;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static void changeLifecycle(String user, APIProvider apiProvider, String
addLCStateChangeInDatabase(user, apiTypeWrapper, currentStatus, targetStatus, uuid);
// Event need to be sent after database status update.
sendLCStateChangeNotification(apiName, apiType, apiContext, apiTypeWrapper.getId().getVersion(), targetStatus, apiTypeWrapper.getId().getProviderName(),
apiTypeWrapper.getId().getId(), uuid, orgId);
apiTypeWrapper.getId().getId(), uuid, orgId, apiTypeWrapper.getApi().getApiSecurity());

// Remove revisions and subscriptions after API retire
if (!apiTypeWrapper.isAPIProduct()) {
Expand Down Expand Up @@ -316,11 +316,12 @@ private static void addLCStateChangeInDatabase(String user, ApiTypeWrapper apiTy
*/
private static void sendLCStateChangeNotification(String apiName, String apiType, String apiContext, String apiVersion,
String targetStatus, String provider, int apiOrApiProductId,
String uuid, String organization) throws APIManagementException {
String uuid, String organization, String securityScheme) throws APIManagementException {

APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(),
APIConstants.EventType.API_LIFECYCLE_CHANGE.name(), APIUtil.getInternalOrganizationId(organization), organization, apiName, apiOrApiProductId,
uuid, apiVersion, apiType, apiContext, APIUtil.replaceEmailDomainBack(provider), targetStatus);
apiEvent.setSecurityScheme(securityScheme);
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public class APIDTO {
private String organization = null;
private Boolean isDefaultVersion = null;
private List<URLMappingDTO> urlMappings = new ArrayList<>();
private String securityScheme = null;

/**
* UUID of API
Expand Down Expand Up @@ -246,6 +247,24 @@ public void setUrlMappings(List<URLMappingDTO> urlMappings) {
this.urlMappings = urlMappings;
}

/**
* Available authentication methods of the API.
**/
public APIDTO securityScheme(String securityScheme) {
this.securityScheme = securityScheme;
return this;
}


@ApiModelProperty(example = "Oauth2,api_key", value = "Available authentication methods of the API.")
@JsonProperty("securityScheme")
public String getSecurityScheme() {
return securityScheme;
}
public void setSecurityScheme(String securityScheme) {
this.securityScheme = securityScheme;
}


@Override
public boolean equals(java.lang.Object o) {
Expand All @@ -267,12 +286,13 @@ public boolean equals(java.lang.Object o) {
Objects.equals(status, API.status) &&
Objects.equals(organization, API.organization) &&
Objects.equals(isDefaultVersion, API.isDefaultVersion) &&
Objects.equals(urlMappings, API.urlMappings);
Objects.equals(urlMappings, API.urlMappings) &&
Objects.equals(securityScheme, API.securityScheme);
}

@Override
public int hashCode() {
return Objects.hash(uuid, apiId, provider, name, version, context, policy, apiType, status, organization, isDefaultVersion, urlMappings);
return Objects.hash(uuid, apiId, provider, name, version, context, policy, apiType, status, organization, isDefaultVersion, urlMappings, securityScheme);
}

@Override
Expand All @@ -292,6 +312,7 @@ public String toString() {
sb.append(" organization: ").append(toIndentedString(organization)).append("\n");
sb.append(" isDefaultVersion: ").append(toIndentedString(isDefaultVersion)).append("\n");
sb.append(" urlMappings: ").append(toIndentedString(urlMappings)).append("\n");
sb.append(" securityScheme: ").append(toIndentedString(securityScheme)).append("\n");
sb.append("}");
return sb.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,10 @@ public Response apisGet(String xWSO2Tenant, String apiId, String context, String
}
API api = subscriptionValidationDAO
.getAPIByContextAndVersion(context, version, gatewayLabel, expand);
if (api != null) {
api.setSecurityScheme(RestApiCommonUtil.getLoggedInUserProvider().getAPIbyUUID(api.getApiUUID(),
api.getOrganization()).getApiSecurity());
}
apiListDTO = SubscriptionValidationDataUtil.fromAPIToAPIListDTO(api);
} else {
if (APIConstants.ORG_ALL_QUERY_PARAM.equals(organization)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ public static APIListDTO fromAPIToAPIListDTO(API model) {
apidto.setStatus(model.getStatus());
apidto.setIsDefaultVersion(model.isDefaultVersion());
apidto.setOrganization(model.getOrganization());
apidto.setSecurityScheme(model.getSecurityScheme());
Map<String, URLMapping> urlMappings = model.getAllResources();
List<URLMappingDTO> urlMappingsDTO = new ArrayList<>();
for (URLMapping urlMapping : urlMappings.values()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -867,6 +867,10 @@ definitions:
type: array
items:
$ref: '#/definitions/URLMapping'
securityScheme:
type: string
description: Available authentication methods of the API.
example: Oauth2,api_key

#-----------------------------------------------------
# synapse Artifact resource
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1113,6 +1113,11 @@
"items" : {
"$ref" : "#/definitions/URLMapping"
}
},
"securityScheme" : {
"type" : "string",
"example" : "Oauth2,api_key",
"description" : "Available authentication methods of the API."
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ private APIKeyValidationInfoDTO validateSubscriptionDetails(APIKeyValidationInfo
.getTenantSubscriptionStore(apiTenantDomain);
//TODO add a check to see whether datastore is initialized an load data using rest api if it is not loaded
if (datastore != null) {
api = datastore.getApiByContextAndVersion(context, version);
api = datastore.getApiByContextAndVersion(context, version);// application subscription validation
if (api != null) {
key = datastore.getKeyMappingByKeyAndKeyManager(consumerKey, keyManager);
if (key != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.wso2.carbon.apimgt.api.model.subscription.URLMapping;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

Expand All @@ -41,6 +42,7 @@ public class API implements CacheableEntity<String> {
private String organization;
private boolean deployed = false;
private boolean isDefaultVersion = false;
private String securityScheme;

public API() {
}
Expand Down Expand Up @@ -203,6 +205,7 @@ public String toString() {
", policy='" + policy + '\'' +
", apiType='" + apiType + '\'' +
", status='" + status + '\'' +
", securityScheme='" + securityScheme + '\'' +
", isDefaultVersion=" + isDefaultVersion +
", urlMappings=" + urlMappings +
'}';
Expand Down Expand Up @@ -295,4 +298,13 @@ public boolean isDeployed() {
public void setDeployed(boolean deployed) {
this.deployed = deployed;
}

public String getSecurityScheme() {
return securityScheme;
}

public void setSecurityScheme(String securityScheme) {
// this.securityScheme = new ArrayList<>(Arrays.asList(securityScheme.split(",")));
this.securityScheme = securityScheme;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ private String invokeService(String path, String tenantDomain) throws DataLoadin
HttpClient httpClient = APIUtil.getHttpClient(servicePort, serviceProtocol);
String responseString;
try (CloseableHttpResponse httpResponse = APIUtil.executeHTTPRequestWithRetries(method, httpClient)) {
responseString = EntityUtils.toString(httpResponse.getEntity(), UTF8);
responseString = EntityUtils.toString(httpResponse.getEntity(), UTF8); //https://localhost:9443/internal/data/v1
} catch (APIManagementException e) {
throw new DataLoadingException("Error while retrieving subscriptions", e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,7 @@ private API getAPIFromAPIEvent(APIEvent event) {
api.setApiProvider(event.getApiProvider());
api.setApiVersion(event.getApiVersion());
api.setContext(event.getApiContext());
api.setSecurityScheme(event.getSecurityScheme());
if (log.isDebugEnabled()) {
log.debug("Event: " + event.toString());
log.debug("Converted : " + api.toString());
Expand Down
Binary file not shown.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2057,7 +2057,7 @@
<imp.package.version.osgi.framework>[1.6.0, 2.0.0)</imp.package.version.osgi.framework>

<!-- Misc Versions -->
<synapse.version>4.0.0-wso2v20</synapse.version>
<synapse.version>4.0.0-wso2v44-SNAPSHOT</synapse.version>

<orbit.version.json>3.0.0.wso2v1</orbit.version.json>

Expand Down

0 comments on commit b22cbf6

Please sign in to comment.