def __init__(self, options=None, session=None): if options and options.get('baseUrl'): raise exceptions.TaskclusterFailure( 'baseUrl option is no longer allowed') o = copy.deepcopy(self.classOptions) o.update(_defaultConfig) if options: o.update(options) if not o.get('rootUrl'): raise exceptions.TaskclusterFailure('rootUrl option is required') credentials = o.get('credentials') if credentials: for x in ('accessToken', 'clientId', 'certificate'): value = credentials.get(x) if value and not isinstance(value, six.binary_type): try: credentials[x] = credentials[x].encode('ascii') except: s = '%s (%s) must be unicode encodable' % ( x, credentials[x]) raise exceptions.TaskclusterAuthFailure(s) self.options = o if 'credentials' in o: log.debug('credentials key scrubbed from logging output') log.debug(dict((k, v) for k, v in o.items() if k != 'credentials')) if session: self.session = session else: self.session = self._createSession()
def _makeHttpRequest(self, method, route, payload): """ Make an HTTP Request for the API endpoint. This method wraps the logic about doing failure retry and passes off the actual work of doing an HTTP request to another method.""" url = self._constructUrl(route) log.debug('Full URL used is: %s', url) hawkExt = self.makeHawkExt() # Serialize payload if given if payload is not None: payload = utils.dumpJson(payload) # Do a loop of retries retry = -1 # we plus first in the loop, and attempt 1 is retry 0 retries = self.options['maxRetries'] while retry < retries: retry += 1 # if this isn't the first retry then we sleep if retry > 0: time.sleep(utils.calculateSleepTime(retry)) # Construct header if self._hasCredentials(): sender = mohawk.Sender( credentials={ 'id': self.options['credentials']['clientId'], 'key': self.options['credentials']['accessToken'], 'algorithm': 'sha256', }, ext=hawkExt if hawkExt else {}, url=url, content=payload if payload else '', content_type='application/json' if payload else '', method=method, ) headers = {'Authorization': sender.request_header} else: log.debug('Not using hawk!') headers = {} if payload: # Set header for JSON if payload is given, note that we serialize # outside this loop. headers['Content-Type'] = 'application/json' log.debug('Making attempt %d', retry) try: response = utils.makeSingleHttpRequest(method, url, payload, headers) except requests.exceptions.RequestException as rerr: if retry < retries: log.warn('Retrying because of: %s' % rerr) continue # raise a connection exception raise exceptions.TaskclusterConnectionError( "Failed to establish connection", superExc=rerr) # Handle non 2xx status code and retry if possible status = response.status_code if status == 204: return None # Catch retryable errors and go to the beginning of the loop # to do the retry if 500 <= status and status < 600 and retry < retries: log.warn('Retrying because of a %s status code' % status) continue # Throw errors for non-retryable errors if status < 200 or status >= 300: data = {} try: data = response.json() except: pass # Ignore JSON errors in error messages # Find error message message = "Unknown Server Error" if isinstance(data, dict): message = data.get('message') else: if status == 401: message = "Authentication Error" elif status == 500: message = "Internal Server Error" # Raise TaskclusterAuthFailure if this is an auth issue if status == 401: raise exceptions.TaskclusterAuthFailure(message, status_code=status, body=data, superExc=None) # Raise TaskclusterRestFailure for all other issues raise exceptions.TaskclusterRestFailure(message, status_code=status, body=data, superExc=None) # Try to load JSON try: return response.json() except ValueError: return {"response": response} # This code-path should be unreachable assert False, "Error from last retry should have been raised!"
def buildSignedUrl(self, methodName, *args, **kwargs): """ Build a signed URL. This URL contains the credentials needed to access a resource.""" if 'expiration' in kwargs: expiration = kwargs['expiration'] del kwargs['expiration'] else: expiration = self.options['signedUrlExpiration'] expiration = int( time.time() + expiration) # Mainly so that we throw if it's not a number requestUrl = self.buildUrl(methodName, *args, **kwargs) if not self._hasCredentials(): raise exceptions.TaskclusterAuthFailure('Invalid Hawk Credentials') clientId = utils.toStr(self.options['credentials']['clientId']) accessToken = utils.toStr(self.options['credentials']['accessToken']) def genBewit(): # We need to fix the output of get_bewit. It returns a url-safe base64 # encoded string, which contains a list of tokens separated by '\'. # The first one is the clientId, the second is an int, the third is # url-safe base64 encoded MAC, the fourth is the ext param. # The problem is that the nested url-safe base64 encoded MAC must be # base64 (i.e. not url safe) or server-side will complain. # id + '\\' + exp + '\\' + mac + '\\' + options.ext; resource = mohawk.base.Resource( credentials={ 'id': clientId, 'key': accessToken, 'algorithm': 'sha256', }, method='GET', ext=utils.toStr(self.makeHawkExt()), url=requestUrl, timestamp=expiration, nonce='', # content='', # content_type='', ) bewit = mohawk.bewit.get_bewit(resource) return bewit.rstrip('=') bewit = genBewit() if not bewit: raise exceptions.TaskclusterFailure('Did not receive a bewit') u = urllib.parse.urlparse(requestUrl) qs = u.query if qs: qs += '&' qs += 'bewit=%s' % bewit return urllib.parse.urlunparse(( u.scheme, u.netloc, u.path, u.params, qs, u.fragment, ))