Пример #1
0
    def login(self, refresh: bool = False) -> Authentication:
        """Creates user credentials to authenticate with Azure Quantum

        It will first try to read the credentials from a secure local cache
        (the location of the cache can be specified via the AZURE_QUANTUM_TOKEN_CACHE environent variable).
        If it the cache is empty or expired, then it uses the device token flow from MSAL (https://github.com/AzureAD/microsoft-authentication-library-for-python)
        to acquire a token from AAD.

        If successful, it stores the acquired token in the cache for future calls.

        :param refresh:
            if true, by-passes the cache and fetches a fresh token from AAD.

        :returns:
            the user credentials to authenticate with Azure Quantum
        """

        # We only clear the credentials if they are of type BasicTokenAuthentication
        if refresh and isinstance(self.credentials, BasicTokenAuthentication):
            self.credentials = None

        if self.credentials is None:
            msal_wrapper = MsalWrapper(subscription_id=self.subscription_id,
                                       refresh=refresh)

            auth_token = msal_wrapper.acquire_auth_token()
            return BasicTokenAuthentication(token=auth_token)

        # When we already have an object of type Authentication, like
        # the ServicePrincipalCredentials, we should NOT wrap it in a BasicTokenAuthentication
        if not isinstance(self.credentials, Authentication):
            return BasicTokenAuthentication(token=self.credentials)

        return self.credentials
    def signed_session(self):
        basic_authentication = BasicTokenAuthentication({"access_token": self.get_access_token()})
        session = basic_authentication.signed_session()

        # If there is no microsoft_app_id and no self.microsoft_app_password, then there shouldn't
        # be an "Authorization" header on the outgoing activity.
        if not self.microsoft_app_id and not self.microsoft_app_password:
            del session.headers['Authorization']
        return session
Пример #3
0
    def test_basic_token_auth(self):

        token = {'access_token': '123456789'}
        basic = BasicTokenAuthentication(token)
        basic.set_token()  # Just check that this does not raise
        session = basic.signed_session()

        req = session.prepare_request(self.request)
        assert 'Authorization' in req.headers
        assert req.headers['Authorization'] == 'Bearer 123456789'
    def signed_session(self) -> requests.Session:
        """
        Gets the signed session.
        :returns: Signed requests.Session object
        """
        auth_token = asyncio.ensure_future(self.get_access_token())

        basic_authentication = BasicTokenAuthentication({"access_token": auth_token})
        session = basic_authentication.signed_session()

        # If there is no microsoft_app_id and no self.microsoft_app_password, then there shouldn't
        # be an "Authorization" header on the outgoing activity.
        if not self.microsoft_app_id and not self.microsoft_app_password:
            del session.headers['Authorization']
        return session
    def signed_session(self) -> requests.Session:  # pylint: disable=arguments-differ
        """
        Gets the signed session.
        :returns: Signed requests.Session object
        """
        auth_token = self.get_access_token()

        basic_authentication = BasicTokenAuthentication({"access_token": auth_token})
        session = basic_authentication.signed_session()

        # If there is no microsoft_app_id and no self.microsoft_app_password, then there shouldn't
        # be an "Authorization" header on the outgoing activity.
        if not self.microsoft_app_id and not self.microsoft_app_password:
            del session.headers["Authorization"]
        return session
    def test_custom_base_uri_positive(self):
        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        config = AutoRestParameterizedHostTestClientConfiguration(cred, host="host:3000")

        config.log_level = log_level
        client = AutoRestParameterizedHostTestClient(config)
        client.paths.get_empty("local")
Пример #7
0
    def test_transformation_api(self):
        creds = BasicTokenAuthentication(
            {'access_token': os.environ['INGEST_TOKEN']})
        client = BingCommerceIngestion(creds)

        query_parameters = {}
        query_parameters['traffictype'] = 'test'

        index_id = ensure_index(client, self.TENANT_ID, query_parameters)

        script = ("retailSearchInput({\n"
                  "    format: 'TSV'\n"
                  "});\n"
                  "\n"
                  "transform((product, rawProduct) => {\n"
                  "    \n"
                  "});\n"
                  "retailSearchOutput({});")

        create_script_response = client.create_or_update_transformation_config(
            script, self.TENANT_ID, index_id)
        read_script_response = client.get_transformation_config(
            self.TENANT_ID, index_id)
        delete_script_response = client.delete_transformation_config(
            self.TENANT_ID, index_id)

        assert script == delete_script_response.value

        try:
            client.get_transformation_config(self.TENANT_ID, index_id)
            assert False
        except HttpOperationError as e:
            assert e.response.status_code == 400
Пример #8
0
    def test_tryout_transformation(self):
        creds = BasicTokenAuthentication({
            'access_token':
            'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjRmZGI5N2ZhLWQyYWItNDY1Mi1iMWE0LWM3Y2E3YTBhNDJmNSJ9.eyJhdWQiOiIxZTE0MmJhOC1kNzU1LTQ0ZDAtOGFlYS03YjJiNTI0NjZhMTMiLCJhcHBpZCI6ImM3MzhhZTBhMWE0ZDEwMzYyMjEzMGNkZjUyNTgxMWQ3MGEwMzI5ZGUiLCJub25jZSI6ImYzMTc2NGY2LWEzNGItZjMxOC05MDAzLWJjY2FlNzE0Yjg0MCIsInNjcCI6IkFkbWluLkVudmlyb25tZW50LlJlYWRXcml0ZSBBZG1pbi5Sb2xlTWFuYWdlbWVudC5SZWFkV3JpdGUgQWRtaW4uVG9rZW4uQ3JlYXRlIEFkbWluLlRva2VuLlJldm9rZSBTZWFyY2guQXV0b3N1Z2dlc3QuUmVhZFdyaXRlIFNlYXJjaC5JbmRleC5SZWFkV3JpdGUgU2VhcmNoLkN1c3RvbWl6YXRpb24uUmVhZFdyaXRlIiwiaW5zdGFuY2VzIjoiIiwiaGFzQWNjZXNzVG9BbGxJbnN0YW5jZXMiOnRydWUsImlhdCI6MTU3ODk1NjM4MywiZXhwIjoxOTI1MTA3MTIzLCJ0aWRzIjpbImY5OGQ3OWI4LTY0MzItNDhjZC1iNTg4LWZiMjIwZWRjYjgxNiJdLCJ2ZXIiOiIxLjAifQ.XybtgWMilIAyoOw4k8Lc7k5tQ2ztthEbo1VJfs7rX0JT4Crj6PU9_AyIBRYVZMvJfriBWy_M8M5c9nQaHV3vcWM5pZkPCrKF1yaTYy2C76ffZjZBILoQkR_chG4rZECvv8x0U28WnbiW5Z9FZEfRR-8feD46oo2XmXvLH6SaJr2JbNItEPlqPBZ1kO-Z5ie34h-fdZergk-WjE3n8yD4ZUJXys-_B4vWXDqFMOGENS-VAuJkVED0QJdI6937LIiFm_mhITl26ZXr2beGv0Pn9z25O477nGvv4vqT07LzZ3eS7Bh7TAnPuzdzSKgG2IJqEHFmGk-y9bL4dwFbOLPeAQ'
        })  #os.environ['INGEST_TOKEN'] })
        client = BingCommerceIngestion(creds)

        query_parameters = {}
        query_parameters['traffictype'] = 'test'

        index_id = ensure_index(client, self.TENANT_ID, query_parameters)

        script = ('retailSearchInput({\n'
                  '    format: \"TSV\"\n'
                  '});\n'
                  '\n'
                  'transform((product, rawProduct) => {\n'
                  '    \n'
                  '});\n'
                  'retailSearchOutput({});')

        data = ("id\ttitle\n" "1\tSample Product")

        create_script_response = client.upload_try_out_config(script)
        execute_response = client.execute_try_out_config(
            data, create_script_response.try_out_id)

        assert 'Succeeded' == execute_response.status
Пример #9
0
 def setUp(self):
     cred = BasicTokenAuthentication({"access_token": str(uuid4())})
     self.client = AutoRestPagingTestService(
         cred, base_url="http://localhost:3000")
     self.client._client._adapter.add_hook(
         "request", self.client._client._adapter._test_pipeline)
     return super(PagingTests, self).setUp()
    def get_vault_uri(self, vault_name: str) -> str:
        """
        Return the URI for a vault name.

        Parameters
        ----------
        vault_name : str
            The Vault name.

        Returns
        -------
        str
            Vault URI.

        """
        cred = BasicTokenAuthentication(
            {"access_token": self.auth_client.token})
        mgmt = KeyVaultManagementClient(cred, self.subscription_id)
        try:
            vault = mgmt.vaults.get(self.resource_group, vault_name)
        except (CloudError, ResourceNotFoundError) as cloud_err:
            raise MsticpyKeyVaultConfigError(
                "Check that you have specified the right value for VaultName" +
                " in your configuration",
                f"Error returned from provider was {cloud_err}",
                title="Key Vault vault '{vault_name}' not found.",
            )
        return vault.properties.vault_uri
    def post_output_to_pr(self, organization_uri, project, repo_id,
                          pull_request_id, access_token, comment_content):
        if comment_content == '':
            print(
                f"{vso_task_skipped if self.enable_vso_output else ''}No Cloud Custodian output found in output dir"
            )
            sys.exit()

        # Create a connection to the org
        token = {'access_token': access_token}
        credentials = BasicTokenAuthentication(token)
        connection = VssConnection(base_url=organization_uri,
                                   creds=credentials)

        # Get a git client
        git_client = connection.get_client(
            "vsts.git.v4_1.git_client.GitClient")

        new_comment = Comment(content=comment_content)
        comments = [new_comment]
        comment_thread = GitPullRequestCommentThread(comments=comments)

        try:
            # Create a comment based on the cloud custodian output
            resp = git_client.create_thread(comment_thread, repo_id,
                                            pull_request_id, project)
            print(
                f"{vso_task_succeeded if self.enable_vso_output else ''}Successfully updated the pull request {pull_request_id}, the comment thread id is: {resp.id}"
            )
        except Exception as e:
            print(
                f"{vso_task_skipped if self.enable_vso_output else ''}Unable to post comment to PR: {pull_request_id}, {e}"
            )
            sys.exit(1)
Пример #12
0
    def create_workspace(self) -> Workspace:
        """Create workspace using credentials stored in config file

        :return: Workspace
        :rtype: Workspace
        """

        workspace = Workspace(
            subscription_id=self.subscription_id,
            resource_group=self.resource_group,
            name=self.workspace_name,
        )

        if self.is_live or self.in_recording:
            workspace.credentials = ServicePrincipalCredentials(
                tenant=self.tenant_id,
                client_id=self.client_id,
                secret=self.client_secret,
                resource="https://quantum.microsoft.com")
            workspace.login(False)
        else:
            workspace.credentials = BasicTokenAuthentication(
                token=self.dummy_auth_token)

        return workspace
    def test_MatchAll(self):
        creds = BasicTokenAuthentication({ 'access_token': os.environ['SEARCH_TOKEN'] })
        client = BingCommerceSearch(creds)
        tenant_id = os.environ['SEARCH_TENANT']
        index_id = os.environ['SEARCH_INDEX']

        request = CommerceSearchPostRequest(
            query = RequestQuery(match_all = 'diamond'), 
            items = RequestItems(select = ['_itemId', 'name']))

        query_parameters = {}
        query_parameters['traffictype'] = 'test'

        response = client.search.post(request, tenant_id, index_id, query_parameters)

        assert response is not None
        assert response.items is not None
        assert response.items.total_estimated_matches is not None
        assert response.items.value is not None

        assert response.items.total_estimated_matches > 0
        assert len(response.items.value) > 0

        for item in response.items.value:
            assert item is not None
            assert item.item_id is not None
            assert item.fields is not None
            assert item.fields['name'] is not None
    def __create_storage_account_and_get_key(self):
        basic_token_auth = BasicTokenAuthentication(
            {'access_token': self.__get_access_token()})
        client = StorageManagementClient(basic_token_auth,
                                         self.__subscription_id)

        storage_accounts = list(
            client.storage_accounts.list_by_resource_group(
                self.__resource_group))
        if (not any(
            [x.name == self.__storage_account_name
             for x in storage_accounts])):
            print("Creating storage account", self.__storage_account_name)
            client.storage_accounts.create(
                self.__resource_group, self.__storage_account_name,
                StorageAccountCreateParameters(
                    sku=Sku(SkuName.standard_ragrs),
                    kind=Kind.storage,
                    location=self.__location)).result()
            print("Created storage account", self.__storage_account_name)

        storage_keys = client.storage_accounts.list_keys(
            self.__resource_group, self.__storage_account_name)
        storage_keys = {v.key_name: v.value for v in storage_keys.keys}

        return storage_keys['key1']
Пример #15
0
    def setUp(self):
        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        config = AutoRestPagingTestServiceConfiguration(cred, base_url="http://localhost:3000")
        config.log_level = log_level
        self.client = AutoRestPagingTestService(config)

        return super(PagingTests, self).setUp()
Пример #16
0
    def setUp(self):

        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        self.client = AutoRestLongRunningOperationTestService(cred, base_url="http://localhost:3000")
        self.client._client.creds = TestAuthentication()
        self.client.config.long_running_operation_timeout = 0
        return super(LroTests, self).setUp()
Пример #17
0
    def get_credentials(self):
        if self.access_token:
            return BasicTokenAuthentication(
                {'access_token': self.access_token})

        token = get_env("VSTS_PAT")
        return BasicAuthentication("ignored", token)
Пример #18
0
    def setUpClass(cls):
        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        config = AutoRestParameterizedHostTestClientConfiguration(cred, host="host:3000")

        config.log_level = log_level
        cls.client = AutoRestParameterizedHostTestClient(config)
        return super(CustomBaseUriTests, cls).setUpClass()
    def create_vault(self, vault_name: str) -> Vault:
        """
        Create new or update existing vault.

        Parameters
        ----------
        vault_name : str
            Name of the Vault

        Returns
        -------
        Vault
            The Vault object.

        """
        if not self.azure_region:
            raise MsticpyKeyVaultConfigError(
                "Could not get Azure region in which to create the vault.",
                "Please add AzureRegion to the KeyVault section of msticpyconfig.yaml",
                title="missing AzureRegion value.",
            )
        parameters = self._get_params()
        cred = BasicTokenAuthentication(
            {"access_token": self.auth_client.token})
        if not self.resource_group:
            raise MsticpyKeyVaultConfigError(
                "Could not get Azure resource group in which to create the vault.",
                "Please add ResourceGroup to the KeyVault section of msticpyconfig.yaml",
                title="missing ResourceGroup value.",
            )
        mgmt = KeyVaultManagementClient(cred, self.subscription_id)
        vault = mgmt.vaults.create_or_update(self.resource_group, vault_name,
                                             parameters).result()
        return vault
Пример #20
0
    def test_Push(self):
        creds = BasicTokenAuthentication(
            {'access_token': os.environ['INGEST_TOKEN']})
        client = BingCommerceIngestion(creds)

        query_parameters = {}
        query_parameters['traffictype'] = 'test'

        index_id = ensure_index(client, self.TENANT_ID, query_parameters)

        push_response = client.push_data_update(
            'Test Content',
            self.TENANT_ID,
            index_id,
            notransform=False,
            query_parameters=query_parameters)
        assert push_response is not None
        assert push_response.update_id is not None

        push_status = client.push_data_status(
            self.TENANT_ID,
            index_id,
            push_response.update_id,
            query_parameters=query_parameters)
        assert push_status is not None
        assert push_status.status is not None
    def _find_using_common_tenant(self, access_token, resource):
        import adal
        from msrest.authentication import BasicTokenAuthentication

        all_subscriptions = []
        token_credential = BasicTokenAuthentication(
            {'access_token': access_token})
        client = self._arm_client_factory(token_credential)
        tenants = client.tenants.list()
        for t in tenants:
            tenant_id = t.tenant_id
            temp_context = self._create_auth_context(tenant_id)
            try:
                temp_credentials = temp_context.acquire_token(
                    resource, self.user_id, _CLIENT_ID)
            except adal.AdalError as ex:
                # because user creds went through the 'common' tenant, the error here must be
                # tenant specific, like the account was disabled. For such errors, we will continue
                # with other tenants.
                logger.warning("Failed to authenticate '%s' due to error '%s'",
                               t, ex)
                continue
            subscriptions = self._find_using_specific_tenant(
                tenant_id, temp_credentials[_ACCESS_TOKEN])
            all_subscriptions.extend(subscriptions)

        return all_subscriptions
Пример #22
0
def client():
    """Create a AutoRestLongRunningOperationTestService client with test server credentials."""
    cred = BasicTokenAuthentication({"access_token": str(uuid4())})
    with AutoRestLongRunningOperationTestService(
            cred, base_url="http://localhost:3000") as client:
        client.config.long_running_operation_timeout = 0  # In theory pointless, since we use AutorestTestARMPolling
        yield client
Пример #23
0
    def test_parameter_grouping(self):

        bodyParameter = 1234
        headerParameter = 'header'
        queryParameter = 21
        pathParameter = 'path'

        cred = BasicTokenAuthentication({"access_token": str(uuid4())})
        client = AutoRestParameterGroupingTestService(
            cred, base_url="http://localhost:3000")

        # Valid required parameters
        requiredParameters = ParameterGroupingPostRequiredParameters(
            body=bodyParameter,
            path=pathParameter,
            custom_header=headerParameter,
            query=queryParameter)
        client.parameter_grouping.post_required(requiredParameters)

        #Required parameters but null optional parameters
        requiredParameters = ParameterGroupingPostRequiredParameters(
            body=bodyParameter, path=pathParameter, query=None)
        client.parameter_grouping.post_required(requiredParameters)

        #Required parameters object is not null, but a required property of the object is
        requiredParameters = ParameterGroupingPostRequiredParameters(
            body=None, path=pathParameter)

        with self.assertRaises(ValidationError):
            client.parameter_grouping.post_required(requiredParameters)
        with self.assertRaises(ValidationError):
            client.parameter_grouping.post_required(None)

        #Valid optional parameters
        optionalParameters = ParameterGroupingPostOptionalParameters(
            custom_header=headerParameter, query=queryParameter)
        client.parameter_grouping.post_optional(optionalParameters)

        #null optional paramters
        client.parameter_grouping.post_optional(None)

        #Multiple grouped parameters
        firstGroup = FirstParameterGroup(header_one=headerParameter,
                                         query_one=queryParameter)
        secondGroup = ParameterGroupingPostMultiParamGroupsSecondParamGroup(
            header_two="header2", query_two=42)

        client.parameter_grouping.post_multi_param_groups(
            firstGroup, secondGroup)

        #Multiple grouped parameters -- some optional parameters omitted
        firstGroup = FirstParameterGroup(header_one=headerParameter)
        secondGroup = ParameterGroupingPostMultiParamGroupsSecondParamGroup(
            query_two=42)

        client.parameter_grouping.post_multi_param_groups(
            firstGroup, secondGroup)
        client.parameter_grouping.post_shared_parameter_group_object(
            firstGroup)
Пример #24
0
    def test_head(self):

        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        client = AutoRestHeadTestService(cred, base_url="http://localhost:3000")

        self.assertTrue(client.http_success.head200())
        self.assertTrue(client.http_success.head204())
        self.assertFalse(client.http_success.head404())
Пример #25
0
    def setUp(self):

        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        self.client = AutoRestLongRunningOperationTestService(cred, base_url="http://localhost:3000")

        self.client.config.long_running_operation_timeout = 0
        self.client._client._adapter.add_hook("request", self.client._client._adapter._test_pipeline)
        return super(LroTests, self).setUp()
Пример #26
0
    def test_xms_request_client_id_in_client(self):
        validSubscription = '1234-5678-9012-3456'
        expectedRequestId = '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'

        cred = BasicTokenAuthentication({"access_token":123})
        client = AutoRestAzureSpecialParametersTestClient(cred, validSubscription, base_url="http://localhost:3000")
        client.config.generate_client_request_id = False
        client.xms_client_request_id.get()
Пример #27
0
    def test_azure_odata(self):

        validSubscription = '1234-5678-9012-3456'
        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        config = AutoRestAzureSpecialParametersTestClientConfiguration(cred, validSubscription, base_url="http://localhost:3000")
        config.log_level = log_level
        client = AutoRestAzureSpecialParametersTestClient(config)
        client.odata.get_with_filter(filter="id gt 5 and name eq 'foo'", top=10, orderby="id")
Пример #28
0
    def test_head_exception(self):

        cred = BasicTokenAuthentication({"access_token" :str(uuid4())})
        client = AutoRestHeadExceptionTestService(cred, base_url="http://localhost:3000")

        client.head_exception.head200()
        client.head_exception.head204()
        with self.assertRaises(CloudError):
            client.head_exception.head404()
Пример #29
0
 def _find_using_specific_tenant(self, tenant, access_token):
     token_credential = BasicTokenAuthentication(
         {'access_token': access_token})
     client = self._arm_client_factory(token_credential)
     subscriptions = client.subscriptions.list()
     all_subscriptions = []
     for s in subscriptions:
         setattr(s, 'tenant_id', tenant)
         all_subscriptions.append(s)
     return all_subscriptions
Пример #30
0
    def test_custom_named_request_id(self):

        validSubscription = '1234-5678-9012-3456'
        expectedRequestId = '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'

        cred = BasicTokenAuthentication({"access_token":123})
        client = AutoRestAzureSpecialParametersTestClient(cred, validSubscription, base_url="http://localhost:3000")

        response = client.header.custom_named_request_id(expectedRequestId, raw=True)
        assert "123" ==  response.response.headers.get("foo-request-id")