Skip to content

Commit

Permalink
Fix junit and write open api format based on file type.
Browse files Browse the repository at this point in the history
  • Loading branch information
rathnapandi committed Nov 22, 2024
1 parent 96007df commit 201e2de
Show file tree
Hide file tree
Showing 4 changed files with 148 additions and 64 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -182,4 +182,8 @@ public APISpecification setFilterConfig(APISpecificationFilter filterConfig) {
this.filterConfig = filterConfig;
return this;
}

public ObjectMapper getMapper() {
return mapper;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public void saveAPILocally(ObjectMapper mapper, ExportAPI exportAPI, String conf
throw new AppException("Backend API Definition is not available for the API : " + exportAPI.getName() + ", hence use the option -useFEAPIDefinition to export API", ErrorCode.BACKEND_API_DEF_NA);
return;
}
writeSpec(mapper, apiDef, exportAPI, localFolder);
writeSpec(apiDef, exportAPI, localFolder);
Image image = exportAPI.getAPIImage();
if (image != null && (!EnvironmentProperties.PRINT_CONFIG_CONSOLE)) {
writeBytesToFile(image.getImageContent(), localFolder + File.separator + image.getBaseFilename());
Expand Down Expand Up @@ -143,22 +143,23 @@ private void storePrivateCerts(File localFolder, List<AuthenticationProfile> aut
}
}

public void writeSpec(ObjectMapper mapper, APISpecification apiDef, ExportAPI exportAPI, File localFolder) throws AppException {
public void writeSpec(APISpecification apiDef, ExportAPI exportAPI, File localFolder) throws AppException {
String targetFile = null;
try {
if (!(apiDef instanceof WSDLSpecification && EnvironmentProperties.RETAIN_BACKEND_URL) && (!EnvironmentProperties.PRINT_CONFIG_CONSOLE)) {
String fileName = Utils.replaceSpecialChars(exportAPI.getName());
String fileExtension = apiDef.getAPIDefinitionType().getFileExtension();
if(apiDef instanceof Swagger2xSpecification || apiDef instanceof OAS3xSpecification){
if (apiDef instanceof Swagger2xSpecification || apiDef instanceof OAS3xSpecification) {
ObjectMapper mapper = apiDef.getMapper();
if (mapper.getFactory() instanceof YAMLFactory) {
fileExtension = APISpecification.APISpecType.SWAGGER_API_20_YAML.getFileExtension();
}else {
fileExtension = APISpecification.APISpecType.SWAGGER_API_20.getFileExtension();
fileExtension = APISpecification.APISpecType.SWAGGER_API_20_YAML.getFileExtension();
} else {
fileExtension = APISpecification.APISpecType.SWAGGER_API_20.getFileExtension();
}
targetFile = localFolder.getCanonicalPath() + "/" + fileName + fileExtension;
Object spec = mapper.readValue(apiDef.getApiSpecificationContent(), Object.class);
mapper.writerWithDefaultPrettyPrinter().writeValue(new File(targetFile), spec);
}else {
} else {
targetFile = localFolder.getCanonicalPath() + "/" + fileName + fileExtension;
writeBytesToFile(apiDef.getApiSpecificationContent(), targetFile);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
import java.security.cert.X509Certificate;
import java.util.*;

import static io.swagger.v3.oas.models.security.SecurityScheme.In.QUERY;
import static io.swagger.v3.oas.models.security.SecurityScheme.In.HEADER;


public class GenerateTemplate implements APIMCLIServiceProvider {


Expand All @@ -59,6 +63,11 @@ public class GenerateTemplate implements APIMCLIServiceProvider {
public static final String PASS_THROUGH = "Pass Through";
public static final String REMOVE_CREDENTIALS_ON_SUCCESS = "removeCredentialsOnSuccess";
public static final String TOKEN_STORE = "tokenStore";
public static final String TAKE_FROM = "takeFrom";
public static final String OAUTH_TOKEN_CLIENT_ID = "${oauth.token.client_id}";
public static final String USE_CLIENT_REGISTRY = "useClientRegistry";
public static final String SUBJECT_SELECTOR = "subjectSelector";
public static final String HEADER_STR = "HEADER";

@Override
public String getName() {
Expand Down Expand Up @@ -292,42 +301,71 @@ public Map<String, InboundProfile> addInboundPerMethodOverride(OpenAPI openAPI,
operationId = httpMethod.name() + " " + key;
}
List<SecurityRequirement> securityRequirements = operation.getSecurity();
if (securityRequirements == null) {
SecurityProfile passThroughProfile = createPassThroughSecurityProfile();
inboundProfile.setSecurityProfile(passThroughProfile.getName());
inboundProfiles.put(operationId, inboundProfile);
securityProfiles.add(passThroughProfile);
} else {

for (SecurityRequirement securityRequirement : securityRequirements) {
Set<String> keys = securityRequirement.keySet();
for (String securityKey : keys) {
SecurityScheme securityScheme = openAPI.getComponents().getSecuritySchemes().get(securityKey);
SecurityScheme.Type type = securityScheme.getType();

if (type == SecurityScheme.Type.OAUTH2) {
List<String> scopes = securityRequirement.get(securityKey);
SecurityProfile oauth2SecurityProfile = createOauthSecurityProfile(operationId, scopes);
inboundProfile.setSecurityProfile(oauth2SecurityProfile.getName());
inboundProfiles.put(operationId, inboundProfile);
securityProfiles.add(oauth2SecurityProfile);
} else if (type == SecurityScheme.Type.APIKEY) {
LOG.warn("API key is not handled");
} else if (type == SecurityScheme.Type.MUTUALTLS) {
LOG.warn("Mutual auth is not handled");
}
}
}
}
handleSecurity(openAPI, inboundProfiles, securityRequirements, securityProfiles, inboundProfile, operationId);
}
}
api.setSecurityProfiles(securityProfiles);
return inboundProfiles;
}

public SecurityProfile createPassThroughSecurityProfile() {

public void handleSecurity(OpenAPI openAPI, Map<String, InboundProfile> inboundProfiles, List<SecurityRequirement> securityRequirements, List<SecurityProfile> securityProfiles, InboundProfile inboundProfile, String operationId) {
if (securityRequirements == null || securityRequirements.isEmpty()) {
SecurityProfile passThroughProfile = createPassThroughSecurityProfile(operationId);
inboundProfile.setSecurityProfile(passThroughProfile.getName());
inboundProfiles.put(operationId, inboundProfile);
securityProfiles.add(passThroughProfile);
} else {
for (SecurityRequirement securityRequirement : securityRequirements) {
Set<String> keys = securityRequirement.keySet();
for (String securityKey : keys) {
SecurityScheme securityScheme = openAPI.getComponents().getSecuritySchemes().get(securityKey);
mapAPIMSecurity(securityRequirement, securityScheme, inboundProfiles, inboundProfile, securityProfiles, operationId, securityKey);
}
}
}
}

public void mapAPIMSecurity(SecurityRequirement securityRequirement, SecurityScheme securityScheme, Map<String, InboundProfile> inboundProfiles, InboundProfile inboundProfile, List<SecurityProfile> securityProfiles, String operationId, String securityKey) {
SecurityScheme.Type type = securityScheme.getType();
if (type == SecurityScheme.Type.OAUTH2) {
LOG.info("mapping oauth2 profile");
List<String> scopes = securityRequirement.get(securityKey);
SecurityProfile oauth2SecurityProfile = createOauthSecurityProfile(operationId, scopes);
inboundProfile.setSecurityProfile(oauth2SecurityProfile.getName());
inboundProfiles.put(operationId, inboundProfile);
securityProfiles.add(oauth2SecurityProfile);
} else if (type == SecurityScheme.Type.APIKEY) {
LOG.info("mapping API key profile");
List<String> scopes = securityRequirement.get(securityKey);
SecurityScheme.In in = securityScheme.getIn();
if (in == SecurityScheme.In.COOKIE) {
LOG.warn("API key in cookie not supported");
return;
}
String apikeyLocation = in.name();
String fieldName = securityScheme.getName();
SecurityProfile apiKeySecurityProfile = createApiKeySecurityProfile(operationId, apikeyLocation, fieldName, scopes);
inboundProfile.setSecurityProfile(apiKeySecurityProfile.getName());
inboundProfiles.put(operationId, inboundProfile);
securityProfiles.add(apiKeySecurityProfile);
} else if (type == SecurityScheme.Type.MUTUALTLS) {
LOG.warn("Mutual auth is not handled");
} else if (type == SecurityScheme.Type.OPENIDCONNECT || type == SecurityScheme.Type.HTTP && securityScheme.getScheme().equalsIgnoreCase("bearer")) {
LOG.info("External auth / openid connect is not handled");
List<String> scopes = securityRequirement.get(securityKey);
SecurityProfile oauth2ExternalSecurityProfile = createOauthExternalSecurityProfile(operationId, scopes);
inboundProfile.setSecurityProfile(oauth2ExternalSecurityProfile.getName());
inboundProfiles.put(operationId, inboundProfile);
securityProfiles.add(oauth2ExternalSecurityProfile);
} else if (type == SecurityScheme.Type.HTTP && securityScheme.getScheme().equalsIgnoreCase("basic")) {
LOG.warn("Basic Auth is not handled");
}
}

public SecurityProfile createPassThroughSecurityProfile(String operationId) {
SecurityProfile profile = new SecurityProfile();
profile.setName(PASS_THROUGH);
profile.setName(PASS_THROUGH + " " + operationId);
profile.setIsDefault(false);
SecurityDevice securityDevice = new SecurityDevice();
securityDevice.setName(PASS_THROUGH);
Expand All @@ -343,6 +381,60 @@ public SecurityProfile createPassThroughSecurityProfile() {
return profile;
}

public SecurityProfile createApiKeySecurityProfile(String operationId, String apikeyLocation, String fieldName, List<String> scopes) {
SecurityProfile profile = new SecurityProfile();
profile.setName("apikey " + operationId);
profile.setIsDefault(false);
SecurityDevice securityDevice = new SecurityDevice();
securityDevice.setName("API Key");
securityDevice.setType(DeviceType.apiKey);
securityDevice.setOrder(0);
Map<String, String> properties = new HashMap<>();
properties.put(REMOVE_CREDENTIALS_ON_SUCCESS, "true");
if (apikeyLocation.equals(HEADER.name())) {
properties.put(TAKE_FROM, HEADER_STR);
} else if (apikeyLocation.equals(QUERY.name())) {
properties.put(TAKE_FROM, "QUERY");
}
properties.put("apiKeyFieldName", fieldName);
if (scopes != null && !scopes.isEmpty()) {
String scope = String.join(" ", scopes);
properties.put("scopes", scope);
properties.put("scopesMustMatch", "All");
}
securityDevice.setProperties(properties);
List<SecurityDevice> securityDevices = new ArrayList<>();
securityDevices.add(securityDevice);
profile.setDevices(securityDevices);
return profile;
}


public SecurityProfile createOauthExternalSecurityProfile(String operationId, List<String> scopes) {
SecurityProfile profile = new SecurityProfile();
profile.setName("External Oauth2 " + operationId);
profile.setIsDefault(false);
SecurityDevice securityDevice = new SecurityDevice();
securityDevice.setName("OAuth (External)");
securityDevice.setType(DeviceType.oauthExternal);
securityDevice.setOrder(0);
Map<String, String> properties = new HashMap<>();
properties.put(TOKEN_STORE, "Tokeninfo policy 1");
properties.put(USE_CLIENT_REGISTRY, "true");
properties.put(SUBJECT_SELECTOR, OAUTH_TOKEN_CLIENT_ID);
properties.put("oauth.token.client_id", OAUTH_TOKEN_CLIENT_ID);
properties.put("oauth.token.scopes", "${oauth.token.scopes}");
properties.put("oauth.token.valid", "${oauth.token.valid}");
String scope = String.join(" ", scopes);
setupOauthProperties(properties, scope);
securityDevice.setProperties(properties);
List<SecurityDevice> securityDevices = new ArrayList<>();
securityDevices.add(securityDevice);
profile.setDevices(securityDevices);
return profile;
}


public SecurityProfile createOauthSecurityProfile(String operationId, List<String> scopes) {
SecurityProfile profile = new SecurityProfile();
profile.setName("Oauth2 " + operationId);
Expand Down Expand Up @@ -490,20 +582,20 @@ private List<SecurityProfile> addInboundSecurityToAPI(String frontendAuthType) t
Map<String, String> properties = new HashMap<>();
if (deviceType.equals(DeviceType.apiKey)) {
properties.put("apiKeyFieldName", "KeyId");
properties.put("takeFrom", "HEADER");
properties.put(TAKE_FROM, HEADER_STR);
properties.put(REMOVE_CREDENTIALS_ON_SUCCESS, "true");
} else if (deviceType.equals(DeviceType.oauth)) {
properties.put(TOKEN_STORE, "OAuth Access Token Store");
setupOauthProperties(properties, "resource.WRITE, resource.READ");
} else if (deviceType.equals(DeviceType.oauthExternal)) {
properties.put(TOKEN_STORE, "Tokeninfo policy 1");
properties.put("useClientRegistry", "true");
properties.put("subjectSelector", "${oauth.token.client_id}");
properties.put(USE_CLIENT_REGISTRY, "true");
properties.put(SUBJECT_SELECTOR, OAUTH_TOKEN_CLIENT_ID);
setupOauthProperties(properties, "resource.WRITE, resource.READ");
} else if (deviceType.equals(DeviceType.authPolicy)) {
properties.put("authenticationPolicy", "Custom authentication policy");
properties.put("useClientRegistry", "true");
properties.put("subjectSelector", "authentication.subject.id");
properties.put(USE_CLIENT_REGISTRY, "true");
properties.put(SUBJECT_SELECTOR, "authentication.subject.id");
properties.put("descriptionType", ORIGINAL);
properties.put("descriptionUrl", "");
properties.put("descriptionMarkdown", "");
Expand All @@ -521,7 +613,7 @@ private List<SecurityProfile> addInboundSecurityToAPI(String frontendAuthType) t
}

private void setupOauthProperties(Map<String, String> properties, String scopes) {
properties.put("accessTokenLocation", "HEADER");
properties.put("accessTokenLocation", HEADER_STR);
properties.put("authorizationHeaderPrefix", "Bearer");
properties.put("accessTokenLocationQueryString", "");
properties.put("scopesMustMatch", "All");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -198,41 +198,28 @@ public void testWithFrontendAuthAlternateName() throws IOException {
}

@Test
public void generateApiMethods() throws IOException {

OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/methods.yaml");
public void generateApiMethods() {
OpenAPI openAPI = new OpenAPIV3Parser().read("methods.yaml");
GenerateTemplate generateTemplate = new GenerateTemplate();
List<APIMethod> apiMethods = generateTemplate.addMethods(openAPI);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(apiMethods));
// System.out.println(openAPI);

Assert.assertEquals(3, apiMethods.size());
Assert.assertNotNull(apiMethods.get(0).getTags().get("public"));
}

@Test
public void includeInboundPerMethodOverride() throws IOException {

OpenAPI openAPI = new OpenAPIV3Parser().read("src/test/resources/methods.yaml");
public void includeInboundPerMethodOverride() {
OpenAPI openAPI = new OpenAPIV3Parser().read("methods.yaml");
GenerateTemplate generateTemplate = new GenerateTemplate();
List<SecurityProfile> securityProfiles = new ArrayList<>();
API api = new API();
generateTemplate.addInboundPerMethodOverride(openAPI, api, securityProfiles);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
FilterProvider filters = new SimpleFilterProvider()

.addFilter("ProfileFilter",
SimpleBeanPropertyFilter.serializeAllExcept("apiMethodId"))
.setDefaultFilter(SimpleBeanPropertyFilter.serializeAllExcept());
objectMapper.setFilterProvider(filters);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(api.getInboundProfiles()));
Map<String, InboundProfile> inboundProfileMap = generateTemplate.addInboundPerMethodOverride(openAPI, api, securityProfiles);
Assert.assertNotNull(inboundProfileMap);
}


@Test
public void testInboundOverride() throws IOException {
String[] args = {"template", "generate", "-c", "api-config.yaml", "-a", "src/test/resources/methods.yaml", "-frontendAuthType", "apiKey", "-inboundPerMethodOverride", "-o", "yaml"};
String[] args = {"template", "generate", "-c", "api-config.json", "-a", "src/test/resources/methods.yaml", "-frontendAuthType", "apiKey", "-inboundPerMethodOverride", "-o", "json"};
GenerateTemplate.generate(args);
// DocumentContext documentContext = JsonPath.parse(Files.newInputStream(Paths.get("api-config.json")));
// Assert.assertEquals("Swagger Petstore - OpenAPI 3.0", documentContext.read("$.name"));
Expand Down

0 comments on commit 201e2de

Please sign in to comment.