import requests
import time
import jwt
import datetime as dt
import json
except Exception as err:
print('ERROR :', err)
exit(-1)
# get file name
def getFileName():
file_name = input("\nEnter the File name of access keys (User_apikey.json)\n")
return file_name
def getCredentials(file_name):
# open credentials file
try:
with open(file_name, 'r') as file:
content = file.read()
return json.loads(content)
except FileNotFoundError:
print(f"⛔ The file '{file_name}' could not be found.")
exit(-1)
except Exception as e:
print(f"⛔ An error occurred while trying to open the file: {e}")
exit(-1)
return {}
# API headers
def api_headers(credentials):
seconds_to_expiry = 3600
exp = time.time() + seconds_to_expiry
expiry = dt.datetime.fromtimestamp(exp).strftime('%Y-%m-%d %H:%M')
domain = credentials['domain']
customerId = credentials['customerId']
key = credentials['key']
secret = credentials['secret']
token = jwt.encode({'iss':key, 'exp':exp}, secret, algorithm='HS256')
auth = f'Bearer {token}'
creds = {'domain':domain,'customerId':customerId}
creds['Expiration'] = expiry
creds['Authorization'] = auth
return creds
# API POST Call
def POSTCall(url, creds, payload):
response = requests.post(url, headers=creds, data=payload)
data = response.json()
status_code = response.status_code
return data, status_code
# check if API call is failed
def check_api_call_status(response, status_code):
if status_code not in [200, 201, 202, 204]:
print(f'API call failed with status code {status_code}\n\n {response}\n\n')
exit(-1)
# save data to json file
def save_to(fileName, data):
try:
with open(f'{fileName}.json', 'w') as f:
f.write(json.dumps(data))
print(f"\nOutput stored to {fileName}.json\n")
except Exception as err:
print(f'\nFailed to store data to {fileName}.json\n{err}')
def main():
file_name = getFileName()
credentials = getCredentials(file_name)
domain = credentials['domain']
customerId = credentials['customerId']
print (f'\n✅ Credentials read for domain {domain}\n')
creds = api_headers(credentials)
resourceId = input("\nEnter the Correct Resource Id of the Asset\n")
resourceType = "HOST_SBOM" if input("\nEnter the resource type: HOST_SBOM (1) | IMAGE_SBOM (2)\n") == "1" else "IMAGE_SBOM"
formatType = "CycloneDX" if input("\nEnter the format spdx (1) | CycloneDX (2)\n") == "2" else "SPDX"
# Format the URL
url = f'https://{domain}.uptycs.io/public/api/v2/customers/{customerId}/sbom'
# payload
payload = {
"name": resourceType, # Host(HOST_SBOM) or Image(IMAGE_SBOM)
"resourceId": resourceId, # Uptycs AssetId or UUID
"resourceName": "ASDWNAADSP001.corp.root.nasd.com", # this is optional. Use this if you know hostname instead of asset id
"format": formatType # output format spdx (or) CycloneDX
}
print("\n\nQuery Posted for execution....\n")
response, status_code = POSTCall(url, creds, payload)
check_api_call_status(response, status_code)
print(f"Query is {response['status']} \n")
# call the API until it finishes
while response['status'] != 'FINISHED':
response, status_code = POSTCall(url, creds, payload)
check_api_call_status(response, status_code)
print(f"Query is {response['status']}\n")
time.sleep(1)
outputFileName = input('Enter the outfile Name to store api response without file extension\n')
save_to(outputFileName, response)
if __name__ == "__main__":
main()