sriram.yeluri Absent Member.
Absent Member.
7778 views

How to create application in SSC with REST API

How to create application in SSC using rest API ?

I checked the API documentation and it is not clear. I tried to capture the request header and see token is used during the request. And when i tried to get token i am getting 200 as response but with empty response body. Any guidance in creating application using rest api ?

Labels (1)
0 Likes
16 Replies
Trusted Contributor.. stephen.b.burri Trusted Contributor..
Trusted Contributor..

Re: How to create application in SSC with REST API

So adding a Project/Application Version is a little tricky.  It actually takes 2 request to fully create a Project/Application Version.

The first request:

POST to /ssc/api/v1/projectVersions

Headers:

Authorization: FortifyToken ZWQ4YjJjOTAtMDU0OS00NGY0LWJiNTItYzRlZmFhM2Q1Nzhm

Content-Type: application/json

Accept: application/json

Payload:

{

  "name": "1.0",

  "description": "",

  "active": true,

  "committed": false,

  "project": {

    "name": "Test Application 2",

    "description": "",

    "issueTemplateId": "Prioritized-HighRisk-Project-Template"

  },

  "issueTemplateId": "Prioritized-HighRisk-Project-Template"

}

This request will come back with a lot of information, but you need to the the id field and use it in the next portion of the request.  In the example coming up, the ID was 10002

The second request:

POST to /ssc/api/v1/bulk

Headers:

Authorization: FortifyToken ZWQ4YjJjOTAtMDU0OS00NGY0LWJiNTItYzRlZmFhM2Q1Nzhm

Content-Type: application/json

Accept: application/json

Payload:

{

  "requests": [

    {

      "uri": "https:\/\/hp-laptop:8443\/ssc1620\/api\/v1\/projectVersions\/10002\/attributes",

      "httpVerb": "PUT",

      "postData": [

        {

          "attributeDefinitionId": 5,

          "values": [

            {

              "guid": "New"

            }

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 6,

          "values": [

            {

              "guid": "Internal"

            }

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 7,

          "values": [

            {

              "guid": "internalnetwork"

            }

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 10,

          "values": [

           

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 11,

          "values": [

           

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 12,

          "values": [

           

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 1,

          "values": [

            {

              "guid": "High"

            }

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 2,

          "values": [

           

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 3,

          "values": [

           

          ],

          "value": null

        },

        {

          "attributeDefinitionId": 4,

          "values": [

           

          ],

          "value": null

        }

      ]

    },

    {

      "uri": "https:\/\/hp-laptop:8443\/ssc1620\/api\/v1\/projectVersions\/10002\/responsibilities",

      "httpVerb": "PUT",

      "postData": [

        {

          "responsibilityGuid": "projectmanager",

          "userId": null

        },

        {

          "responsibilityGuid": "securitychampion",

          "userId": null

        },

        {

          "responsibilityGuid": "developmentmanager",

          "userId": null

        }

      ]

    },

    {

      "uri": "https:\/\/hp-laptop:8443\/ssc1620\/api\/v1\/projectVersions\/10002\/action",

      "httpVerb": "POST",

      "postData": [

        {

          "type": "COPY_FROM_PARTIAL",

          "values": {

            "projectVersionId": 10002,

            "previousProjectVersionId": -1,

            "copyAnalysisProcessingRules": true,

            "copyBugTrackerConfiguration": true,

            "copyCurrentStateFpr": false,

            "copyCustomTags": true

          }

        }

      ]

    },

    {

      "uri": "https:\/\/hp-laptop:8443\/ssc1620\/api\/v1\/projectVersions\/10002?hideProgress=true",

      "httpVerb": "PUT",

      "postData": {

        "committed": true

      }

    }

  ]

}

The second request is setting the required attribute fields for Project Versions, setting initial values for fields that are multi-select (basically setting to empty array).  Then lastly changing the committed value to true (the required fields are needed for this to take hold).

If you ever run into problems with the REST API, you can watch what the HTML5 front does, it uses the REST API in the back ground.  I used chrome to capture the network traffic on the Application Version creation wizard when the "Finish" button was clicked, two request went across the wire, projectVersions and bulk.  I looked at those to figure out the correct headers (except Authorization which I got from the REST API docs) and payload.

Re: How to create application in SSC with REST API

Hi, I created the application using the JSON Data provided. Now I am trying to create one more new version under the same application. How do I create it? when I modify the name in existing json it says "Project already exists"

 

0 Likes
mfeferman
New Member.

Re: How to create application in SSC with REST API

As someone who has written an application which can clone an entire SSC server to another SSC server, this is exactly correct.

Of course, the application can do much more than that, but this is the correct approach for this functionality.

http://vauntedsecurity.com

0 Likes
Dave Lawson
Visitor.

Re: How to create application in SSC with REST API

One extra thing to note. SSC appears to be case sensitive. I needed to change the two "IssueTemplateId" fields to "issueTemplateId" for a similar implementation.
0 Likes
Super Contributor.. ellerm Super Contributor..
Super Contributor..

Re: How to create application in SSC with REST API

I just wrote a solution in Python.  I'll post it soon.

0 Likes
Super Contributor.. ellerm Super Contributor..
Super Contributor..

Re: How to create application in SSC with REST API

import requests
import sys, getopt
from pprint import pprint

# Following are the steps that this script takes.
# Use Basic Auth to obtain a token
# Use token in order to perform a project lookup
# 	If the project doesn't exist, the project and project version will be created
#	1. Make call to projectVersions to create Project and Version
#   2. Make call to projectVersions/attributes to update the project attributes
#   3. Update projectVersions resource to be enabled.
# Use token in order to perform a project version lookup
# If the project version doesn't exist the project version will be created

baseURL = "http://<ssc server>:8080/ssc/api/v1/"
authURL = baseURL+"auth/obtain_token"
projectURL = baseURL+"projects?start=-1&limit=-1"


authHeaders = {
	'accept': "application/json, text/plain; */*",
	'content-type': "application/json;charset=UTF-8",
	'accept-encoding': "application/gzip",
	'cache-control': "no-cache",
	'authorization': "Basic <insert basic token>",
	}
#
# This function will get project information and return the assocaited project ID for the project
#
def getProject( projectHeaders, projectName, projectVersion, projectURL ):
	print "Performing Project Lookup....................\n"
	# Connect to Project Resource to get details on available projects
	print "Connecting to " + projectURL + " ...............................\n"

	try:
		projectResponse = requests.request("GET", projectURL, headers=projectHeaders)
	except requests.exceptions.RequestException as e:
		print e
		print "-------------------------------------- \n"
		print "Project Response Status Code = " + str(projectResponse.status_code) + "\n"
		print "-------------------------------------- \n"
		sys.exit(1)

	if projectResponse.status_code == 200 :
		projectJSON = projectResponse.json()
		projectList = projectJSON['data']

		for projectDict in projectList :
			if projectDict['name'] == projectName :
				projectID = projectDict['id']
				print "Project ID Was located.........................................\n"
				print "\n--------------- Project ID from Lookup,  " + str(projectID) + "\n"
				print "Project ID "+ str(projectID)
				versionID = getProjectVersion( projectHeaders, baseURL, projectID, projectVersion, projectName )
				return projectID;
				break
		else:
			print "Project ID was not found, creating new project...................................."
			
			returnedVersionID = createProject(projectName, projectVersion, projectHeaders )
			#print "Project ID after project creation " + str(versionID) + "\n"
			print "Project Version ID after project creation " + str(returnedVersionID) + "\n"
			updateProjectAttributes( projectHeaders, returnedVersionID, projectVersion, projectName)
			updateProject( projectHeaders, returnedVersionID, projectVersion, projectName )
			return returnedVersionID;

	else :
		print "Project Request experienced an error and returned response code " + str(projectResponse.status_code) + "\n"

#
# This function will get project version information and return the assocaited project ID for the project
#
def getProjectVersion( projectHeaders, baseURL, projectID, projectVersion, projectName ):
	#Get the Project Version data
	print "Looking up Project Version information.........................\n"
	projectVersionURL = baseURL+"projects/"+str(projectID)+"/versions"
	print "\nConnecting to " + projectVersionURL + " ...............................\n"
	try:
		projectVersionResponse = requests.request("GET", projectVersionURL, headers=projectHeaders)
	except requests.exceptions.RequestException as e:
		print e
		print "-------------------------------------- \n"
		print "Project Version Response Status Code = " + str(projectVersionResponse.status_code) + "\n"
		print "-------------------------------------- \n"
		sys.exit(1)

	if projectVersionResponse.status_code == 200 :
		projectVersionJSON = projectVersionResponse.json()
		#pprint(projectVersionJSON)
		# Grab the Data Dictionariy from the JSON
		projectVersionList = projectVersionJSON['data']
		#pprint( projectVersionList )
		# The project version call returns a list of dictionaries.  Loop through the list to get individual dictionaries
		# After obtaining the individial dictionaries look through each one to see if any of them have a projectVersion that matches
		# out project version.
		for projectVersionDict in projectVersionList :
			if projectVersionDict['name'] == projectVersion :
				lookupVersionID = projectVersionDict['id']
				print "Project Version ID Was located.........................................\n"
				print "\n--------------- Project Version ID is: " + str(lookupVersionID) + "\n"
				return lookupVersionID;
				break
		else:
			print "Project Version was not found, We need to create a new project ..............................\n"
			createVersion( projectHeaders, projectID, projectVersion, projectName )
	return;

def createProject (projectName, projectVersion, projectHeaders ):
	print "\n................................."
	print "\n Creating new project................................................"

	url = "http://<ssc server>:8080/ssc/api/v1/projectVersions"

	payload = "{\"project\":{\"name\":\""+projectName+"\",\"description\":\"Created with SSC Client\",\"issueTemplateId\":\"Prioritized-HighRisk-Project-Template\",\"committed\": \"true\"},\"masterAttrGuid\":\"87f2364f-dcd4-49e6-861d-f8d3f351686b\",\"name\":\""+projectVersion+"\",\"description\":\"Created with SSC Client\",\"issueTemplateId\":\"Prioritized-HighRisk-Project-Template\",\"owner\": \"SSC Client\",\"active\": \"true\",\"committed\": \"false\"}"
	try:
		response = requests.request("POST", url, data=payload, headers=projectHeaders)
	except requests.exceptions.RequestException as e:
		print e
		print "-------------------------------------- \n"
		print "Response Status Code = " + str(response.status_code) + "\n"
		print "-------------------------------------- \n"
		sys.exit(1)
	print "\n--------------- Project Creation JSON --------------- \n"
	print(response.text)
	if response.status_code == 201 :
		projectJSON = response.json()
		projectData = projectJSON['data']
		versionID = projectData['id']
		print "\n.............................. Project Version ID after Project Creation .............................. \n"
		print "ProjectVersionID = " + str(versionID)
		print "\n....................................................................................................... \n"
		return versionID;
	else:
		return;
		
def createVersion( projectHeaders, projectID, projectVersion, projectName ):
	print "Creating new Project Version.............................................\n"
	print "Creating project Version " + projectVersion + " with project ID of " + str(projectID) + "\n"
	url = "http://<ssc server>:8080/ssc/api/v1/projects/"+str(projectID)+"/versions"

	payload = "{\n\t\"masterAttrGuid\":\"87f2364f-dcd4-49e6-861d-f8d3f351686b\",\n\t\"name\":\""+projectVersion+"\",\n\t\"description\":\"Created with SSC Client\",\n\t\"issueTemplateId\":\"Prioritized-HighRisk-Project-Template\",\n\t\"owner\": \"SSC Client\",\n\t\"active\": \"true\",\n\t\"committed\": \"true\"\n}"
	print "Creating project version by connecting to " + url
	try:
		response = requests.request("POST", url, data=payload, headers=projectHeaders)
	except requests.exceptions.RequestException as e:
		print e
		print "-------------------------------------- \n"
		print "Response Status Code = " + str(response.status_code) + "\n"
		print "-------------------------------------- \n"
		sys.exit(1)
	print projectID
	print response.status_code
	if response.status_code == 201 :
		projectJSON = response.json()
		pprint( projectJSON )
		projectData = projectJSON['data']
		versionID = projectData['id']
		print "\n.............................. Project Version ID after Project Creation .............................. \n"
		print "ProjectVersionID = " + str(versionID)
		print "\n....................................................................................................... \n"
		updateProjectAttributes( projectHeaders, versionID, projectVersion, projectName )
		updateProject( projectHeaders, versionID, projectVersion, projectName )
		return;
	return;


def updateProjectAttributes( projectHeaders, projectID, projectVersion, projectName ):
	print "Updating Project Attributes ................................................\n"
	print "Updating project Attributes for project " + projectName + " with project id of, " + str(projectID) + "\n"
	url = "http://<ssc server>:8080/ssc/api/v1/projectVersions/" + str(projectID) + "/attributes"
	

	payload = "[\n\t{\n\t  \"guid\":\"DevPhase\",\n\t  \"attributeDefinitionId\":\"5\",\n\t  \"values\": [ \n\t\t\t\t  {\"guid\":\"Active\"} \n\t\t\t    ]\n\t},\n\t\t{\n\t\t\"guid\":\"Accessibility\",\n\t\t\"attributeDefinitionId\":\"7\",\n\t\t\"values\": [\n\t\t\t\t\t{\"guid\":\"externalpublicnetwork\"}\n\t\t\t\t  ]\n\t},\n\t{\n\t\t\"guid\":\"DevStrategy\",\n\t\t\"attributeDefinitionId\":\"6\",\n\t\t\"values\": [\n\t\t\t\t\t{\"guid\":\"Internal\"}\n\t\t\t\t  ]\n\t}\n\n]\n\t\n\t\n\t"

	try:
		response = requests.request("PUT", url, data=payload, headers=projectHeaders)
	except requests.exceptions.RequestException as e:
		print e
		print "-------------------------------------- \n"
		print "Response Status Code = " + str(response.status_code) + "\n"
		print "-------------------------------------- \n"
		sys.exit(1)

	print "Project Attribute Update Completed................................\n"
	return;

def updateProject( projectHeaders, projectID, projectVersion, projectName ):
	print "Updating Project Version Status to Committed ................................................\n"
	print "Changing Project Version Status to Committed for project " + projectName + " with with project id of, " + str(projectID) + "\n"
	
	url = "http://<ssc server>:8080/ssc/api/v1/projectVersions/"+str(projectID)+"/"
	print "Connecting to " + url
	
	payload = "{\"project\":{\"name\":\""+projectName+"\",\"description\":\"Created with SSC Client\",\"issueTemplateId\":\"Prioritized-HighRisk-Project-Template\",\"committed\": \"true\"},\"masterAttrGuid\":\"87f2364f-dcd4-49e6-861d-f8d3f351686b\",\"name\":\""+projectVersion+"\",\"description\":\"Created with SSC Client\",\"issueTemplateId\":\"Prioritized-HighRisk-Project-Template\",\"owner\": \"SSC CLIENT\",\"active\": \"true\",\"committed\": \"true\"}"
	print payload
	try:
		response = requests.request("PUT", url, data=payload, headers=projectHeaders)
		print(response.text)
	except requests.exceptions.RequestException as e:
		print e
		print "-------------------------------------- \n"
		print "Response Status Code = " + str(response.status_code) + "\n"
		print "-------------------------------------- \n"
		sys.exit(1)
	return;
	
def main(argv):

	projectName = ''
	projectVersion = ''
	
	try:
		opts, args = getopt.getopt(argv, "hn:v:d", ["help", "projectName=", "projectVersion="])
	except getopt.GetoptError:
		print 'ssc-client.py -n <projectName> -v <projectVersion>'
		sys.exit(2)
	for opt, arg in opts:
		if opt == '-h':
			print 'ssc-client.py -n <projectName> -v <projectVersion>'
			sys.exit()
		elif opt in ("-n", "--projectName"):
			projectName = arg
		elif opt in ("-v", "--projectVersion"):
			projectVersion = arg
	print "\nProject Name entered is: " + projectName
	print "\nProject Version entered is: " + projectVersion
	print "\nPerforming Initial Authentication................................."
	print "\nConnecting to " + authURL + "\n"

	try:
		authResponse = requests.request("POST", authURL, headers=authHeaders)
	except requests.exceptions.RequestException as e:
		print e
		print "-------------------------------------- \n"
		print "Auth Response Status Code = " + str(authResponse.status_code) + "\n"
		print "-------------------------------------- \n"
		sys.exit(1)

	if authResponse.status_code == 200 :

		authJSON = authResponse.json()
		data = authJSON['data']
		sscToken = data['token']
		print "SSC Token: " + sscToken + "\n"

		projectHeaders = {
			'accept': "application/json, text/plain, */*",
			'cache-control': "no-cache",
			'authorization': "FortifyToken "+sscToken,
			'content-type': "application/json; charset=utf-8",
			'accept-encoding': "gzip, deflate",
			}

		#projectID = getProject( projectHeaders, projectName, projectVersion, projectURL )
		getProject( projectHeaders, projectName, projectVersion, projectURL )

	else :
		print "Auth Request experienced an error and returned response code " + str(authResponse.status_code) + "\n"

if __name__ == "__main__":
	main(sys.argv[1:])
cfzhao Frequent Contributor.
Frequent Contributor.

Re: How to create application in SSC with REST API

Hi Ellerm,

I can create application by your python script, after that, how can add user to this project? I can not find the API on Swagger UI.

0 Likes
Respected Contributor.. dgarozzo Respected Contributor..
Respected Contributor..

Re: How to create application in SSC with REST API

I believe this is done with the responsibilities API call, however, I can only see options to assign a Project Manager, a Security Manager, and a Development Manager. There does not appear to be an option to assign to the "TEAM". Does anybody know if it is possible to use the API to assign to the "TEAM"?

0 Likes
cfzhao Frequent Contributor.
Frequent Contributor.

Re: How to create application in SSC with REST API

You are right. I also can not find the TEAM enties in the responsibliitles API. And I check the ldap user API, just delete is right, others is returned 501 Internal error  with user id. I think this is bug.

Helping SSC TEAM can provide the scirpt to add ldap user and hwo to add user to project version let us automation all processing. 

0 Likes
Super Contributor.. ellerm Super Contributor..
Super Contributor..

Re: How to create application in SSC with REST API

This is something I'm not sure about since I don't do that.  In my environment I have the security team set up as admins so they automatically get access to any new projects created.  The development teams get added manually since we have at least 40 dev teams.  We use this in our CI environments to automatically create projects in SSC for scanning based upon the project being created in Bitbucket so at the time of creation I don't know which development team needs to see the project (besides our software security team).

MJ Hartman Trusted Contributor.
Trusted Contributor.

Re: How to create application in SSC with REST API

I based my jenkins pipeline groovy script on this Python example, but get stuck on creating a version (Fortify 17.20):

def response = httpRequest validResponseCodes: "200:500",
url: "https://fortify.cgn.canon-europa.com/ssc/api/v1/projects/" + idR12 + "/versions",
httpMode: "POST",
customHeaders:[[name: "Authorization", value: "FortifyToken " + token]],
contentType: "APPLICATION_JSON"
requestBody: '''{
"masterAttrGuid" : "87f2364f-dcd4-49e6-861d-f8d3f351686b",
"name": "R12 CH1234",
"description": "CH1234",
"issueTemplateId": "Prioritized-HighRisk-Project-Template",
"owner": "marjo.hartman",
"active": true,
"committed": true
}'''

Result:

[Pipeline] httpRequestHttpMethod: POST
URL: https://fortify.cgn.canon-europa.com/ssc/api/v1/projects/23/versions
Content-type: application/json
Authorization: *****
Sending request to url: https://fortify.cgn.canon-europa.com/ssc/api/v1/projects/23/versions
Response Code: HTTP/1.1 500 
Success code from [200‥500]
[Pipeline] echoContent: {"message":"Content was incorrectly formatted (expected Unknown).","responseCode":500,"errorCode":-20209}

I think the message is formatted in the same way as in the Python example code. But the result tells me it is wrongly formatted.

0 Likes
Super Contributor.. ellerm Super Contributor..
Super Contributor..

Re: How to create application in SSC with REST API

You might want to check the masterAttrGuid and issueTemplateId in your system to make sure that they're valid in your system.  You should be able to find these values in the issueTemplateId table in your database.  It's possible that they changed for your version.

0 Likes
MJ Hartman Trusted Contributor.
Trusted Contributor.

Re: How to create application in SSC with REST API

I used the same masterAttrGuid  and issueTemplateId defined with an existing version.

And I expect that wrong values would not result in a "wrong format" result.

0 Likes
Agilan Frequent Contributor.
Frequent Contributor.

Re: How to create application in SSC with REST API

Hello,

Did you get resolution for the issue. I too getting the same error, I tested in the swagger documentation with the same values and it worked. But throwing error when calling from the CI pipeline. FYI, I used the same credentials.

Thanks

0 Likes
The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.