|
| 1 | +import logging |
| 2 | +import requests |
| 3 | +import json |
| 4 | +from operator import itemgetter |
| 5 | +import urllib.parse |
| 6 | + |
| 7 | +logger = logging.getLogger(__name__) |
| 8 | + |
| 9 | +def read_config(self): |
| 10 | + try: |
| 11 | + with open('.restconfig.json','r') as f: |
| 12 | + self.config = json.load(f) |
| 13 | + except: |
| 14 | + logging.error(f"Unable to load configuration from '.restconfig.json'. Make sure you create one with proper connection and authentication values for your Black Duck server") |
| 15 | + raise |
| 16 | + |
| 17 | +def write_config(self): |
| 18 | + with open(self.configfile,'w') as f: |
| 19 | + json.dump(self.config, f, indent=3) |
| 20 | + |
| 21 | +def get_auth_token(self): |
| 22 | + api_token = self.config.get('api_token', False) |
| 23 | + if api_token: |
| 24 | + authendpoint = "/api/tokens/authenticate" |
| 25 | + url = self.config['baseurl'] + authendpoint |
| 26 | + session = requests.session() |
| 27 | + response = session.post( |
| 28 | + url, |
| 29 | + data={}, |
| 30 | + headers={'Authorization': 'token {}'.format(api_token)}, |
| 31 | + verify=not self.config['insecure'] |
| 32 | + ) |
| 33 | + csrf_token = response.headers['X-CSRF-TOKEN'] |
| 34 | + try: |
| 35 | + bearer_token = json.loads(response.content.decode('utf-8'))['bearerToken'] |
| 36 | + except json.decoder.JSONDecodeError as e: |
| 37 | + logger.exception("Authentication failure, could not obtain bearer token") |
| 38 | + raise Exception("Failed to obtain bearer token, check for valid authentication token") |
| 39 | + return (bearer_token, csrf_token, None) |
| 40 | + else: |
| 41 | + authendpoint="/j_spring_security_check" |
| 42 | + url = self.config['baseurl'] + authendpoint |
| 43 | + session=requests.session() |
| 44 | + credentials = dict() |
| 45 | + credentials['j_username'] = self.config['username'] |
| 46 | + credentials['j_password'] = self.config['password'] |
| 47 | + response = session.post(url, credentials, verify= not self.config['insecure']) |
| 48 | + cookie = response.headers['Set-Cookie'] |
| 49 | + token = cookie[cookie.index('=')+1:cookie.index(';')] |
| 50 | + return (token, None, cookie) |
| 51 | + |
| 52 | +def _get_hub_rest_api_version_info(self): |
| 53 | + '''Get the version info from the server, if available |
| 54 | + ''' |
| 55 | + session = requests.session() |
| 56 | + url = self.config['baseurl'] + "/api/current-version" |
| 57 | + response = session.get(url, verify = not self.config['insecure']) |
| 58 | + |
| 59 | + if response.status_code == 200: |
| 60 | + version_info = response.json() |
| 61 | + if 'version' in version_info: |
| 62 | + return version_info |
| 63 | + else: |
| 64 | + raise UnknownVersion("Did not find the 'version' key in the response to a successful GET on /api/current-version") |
| 65 | + else: |
| 66 | + raise UnknownVersion("Failed to retrieve the version info from {}, status code {}".format(url, response.status_code)) |
| 67 | + |
| 68 | +def _get_major_version(self): |
| 69 | + return self.version_info['version'].split(".")[0] |
| 70 | + |
| 71 | +def get_urlbase(self): |
| 72 | + return self.config['baseurl'] |
| 73 | + |
| 74 | +def get_headers(self): |
| 75 | + if self.config.get('api_token', False): |
| 76 | + return { |
| 77 | + 'X-CSRF-TOKEN': self.csrf_token, |
| 78 | + 'Authorization': 'Bearer {}'.format(self.token), |
| 79 | + 'Accept': 'application/json', |
| 80 | + 'Content-Type': 'application/json'} |
| 81 | + else: |
| 82 | + if self.bd_major_version == "3": |
| 83 | + return {"Cookie": self.cookie} |
| 84 | + else: |
| 85 | + return {"Authorization":"Bearer " + self.token} |
| 86 | + |
| 87 | +def get_api_version(self): |
| 88 | + url = self.get_urlbase() + '/api/current-version' |
| 89 | + response = self.execute_get(url) |
| 90 | + version = response.json().get('version', 'unknown') |
| 91 | + return version |
| 92 | + |
| 93 | +def _get_parameter_string(self, parameters={}): |
| 94 | + parameter_string = "&".join(["{}={}".format(k,urllib.parse.quote(str(v))) for k,v in sorted(parameters.items(), key=itemgetter(0))]) |
| 95 | + return "?" + parameter_string |
| 96 | + |
| 97 | +def get_tags_url(self, component_or_project): |
| 98 | + # Utility method to return the tags URL from either a component or project object |
| 99 | + url = None |
| 100 | + for link_d in component_or_project['_meta']['links']: |
| 101 | + if link_d['rel'] == 'tags': |
| 102 | + return link_d['href'] |
| 103 | + return url |
| 104 | + |
| 105 | +def get_link(self, bd_rest_obj, link_name): |
| 106 | + # returns the URL for the link_name OR None |
| 107 | + if bd_rest_obj and '_meta' in bd_rest_obj and 'links' in bd_rest_obj['_meta']: |
| 108 | + for link_obj in bd_rest_obj['_meta']['links']: |
| 109 | + if 'rel' in link_obj and link_obj['rel'] == link_name: |
| 110 | + return link_obj.get('href', None) |
| 111 | + else: |
| 112 | + logger.warning("This does not appear to be a BD REST object. It should have ['_meta']['links']") |
| 113 | + |
| 114 | +def get_limit_paramstring(self, limit): |
| 115 | + return "?limit={}".format(limit) |
| 116 | + |
| 117 | +def get_apibase(self): |
| 118 | + return self.config['baseurl'] + "/api" |
| 119 | + |
| 120 | +def execute_delete(self, url): |
| 121 | + headers = self.get_headers() |
| 122 | + response = requests.delete(url, headers=headers, verify = not self.config['insecure']) |
| 123 | + return response |
| 124 | + |
| 125 | +def _validated_json_data(self, data_to_validate): |
| 126 | + if isinstance(data_to_validate, dict) or isinstance(data_to_validate, list): |
| 127 | + json_data = json.dumps(data_to_validate) |
| 128 | + else: |
| 129 | + json_data = data_to_validate |
| 130 | + json.loads(json_data) # will fail with JSONDecodeError if invalid |
| 131 | + return json_data |
| 132 | + |
| 133 | +def execute_get(self, url, custom_headers={}): |
| 134 | + headers = self.get_headers() |
| 135 | + headers.update(custom_headers) |
| 136 | + response = requests.get(url, headers=headers, verify = not self.config['insecure']) |
| 137 | + return response |
| 138 | + |
| 139 | +def execute_put(self, url, data, custom_headers={}): |
| 140 | + json_data = self._validated_json_data(data) |
| 141 | + headers = self.get_headers() |
| 142 | + headers["Content-Type"] = "application/json" |
| 143 | + headers.update(custom_headers) |
| 144 | + response = requests.put(url, headers=headers, data=json_data, verify = not self.config['insecure']) |
| 145 | + return response |
| 146 | + |
| 147 | +def _create(self, url, json_body): |
| 148 | + response = self.execute_post(url, json_body) |
| 149 | + # v4+ returns the newly created location in the response headers |
| 150 | + # and there is nothing in the response json |
| 151 | + # whereas v3 returns the newly created object in the response json |
| 152 | + if response.status_code == 201: |
| 153 | + if "location" in response.headers: |
| 154 | + return response.headers["location"] |
| 155 | + else: |
| 156 | + try: |
| 157 | + response_json = response.json() |
| 158 | + except json.decoder.JSONDecodeError: |
| 159 | + logger.warning('did not receive any json data back') |
| 160 | + else: |
| 161 | + if '_meta' in response_json and 'href' in response_json['_meta']: |
| 162 | + return response_json['_meta']['href'] |
| 163 | + else: |
| 164 | + return response_json |
| 165 | + elif response.status_code == 412: |
| 166 | + raise CreateFailedAlreadyExists("Failed to create the object because it already exists - url {}, body {}, response {}".format(url, json_body, response)) |
| 167 | + else: |
| 168 | + raise CreateFailedUnknown("Failed to create the object for an unknown reason - url {}, body {}, response {}".format(url, json_body, response)) |
| 169 | + |
| 170 | +def execute_post(self, url, data, custom_headers={}): |
| 171 | + json_data = self._validated_json_data(data) |
| 172 | + headers = self.get_headers() |
| 173 | + headers["Content-Type"] = "application/json" |
| 174 | + headers.update(custom_headers) |
| 175 | + response = requests.post(url, headers=headers, data=json_data, verify = not self.config['insecure']) |
| 176 | + return response |
| 177 | + |
| 178 | +def get_matched_components(self, version_obj, limit=9999): |
| 179 | + url = "{}/matched-files".format(version_obj['_meta']['href']) |
| 180 | + param_string = self._get_parameter_string({'limit': limit}) |
| 181 | + url = "{}{}".format(url, param_string) |
| 182 | + response = self.execute_get(url) |
| 183 | + return response.json() |
0 commit comments