def get_jira_auth_from_request(request): # https://developer.atlassian.com/static/connect/docs/latest/concepts/authentication.html # Extract the JWT token from the request's jwt query # parameter or the authorization header. token = request.GET.get("jwt") if token is None: raise ApiError("No token parameter") # Decode the JWT token, without verification. This gives # you a header JSON object, a claims JSON object, and a signature. decoded = jwt.decode(token, verify=False) # Extract the issuer ('iss') claim from the decoded, unverified # claims object. This is the clientKey for the tenant - an identifier # for the Atlassian application making the call issuer = decoded["iss"] # Look up the sharedSecret for the clientKey, as stored # by the add-on during the installation handshake from sentry_plugins.jira_ac.models import JiraTenant jira_auth = JiraTenant.objects.get(client_key=issuer) # Verify the signature with the sharedSecret and # the algorithm specified in the header's alg field. decoded_verified = jwt.decode(token, jira_auth.secret) # Verify the query has not been tampered by Creating a Query Hash # and comparing it against the qsh claim on the verified token. # TODO: probably shouldn't need to hardcode get... for post maybe # the secret should just be a hidden field in the form ? qsh = get_query_hash(request.path, "GET", request.GET) # qsh = get_query_hash(request.path, request.method, request.GET) if qsh != decoded_verified["qsh"]: raise ApiError("Query hash mismatch") return jira_auth
def get_issue(self, repo, issue_id): try: return self.request( "GET", "/projects/{}/issues/{}".format(quote(repo, safe=""), issue_id)) except IndexError: raise ApiError("Issue not found with ID", 404)
def get_issue(self, repo, issue_id): try: return self.request( 'GET', '/projects/{}/issues/{}'.format(quote(repo, safe=''), issue_id)) except IndexError: raise ApiError('Issue not found with ID', 404)
def request(self, method, version, path, data=None, params=None, json=True): oauth = OAuth1(six.text_type(settings.BITBUCKET_CONSUMER_KEY), six.text_type(settings.BITBUCKET_CONSUMER_SECRET), self.auth.tokens['oauth_token'], self.auth.tokens['oauth_token_secret'], signature_type='auth_header') session = build_session() try: resp = getattr(session, method.lower())( url='%s%s%s' % (self.API_URL, version, path), auth=oauth, data=(data if version == '1.0' else None), json=(data if version == '2.0' else None), params=params, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) if resp.status_code == 204: return {} if json: return resp.json() else: return resp.text
def get_issue(self, repo, issue_id): try: return self.request( 'GET', '/projects/{}/issues'.format(quote(repo, safe=''), ), params={ # XXX(dcramer): this is an undocumented API 'iid': issue_id, })[0] except IndexError: raise ApiError('Issue not found with ID', 404)
def get_create_meta_for_project(self, project): metas = self.get_create_meta(project) # We saw an empty JSON response come back from the API :( if not metas: return None # XXX(dcramer): document how this is possible, if it even is if len(metas["projects"]) > 1: raise ApiError("More than one project found.") try: return metas["projects"][0] except IndexError: return None
def request(self, method, path, data): payload = { 'k': self.privatekey, } payload.update(data) session = build_session() try: resp = getattr(session, method.lower())( url='{}{}'.format(self.base_url, path), data=payload, allow_redirects=True, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def request(self, method, path, data=None, params=None): headers = { 'Private-Token': self.token, } session = build_session() try: resp = getattr(session, method.lower())( url='{}/api/v4/{}'.format(self.url, path.lstrip('/')), headers=headers, json=data, params=params, allow_redirects=False, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def request(self, data): endpoint = 'https://alert.victorops.com/integrations/generic/20131114/alert/{}/{}'.format( self.api_key, self.routing_key, ) session = build_session() try: resp = session.post( url=endpoint, json=data, allow_redirects=False, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def request(self, data): payload = { 'service_key': self.service_key, } payload.update(data) session = build_session() try: resp = session.post( url=INTEGRATION_API_URL, json=payload, allow_redirects=False, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def request(self, method, path, data=None, params=None): headers = { 'Authorization': 'token %s' % self.token, } session = build_session() try: resp = getattr(session, method.lower())( url='{}{}'.format(self.url, path), headers=headers, json=data, params=params, allow_redirects=True, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def _request(self, token, method, path, data=None, params=None): headers = { 'Authorization': 'Bearer %s' % token, } session = build_session() try: resp = getattr(session, method.lower())( url='%s%s' % (self.API_URL, path), headers=headers, json=data, params=params, allow_redirects=False, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def _request(self, method, path, headers=None, data=None, params=None): session = build_session() try: resp = getattr(session, method.lower())( url='{}{}'.format(self.url, path), headers=headers, json=data, params=params, allow_redirects=True, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) if resp.status_code == 204: return {} return resp.json()
def request(self, method, path, data=None, params=None): oauth = OAuth1(unicode(settings.BITBUCKET_CONSUMER_KEY), unicode(settings.BITBUCKET_CONSUMER_SECRET), self.auth.tokens['oauth_token'], self.auth.tokens['oauth_token_secret'], signature_type='auth_header') session = build_session() try: resp = getattr(session, method.lower())( url='%s%s' % (self.API_URL, path), auth=oauth, data=data, params=params, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def test_notify_failure(self): errors = ( ApiError("The server is sad"), SSLError("[SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:590)"), HTTPError("A bad response"), PluginError("A plugin is sad"), ) for err in errors: n = DummyNotificationPlugin() n.slug = "slack" def hook(*a, **kw): raise err event = self.store_event(data={}, project_id=self.project.id) notification = Notification(event) n.notify_users = hook assert n.notify(notification) is False
def test_test_configuration_and_get_test_results(self): errors = ( ApiError("The server is sad"), ApiHostError("host error"), ApiUnauthorized("not used"), ) for err in errors: n = DummyNotificationPlugin() n.slug = "slack" def hook(*a, **kw): n.raise_error(err) n.notify_users = hook if isinstance(err, ApiUnauthorized): message = "your access token was invalid" else: message = err.text assert message assert message in n.test_configuration_and_get_test_results(self.project)
def request(self, method, path, data): # see https://pushover.net/api # We can no longer send JSON because pushover disabled incoming # JSON data: http://updates.pushover.net/post/39822700181/ payload = { 'user': self.userkey, 'token': self.apikey, } payload.update(data) session = build_session() try: resp = getattr(session, method.lower())( url='{}{}'.format(self.base_url, path), data=payload, allow_redirects=False, ) resp.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return resp.json()
def make_request(self, method, url, payload=None): if url[:4] != "http": url = self.zendesk_url + url auth = self.username.encode('utf8'), self.password.encode('utf8') session = build_session() if method == 'get': response = session.get(url, params=payload, auth=auth, verify=False, timeout=self.HTTP_TIMEOUT) else: response = session.post(url, json=payload, auth=auth, verify=False, timeout=self.HTTP_TIMEOUT) try: response.raise_for_status() except HTTPError as e: raise ApiError.from_response(e.response) return response