Skip to content

Commit 17bc1a7

Browse files
Additional user methods, refactoring
1 parent 4bdf401 commit 17bc1a7

File tree

3 files changed

+64
-52
lines changed

3 files changed

+64
-52
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,12 @@ The following methods call Veracode REST APIs and return JSON.
4343
- `scantype`: Defaults to STATIC findings, but can be STATIC, DYNAMIC, MANUAL, SCA, or ALL (static, dynamic, manual).
4444
- `annot`: Defaults to TRUE but can be FALSE
4545
- `get_users()`: get a list of users for the organization.
46+
- `get_user_self()`: get user information for the current user.
4647
- `get_user(user_guid)`: get information for an individual user based on `user_guid`.
48+
- `get_user_by_name(username)`: look up info for an individual user based on their user_name.
4749
- `get_creds()`: get credentials information (API ID and expiration date) for the current user.
4850
- `update_user(user_guid, roles)`: update the user identified by `user_guid` with the list of roles passed in `roles`. Because the Identity API does not support adding a single role, the list should be the entire list of existing roles for the user plus whatever new roles. See [veracode-user-bulk-role-assign](https://github.com/tjarrettveracode/veracode-user-bulk-role-assign) for an example.
51+
- `disable_user(user_guid)`: set the `Active` flag the user identified by `user_guid` to `False`.
4952
- `get_workspaces()`: get a list of SCA Agent workspaces for the organization.
5053
- `get_workspace_by_name(name)`: get a list of SCA Agent workspaces whose name partially matches `name`.
5154
- `create_workspace(name)`: create an SCA Agent workspace named `name`. Returns the GUID for the workspace.

setup.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,19 @@
33
setup(
44
name = 'veracode_api_py',
55
packages = ['veracode_api_py'],
6-
version = '0.9',
6+
version = '0.9.1',
77
license='MIT',
88
description = 'Python helper library for working with the Veracode APIs. Handles retries, pagination, and other features of the modern Veracode REST APIs.',
99
author = 'Tim Jarrett',
1010
author_email = 'tjarrett@veracode.com',
1111
url = 'https://github.com/tjarrettveracode',
12-
download_url = 'https://github.com/tjarrettveracode/veracode-api-py/archive/v_07.tar.gz',
12+
download_url = 'https://github.com/tjarrettveracode/veracode-api-py/archive/v_091.tar.gz',
1313
keywords = ['veracode', 'veracode-api'],
1414
install_requires=[
1515
'veracode-api-signing'
1616
],
1717
classifiers=[
18-
'Development Status :: 3 - Alpha', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package
18+
'Development Status :: 4 - Beta', # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package
1919
'Intended Audience :: Developers',
2020
'Topic :: Software Development :: Build Tools',
2121
'License :: OSI Approved :: MIT License',

veracode_api_py/api.py

Lines changed: 58 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212
import time
1313
import requests
1414
import logging
15+
import json
1516
from requests.adapters import HTTPAdapter
17+
from requests.packages.urllib3.util.retry import Retry
18+
1619

1720
from veracode_api_signing.exceptions import VeracodeAPISigningException
1821
from veracode_api_signing.plugin_requests import RequestsAuthPluginVeracodeHMAC
@@ -64,63 +67,54 @@ def _request(self, url, method, params=None):
6467
raise VeracodeAPIError(e)
6568

6669
def _rest_request(self, url, method, params=None,body=None,fullresponse=False):
67-
# base request method for a REST request
68-
myheaders = {"User-Agent": "api.py"}
69-
if method in ["POST", "PUT"]:
70-
myheaders.update({'Content-type': 'application/json'})
70+
# base request method for a REST request
71+
myheaders = {"User-Agent": "api.py"}
72+
if method in ["POST", "PUT"]:
73+
myheaders.update({'Content-type': 'application/json'})
74+
75+
retry_strategy = Retry(total=3,
76+
status_forcelist=[429, 500, 502, 503, 504],
77+
method_whitelist=["HEAD", "GET", "OPTIONS"]
78+
)
79+
session = requests.Session()
80+
session.mount(self.base_rest_url, HTTPAdapter(max_retries=retry_strategy))
7181

82+
try:
7283
if method == "GET":
73-
# incorporate retries to deal with some failure situations
74-
try:
75-
session = requests.Session()
76-
session.mount(self.base_rest_url, HTTPAdapter(max_retries=3))
77-
request = requests.Request(method, self.base_rest_url + url, params=params, auth=RequestsAuthPluginVeracodeHMAC(), headers=myheaders)
78-
prepared_request = request.prepare()
79-
r = session.send(prepared_request, proxies=self.proxies)
80-
if r.status_code == 500 or r.status_code == 504:
81-
time.sleep(1)
82-
r = requests.Request(method, url, params=params, auth=RequestsAuthPluginVeracodeHMAC(),headers=myheaders,json=body)
83-
except requests.exceptions.RequestException as e:
84-
logging.exception(self.connect_error_msg)
85-
raise VeracodeAPIError(e)
84+
request = requests.Request(method, self.base_rest_url + url, params=params, auth=RequestsAuthPluginVeracodeHMAC(), headers=myheaders)
85+
prepared_request = request.prepare()
86+
r = session.send(prepared_request, proxies=self.proxies)
8687
elif method == "POST":
87-
try:
88-
r = requests.post(self.base_rest_url + url,params=params,auth=RequestsAuthPluginVeracodeHMAC(),headers=myheaders,data=body)
89-
except requests.exceptions.RequestException as e:
90-
logging.exception(self.connect_error_msg)
91-
raise VeracodeAPIError(e)
88+
r = requests.post(self.base_rest_url + url,params=params,auth=RequestsAuthPluginVeracodeHMAC(),headers=myheaders,data=body)
9289
elif method == "PUT":
93-
try:
94-
r = requests.put(self.base_rest_url + url,params=params,auth=RequestsAuthPluginVeracodeHMAC(), headers=myheaders,data=body)
95-
except requests.exceptions.RequestException as e:
96-
logging.exception(self.connect_error_msg)
97-
raise VeracodeAPIError(e)
90+
r = requests.put(self.base_rest_url + url,params=params,auth=RequestsAuthPluginVeracodeHMAC(), headers=myheaders,data=body)
9891
elif method == "DELETE":
99-
try:
100-
r = requests.delete(self.base_rest_url + url,params=params,auth=RequestsAuthPluginVeracodeHMAC(),headers=myheaders)
101-
except requests.exceptions.RequestException as e:
102-
logging.exception(self.connect_error_msg)
103-
raise VeracodeAPIError(e)
92+
r = requests.delete(self.base_rest_url + url,params=params,auth=RequestsAuthPluginVeracodeHMAC(),headers=myheaders)
10493
else:
10594
raise VeracodeAPIError("Unsupported HTTP method")
95+
except requests.exceptions.RequestException as e:
96+
logging.exception(self.connect_error_msg)
97+
raise VeracodeAPIError(e)
10698

107-
if not (r.status_code == requests.codes.ok):
108-
logging.debug("API call returned non-200 HTTP status code: {}".format(r.status_code))
99+
if not (r.status_code == requests.codes.ok):
100+
logging.debug("API call returned non-200 HTTP status code: {}".format(r.status_code))
109101

110-
if not (r.ok):
111-
logging.debug("Error retrieving data. HTTP status code: {}".format(r.status_code))
112-
if r.status_code == 401:
113-
logging.exception("Check that your Veracode API account credentials are correct.")
114-
else:
115-
logging.exception("Error [{}]: {} for request {}".format(r.status_code,r.text, r.request.url))
116-
raise requests.exceptions.RequestException()
117-
elif fullresponse:
118-
return r
102+
if not (r.ok):
103+
logging.debug("Error retrieving data. HTTP status code: {}".format(r.status_code))
104+
if r.status_code == 401:
105+
logging.exception("Check that your Veracode API account credentials are correct.")
119106
else:
120-
if r.text != "":
121-
return r.json()
122-
else:
123-
return ""
107+
logging.exception("Error [{}]: {} for request {}".
108+
format(r.status_code, r.text, r.request.url))
109+
raise requests.exceptions.RequestException()
110+
111+
if fullresponse:
112+
return r
113+
114+
if r.text != "":
115+
return r.json()
116+
else:
117+
return ""
124118

125119
def _rest_paged_request(self, url, method, element, params=None):
126120
all_data = []
@@ -137,7 +131,7 @@ def _rest_paged_request(self, url, method, element, params=None):
137131
page += 1
138132
more_pages = page < total_pages
139133
return all_data
140-
134+
141135
#xml apis
142136

143137
def get_app_list(self):
@@ -233,18 +227,33 @@ def get_users(self):
233227
request_params = {'page': 0} #initialize the page request
234228
return self._rest_paged_request("api/authn/v2/users","GET","users",request_params)
235229

230+
def get_user_self (self):
231+
#Gets the user info for the current user, using the Veracode Identity API
232+
return self._rest_request("api/authn/v2/users/self","GET")
233+
236234
def get_user(self,user_guid):
237235
#Gets an individual user provided their GUID, using the Veracode Identity API
238236
uri = "api/authn/v2/users/{}".format(user_guid)
239237
return self._rest_request(uri,"GET")
240238

239+
def get_user_by_name(self,username):
240+
#Gets all the users who match the provided email address, using the Veracode Identity API
241+
request_params = {'user_name': username} #initialize the page request
242+
return self._rest_paged_request("api/authn/v2/users","GET","users",request_params)
243+
241244
def get_creds (self):
242245
return self._rest_request("api/authn/v2/api_credentials","GET")
243246

244247
def update_user (self,user_guid,roles):
245248
request_params = {'partial':'TRUE',"incremental": 'TRUE'}
246249
uri = "api/authn/v2/users/{}".format(user_guid)
247-
return self._rest_request(uri,"PUT",request_params,roles)
250+
return self._rest_request(uri,"PUT",request_params,roles)
251+
252+
def disable_user (self,user_guid):
253+
request_params = {'partial':'TRUE'}
254+
uri = 'api/authn/v2/users/{}'.format(user_guid)
255+
payload = json.dumps({'active': False})
256+
return self._rest_request(uri,"PUT",request_params,payload)
248257

249258
## SCA APIs - note must be human user to use these, not API user
250259

0 commit comments

Comments
 (0)