Skip to content

Commit

Permalink
Merge pull request #772 from akto-api-security/fix/postman_export
Browse files Browse the repository at this point in the history
Changes for fixing postman export
  • Loading branch information
aktoboy authored Dec 18, 2023
2 parents fa9ffff + a79d786 commit 346a110
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 46 deletions.
71 changes: 42 additions & 29 deletions apps/dashboard/src/main/java/com/akto/action/PostmanAction.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.json.JSONObject;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -76,47 +77,59 @@ public void setWorkspace_id(String workspace_id) {
this.workspace_id = workspace_id;
}

private ExecutorService executor = Executors.newSingleThreadExecutor();


private int apiCollectionId;
public String createPostmanApi() throws Exception {
public String createPostmanApi() throws Exception { // TODO: remove exception
PostmanCredential postmanCredential = fetchPostmanCredential();
if (postmanCredential == null) {
addActionError("Please add postman credentials in settings");
return ERROR.toUpperCase();
}
int accountId = Context.accountId.get();

Runnable r = () -> {
loggerMaker.infoAndAddToDb("Starting thread to create postman api", LogDb.DASHBOARD);
Context.accountId.set(accountId);
ApiCollection apiCollection = ApiCollectionsDao.instance.findOne(Filters.eq("_id", apiCollectionId));
if (apiCollection == null) {
return;
}
String apiName = "AKTO " + apiCollection.getDisplayName();

ApiCollection apiCollection = ApiCollectionsDao.instance.findOne(Filters.eq("_id", apiCollectionId));
if (apiCollection == null) {
return ERROR.toUpperCase();
}
String apiName = "AKTO " + apiCollection.getDisplayName();

List<SampleData> sampleData = SampleDataDao.instance.findAll(
Filters.eq("_id.apiCollectionId", apiCollectionId)
List<SampleData> sampleData = SampleDataDao.instance.findAll(
Filters.eq("_id.apiCollectionId", apiCollectionId)
);
String host = apiCollection.getHostName();
SampleDataToSTI sampleDataToSTI = new SampleDataToSTI();
sampleDataToSTI.setSampleDataToSTI(sampleData);
Map<String,Map<String, Map<Integer, List<SingleTypeInfo>>>> stiList = sampleDataToSTI.getSingleTypeInfoMap();
OpenAPI openAPI = com.akto.open_api.Main.init(apiCollection.getDisplayName(),stiList, true, host);
String openAPIStringAll = com.akto.open_api.Main.convertOpenApiToJSON(openAPI);

List<SensitiveSampleData> SensitiveSampleData = SensitiveSampleDataDao.instance.findAll(
Filters.eq("_id.apiCollectionId", apiCollectionId)
);
SampleDataToSTI sensitiveSampleDataToSTI = new SampleDataToSTI();
sensitiveSampleDataToSTI.setSensitiveSampleDataToSTI(SensitiveSampleData);
Map<String,Map<String, Map<Integer, List<SingleTypeInfo>>>> sensitiveStiList = sensitiveSampleDataToSTI.getSingleTypeInfoMap();
openAPI = com.akto.open_api.Main.init(apiCollection.getDisplayName(), sensitiveStiList, true, host);
String openAPIStringSensitive = com.akto.open_api.Main.convertOpenApiToJSON(openAPI);
String host = apiCollection.getHostName();
SampleDataToSTI sampleDataToSTI = new SampleDataToSTI();
sampleDataToSTI.setSampleDataToSTI(sampleData);
Map<String,Map<String, Map<Integer, List<SingleTypeInfo>>>> stiList = sampleDataToSTI.getSingleTypeInfoMap();
OpenAPI openAPI = null;
try {
openAPI = com.akto.open_api.Main.init(apiCollection.getDisplayName(),stiList, true, host);
} catch (Exception e) {
loggerMaker.errorAndAddToDb("Error while creating open api: " + e.getMessage(), LogDb.DASHBOARD);
return;
}
String openAPIStringAll = null;
try {
openAPIStringAll = com.akto.open_api.Main.convertOpenApiToJSON(openAPI);
} catch (Exception e) {
loggerMaker.errorAndAddToDb("Error while converting open api to json: " + e.getMessage(), LogDb.DASHBOARD);
return;
}

Main main = new Main(postmanCredential.getApiKey());
Map<String, String> openApiSchemaMap = new HashMap<>();
openApiSchemaMap.put("All", openAPIStringAll);
openApiSchemaMap.put("Sensitive", openAPIStringSensitive);
Main main = new Main(postmanCredential.getApiKey());
try {
main.createApiWithSchema(postmanCredential.getWorkspaceId(), apiName, openAPIStringAll);
} catch (Exception e){
loggerMaker.errorAndAddToDb("Error while creating api in postman: " + e.getMessage(), LogDb.DASHBOARD);
}
loggerMaker.infoAndAddToDb("Successfully created api in postman", LogDb.DASHBOARD);
};

main.createApiWithSchema(postmanCredential.getWorkspaceId(),apiName, openApiSchemaMap);
executorService.submit(r);

return SUCCESS.toUpperCase();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ function ApiEndpoints() {
async function exportPostman() {
const result = await api.exportToPostman(apiCollectionId)
if (result)
func.setToast(true, false, "Postman collection downloaded successfully")
func.setToast(true, false, "We have initiated export to Postman, checkout API section on your Postman app in sometime.")
}

function disambiguateLabel(key, value) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ export default {
var result = await this.$store.dispatch('inventory/exportToPostman')
window._AKTO.$emit('SHOW_SNACKBAR', {
show: true,
text: "Exported to Postman!",
text: "We have initiated export to Postman, checkout API section on your Postman app in sometime.",
color: 'green'
})
},
Expand Down
77 changes: 62 additions & 15 deletions libs/integrations/src/main/java/com/akto/postman/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.*;
Expand Down Expand Up @@ -109,11 +110,61 @@ public void addSchema(String apiId, String version, String openApiSchema) {

}

public void createApiWithSchema(String workspaceId, String apiName, Map<String, String> openApiSchemaMap) {
public String addSchemaV10(String apiId, String openApiSchema){
String url = BASE_URL + "apis/" + apiId + "?include=schemas";

JsonNode getNode = ApiRequest.getRequest(generateHeadersWithAuthForV10(),url);

Set<String> schemaIds = new HashSet<>();
if(getNode.has("schemas")) {
Iterator<JsonNode> schemas = getNode.get("schemas").elements();
while (schemas.hasNext()) {
schemaIds.add(schemas.next().get("id").textValue());
}
}
if(schemaIds.isEmpty()){
return createSchema(apiId, openApiSchema);
}
for (String schemaId: schemaIds) {
String url2 = BASE_URL + "apis/"+apiId+"/schemas/" + schemaId;
JsonNode response = ApiRequest.getRequest(generateHeadersWithAuthForV10(), url2);
JsonNode data = response.get("files").get("data");
while (data.elements().hasNext()){
JsonNode file = data.elements().next();
if(file.get("name").textValue().equals("index.json")){
String url1 = BASE_URL + "apis/"+apiId+"/schemas/" + schemaId + "/files/index.json";
JSONObject obj = new JSONObject();
obj.put("content", openApiSchema);
JsonNode node = ApiRequest.putRequest(generateHeadersWithAuthForV10(), url1, obj.toString());
return node.get("id").textValue();
}
}
}
return createSchema(apiId, openApiSchema);
}

private String createSchema(String apiId, String openApiSchema) {
String url1 = BASE_URL + "apis/"+ apiId +"/schemas";
JSONObject fileObj = new JSONObject();
fileObj.put("content", openApiSchema);
fileObj.put("path", "index.json");
JSONArray files = new JSONArray();
files.put(0, fileObj);

JSONObject child = new JSONObject();
child.put("files", files);
child.put("type", "openapi:3");

String json = child.toString();
JsonNode node = ApiRequest.postRequest(generateHeadersWithAuthForV10(), url1,json);
return node.get("id").textValue();
}

public void createApiWithSchema(String workspaceId, String apiName, String openApiSchema) {
// Get akto_<collectionName> API
String url = BASE_URL + "apis?name=" + apiName + "&" + "workspace=" + workspaceId;
String url = BASE_URL + "apis?name=" + apiName + "&" + "workspace=" + workspaceId; // TODO: created by me
JsonNode jsonNode = ApiRequest.getRequest(generateHeadersWithAuth(), url);
JsonNode apisNode = jsonNode.get("apis");
JsonNode apisNode = jsonNode.get("apis"); // TODO:
String apiId;

if (apisNode.elements().hasNext()) {
Expand All @@ -123,18 +174,7 @@ public void createApiWithSchema(String workspaceId, String apiName, Map<String,
// Create New API
apiId = createApi(workspaceId,apiName);
}

// get versions (if not present create them)
Map<String, String> apiVersionNameMap = getVersion(apiId,openApiSchemaMap.keySet());


for (String name: apiVersionNameMap.keySet()) {
// Finally, replace schema for all versions
addSchema(apiId, apiVersionNameMap.get(name), openApiSchemaMap.get(name));
}



addSchemaV10(apiId, openApiSchema);
}


Expand Down Expand Up @@ -168,6 +208,13 @@ public Map<String,String> generateHeadersWithAuth() {
return headersMap;
}

public Map<String,String> generateHeadersWithAuthForV10() {
Map<String,String> headersMap = new HashMap<>();
headersMap.put("X-API-Key",apiKey);
headersMap.put("Accept", "application/vnd.api.v10+json");
return headersMap;
}

public String createWorkspace() {
String url = BASE_URL + "workspaces";
JSONObject json = new JSONObject();
Expand Down

0 comments on commit 346a110

Please sign in to comment.