def get_cache_key( self, data_source: Optional[ToucanDataSource] = None, permissions: Optional[dict] = None, offset: int = 0, limit: Optional[int] = None, ) -> str: """ Generate a unique identifier (str) for a given connector's configuration (if no parameters are supplied) or for a given couple connector/query configuration (if `data_source` parameter is supplied). This identifier will then be used as a cache key. """ unique_identifier = { 'connector': self.get_unique_identifier(), 'permissions': nosql_apply_parameters_to_query(permissions, data_source.parameters) if data_source else permissions, 'offset': offset, 'limit': limit, } if data_source is not None: unique_identifier['datasource'] = self._get_unique_datasource_identifier(data_source) json_uid = JsonWrapper.dumps(unique_identifier, sort_keys=True, default=hash) string_uid = str(uuid.uuid3(uuid.NAMESPACE_OID, json_uid)) return string_uid
def test_fail_retrieve_tokens(oauth2_connector, secrets_keeper): """ It should fail ig the stored state does not match the received state """ secrets_keeper.save('test', {'state': JsonWrapper.dumps({'token': 'the_token'})}) with pytest.raises(AssertionError): oauth2_connector.retrieve_tokens( f'http://localhost/?state={JsonWrapper.dumps({"token": "bad_token"})}' )
def get_identifier(self): json_uid = JsonWrapper.dumps( { 'name': self.name, 'account': self.account, 'client_id': self.client_id, 'scope': self.scope, 'role': self.role, }, sort_keys=True, ) string_uid = str(uuid.uuid3(uuid.NAMESPACE_OID, json_uid)) return string_uid
def build_authorization_url(self, **kwargs) -> str: """Build an authorization request that will be sent to the client.""" client = OAuth2Session( client_id=self.config.client_id, client_secret=self.config.client_secret.get_secret_value(), redirect_uri=self.redirect_uri, scope=self.scope, ) state = {'token': generate_token(), **kwargs} uri, state = client.create_authorization_url( self.authorization_url, state=JsonWrapper.dumps(state)) self.secrets_keeper.save(self.auth_flow_id, {'state': state}) return uri
def test_retrieve_tokens(mocker, oauth2_connector, secrets_keeper): """ It should retrieve tokens and save them """ secrets_keeper.save('test', {'state': JsonWrapper.dumps({'token': 'the_token'})}) mock_fetch_token: Mock = mocker.patch( 'toucan_connectors.oauth2_connector.oauth2connector.OAuth2Session.fetch_token', return_value={'access_token': 'dummy_token'}, ) oauth2_connector.retrieve_tokens( f'http://localhost/?state={JsonWrapper.dumps({"token": "the_token"})}') mock_fetch_token.assert_called() assert secrets_keeper.load('test')['access_token'] == 'dummy_token'
def retrieve_data_with_jwt(self, data_source: RokDataSource, endpoint: str) -> str: """Query ROK API with JWT crafted based on the ROK secret to get the Data""" # Claims defined with ROK payload = { 'aud': 'Rok-solution', 'iss': 'ToucanToco', 'exp': str(int((datetime.now() + timedelta(minutes=10)).timestamp())), 'email': self.username, 'iat': str(int(datetime.now().timestamp())), 'nbf': str(int(datetime.now().timestamp())), } encoded_payload = encode(payload, base64.b64decode(self.secret.encode('utf-8')), algorithm='HS256') headers = { 'DatabaseName': data_source.database, 'JwtString': encoded_payload, 'Accept': 'application/json', 'Content-Type': 'application/json', } try: res = requests.post(url=endpoint, data=JsonWrapper.dumps( {'query': data_source.query}), headers=headers).json() except JSONDecodeError: raise InvalidJWTError('Invalid request, JWT not validated by ROK') if res.get('Message'): if 'not authenticated' in res['Message']: raise InvalidUsernameError('Invalid username') else: raise ValueError(res['Message']) return res
def test_json_dumps(): result = JsonWrapper.dumps(json_json) assert json_string == result
def get_identifier(self): json_uid = JsonWrapper.dumps(self.get_unique_identifier(), sort_keys=True) string_uid = str(uuid.uuid3(uuid.NAMESPACE_OID, json_uid)) return string_uid