Exemple #1
0
    def test_e2e(self, vault, storage_account, resource_group, **kwargs):
        # find the role definition for "Storage Account Key Operator Service Role"
        filter_str = 'roleName eq \'Storage Account Key Operator Service Role\''
        authorization_mgmt_client = self.create_mgmt_client(
            AuthorizationManagementClient)
        role_id = list(
            authorization_mgmt_client.role_definitions.list(
                scope='/', filter=filter_str))[0].id

        # create a role assignment granting the key vault service principal this role
        role_params = RoleAssignmentCreateParameters(
            role_definition_id=role_id,
            # the Azure Key Vault service id
            principal_id='93c27d83-f79b-4cb2-8dd4-4aa716542e74')

        if not self.is_live:
            sa_id = '{}/providers/Microsoft.Storage/storageAccounts/{}'.format(
                resource_group.id, storage_account.name)
        else:
            sa_id = storage_account.id

        authorization_mgmt_client.role_assignments.create(
            scope=sa_id,
            role_assignment_name='d7607bd3-a467-4a14-ab5f-f4b016ffbfff',
            parameters=role_params)

        # add the storage account to the vault using the users KeyVaultClient
        attributes = StorageAccountAttributes(enabled=True)
        self.client.set_storage_account(
            vault_base_url=vault.properties.vault_uri,
            storage_account_name=storage_account.name,
            resource_id=sa_id,
            active_key_name='key1',
            auto_regenerate_key=True,
            regeneration_period='P30D',
            storage_account_attributes=attributes)

        # update active key for the storage account
        self.client.update_storage_account(
            vault_base_url=vault.properties.vault_uri,
            storage_account_name=storage_account.name,
            active_key_name='key2')

        self.client.regenerate_storage_account_key(
            vault_base_url=vault.properties.vault_uri,
            storage_account_name=storage_account.name,
            key_name='key1')

        self.create_account_sas_definition(storage_account.name,
                                           vault.properties.vault_uri)

        self.create_blob_sas_defintion(storage_account.name,
                                       vault.properties.vault_uri)

        self.get_sas_definitions(storage_account.name,
                                 vault.properties.vault_uri)

        self.client.delete_storage_account(
            vault_base_url=vault.properties.vault_uri,
            storage_account_name=storage_account.name)
def assign_role(scope, role_name, principal_id):
    role_definition_id = get_role_definition(scope, role_name)
    parameters = RoleAssignmentCreateParameters(
        role_definition_id=role_definition_id, principal_id=principal_id)
    auth_client.role_assignments.create(scope,
                                        str(uuid.uuid4()),
                                        parameters=parameters)
Exemple #3
0
def assign_role(scope,role_name,principal_id):
    try:
        role_definition_id = get_role_definition(scope,role_name)
        parameters = RoleAssignmentCreateParameters(role_definition_id=role_definition_id,principal_id=principal_id)
        auth_client.role_assignments.create(scope,str(uuid.uuid4()),parameters=parameters)
    except CloudError as e:
        if 'already exists' in e.message:
            pass
        else:
            print('error : {}'.format(e.error))
            sys.exit()
Exemple #4
0
    def assign_resource_group(self, resource_group):
        scope = '/subscriptions/' + self.subscription_id + \
            '/resourceGroups/' + resource_group
        assignment_name = uuid.uuid4()
        role = "/subscriptions/" + self.subscription_id + \
               "/providers/Microsoft.Authorization/roleDefinitions/b24988ac-6180-42a0-ab88-20f7382dd24c"

        parameters = RoleAssignmentCreateParameters(
            role_definition_id=role, principal_id=self.user.object_id)

        self.roleAssignment = self.authClient.role_assignments.create(
            scope=scope,
            role_assignment_name=assignment_name,
            parameters=parameters)
Exemple #5
0
def assign_identity(cli_ctx,
                    getter,
                    setter,
                    identity_role=None,
                    identity_scope=None):
    import time
    from azure.mgmt.authorization import AuthorizationManagementClient
    from azure.mgmt.authorization.models import RoleAssignmentCreateParameters
    from msrestazure.azure_exceptions import CloudError

    # get
    resource = getter()
    resource = setter(resource)

    # create role assignment:
    if identity_scope:
        principal_id = resource.identity.principal_id

        identity_role_id = resolve_role_id(cli_ctx, identity_role,
                                           identity_scope)
        assignments_client = get_mgmt_service_client(
            cli_ctx, AuthorizationManagementClient).role_assignments
        parameters = RoleAssignmentCreateParameters(
            role_definition_id=identity_role_id, principal_id=principal_id)

        logger.info(
            "Creating an assignment with a role '%s' on the scope of '%s'",
            identity_role_id, identity_scope)
        retry_times = 36
        assignment_name = _gen_guid()
        for l in range(0, retry_times):
            try:
                assignments_client.create(scope=identity_scope,
                                          role_assignment_name=assignment_name,
                                          parameters=parameters)
                break
            except CloudError as ex:
                if 'role assignment already exists' in ex.message:
                    logger.info('Role assignment already exists')
                    break
                elif l < retry_times and ' does not exist in the directory ' in ex.message:
                    time.sleep(5)
                    logger.warning('Retrying role assignment creation: %s/%s',
                                   l + 1, retry_times)
                    continue
                else:
                    raise
    return resource
Exemple #6
0
def _create_role_assignment(cli_ctx, role, assignee_object_id, scope):
    factory = _auth_client_factory(cli_ctx, scope)
    assignments_client = factory.role_assignments
    definitions_client = factory.role_definitions

    scope = '/subscriptions/' + assignments_client.config.subscription_id

    role_id = _resolve_role_id(role, scope, definitions_client)

    from azure.mgmt.authorization.models import RoleAssignmentCreateParameters
    parameters = RoleAssignmentCreateParameters(
        role_definition_id=role_id, principal_id=assignee_object_id)

    return assignments_client.create(scope=scope,
                                     role_assignment_name=_gen_guid(),
                                     parameters=parameters)
Exemple #7
0
    def create_roleassignment(self):
        '''
        Creates role assignment.

        :return: deserialized role assignment
        '''
        self.log("Creating role assignment {0}".format(self.name))

        try:
            parameters = RoleAssignmentCreateParameters(role_definition_id=self.role_definition_id, principal_id=self.assignee_object_id)
            response = self._client.role_assignments.create(scope=self.scope,
                                                            role_assignment_name=self.name,
                                                            parameters=parameters)

        except CloudError as exc:
            self.log('Error attempting to create role assignment.')
            self.fail("Error creating role assignment: {0}".format(str(exc)))
        return roleassignment_to_dict(response)
Exemple #8
0
 def create_role_assignment(
     self,
     stg_account_name,
     subscription_id,
     client_authorization,
     guid,
     scope,
     principalId,
     sql_server_name,
 ):
     """Creates a Role Assignment
     :param stg_account_name: Storage Account name
     :param subscription_id: Azure Subscription Id
     :param client_authorization: Instance of the Azure AuthorizationManagementClient.
     :param guid: UUID for role name
     :param scope: The scope of the role assignment.
     :param principalId: Principal Id of the SQL Server
     :param sql_server_name: SQL Server Name
     :type client_authorization: object
     :type stg_account_name: str
     :type subscription_id: str
     :type guid: str
     :type scope: str
     :type principalId: str
     :type sql_server_name: str
     :returns: None
     :rtype: None
     """
     logging.info(
         f"Creating a Role Assignment for Storage Account {stg_account_name} and assigning Storage Blob Data Contributer Role to the SQL Database Server {sql_server_name}"
     )
     logging.info("executing client_authorization.role_assignments.create")
     logging.info(f"      scope={scope}")
     logging.info(f"      role_assignment_name={guid}")
     client_authorization.role_assignments.create(
         scope=scope,
         role_assignment_name=guid,
         parameters=RoleAssignmentCreateParameters(
             properties=RoleAssignmentProperties(
                 role_definition_id=f"/subscriptions/{subscription_id}/providers/Microsoft.Authorization/roleDefinitions/ba92f5b4-2d11-453d-a403-e96b0029c9fe",
                 principal_id=principalId,
             ),
         ),
     )
 def create_role_assignment(
     self,
     subscription_id,
     client_authorization,
     guid,
     scope,
     app_object_id,
     key_vault_name,
 ):
     """Creates a Role Assignment
     :param subscription_id: Azure Subscription Id
     :param client_authorization: Instance of the Azure AuthorizationManagementClient.
     :param guid: UUID for role name
     :param scope: The scope of the role assignment.
     :param app_object_id: Object Id of the Application
     :param key_vault_name: Key Vault Name
     :type client_authorization: object
     :type subscription_id: str
     :type guid: str
     :type scope: str
     :type principalId: str
     :type key_vault_name: str
     :returns: None
     :rtype: None
     """
     logging.info(
         f"Creating a Role Assignment for Key Vault {key_vault_name} and assigning Key Vault Secrets Officer Role to the application"
     )
     logging.info("executing client_authorization.role_assignments.create")
     logging.info(f"      scope={scope}")
     logging.info(f"      role_assignment_name={guid}")
     client_authorization.role_assignments.create(
         scope=scope,
         role_assignment_name=guid,
         parameters=
         RoleAssignmentCreateParameters(properties=RoleAssignmentProperties(
             role_definition_id=
             f"/subscriptions/{subscription_id}/providers/Microsoft.Authorization/roleDefinitions/b86a8fe4-44ce-4948-aee5-eccb2c155cd7",
             principal_id=app_object_id,
         ), ),
     )
Exemple #10
0
def create_role_assignment(auth,
                           role,
                           assignee,
                           resource_group_name=None,
                           scope=None,
                           resolve_assignee=True):
    """
    :param auth: auth object
    :type auth: azureml.core.authentication.AbstractAuthentication
    :param role:
    :param assignee:
    :param resource_group_name:
    :param scope:
    :param resolve_assignee:
    :return:
    """

    factory = auth_client_factory(auth, scope)
    assignments_client = factory.role_assignments
    definitions_client = factory.role_definitions

    scope = _build_role_scope(resource_group_name, scope,
                              assignments_client.config.subscription_id)

    role_id = _resolve_role_id(role, scope, definitions_client)
    object_id = _resolve_object_id(auth,
                                   assignee) if resolve_assignee else assignee

    from azure.mgmt.authorization.models import RoleAssignmentCreateParameters
    properties = RoleAssignmentCreateParameters(role_definition_id=role_id,
                                                principal_id=object_id)
    assignment_name = uuid.uuid4()
    custom_headers = None
    return assignments_client.create(scope,
                                     assignment_name,
                                     properties,
                                     custom_headers=custom_headers)
Exemple #11
0
    def add_storage_account(self):
        """
        Creates a storage account then adds the storage account to the vault to manage its keys.
        """
        from azure.mgmt.storage import StorageManagementClient
        from azure.mgmt.storage.models import StorageAccountCreateParameters, Sku, SkuName, Kind
        from msrestazure.azure_active_directory import AADTokenCredentials
        from azure.mgmt.authorization.models import RoleAssignmentCreateParameters
        from azure.keyvault.models import StorageAccountAttributes
        from azure.mgmt.authorization import AuthorizationManagementClient

        self.config.storage_account_name = get_name('sa', '')

        # only user accounts with access to the storage account keys can add a storage account to
        # a vault.  For this reason this sample creates the storage account with a user account
        # authenticated through device login rather than the service principal credentials used
        # in other samples.
        # create the StorageManagementClient with user token credentials
        user_token_creds = AADTokenCredentials(
            self.get_user_token('https://management.core.windows.net/'))

        print('creating storage account %s' % self.config.storage_account_name)
        storage_mgmt_client = StorageManagementClient(
            user_token_creds, self.config.subscription_id)

        # create the storage account
        sa_params = StorageAccountCreateParameters(
            sku=Sku(SkuName.standard_ragrs),
            kind=Kind.storage,
            location=self.config.location)
        sa = storage_mgmt_client.storage_accounts.create(
            resource_group_name=self.config.group_name,
            account_name=self.config.storage_account_name,
            parameters=sa_params).result()

        # the KeyVault service must be given the "Storage Account Key Operator Service Role" on the
        # storage account before the storage account can be added to the vault

        print(
            'granting Azure Key Vault the "Storage Account Key Operator Service Role" on the storage account'
        )
        # find the role definition for "Storage Account Key Operator Service Role"
        filter_str = 'roleName eq \'Storage Account Key Operator Service Role\''
        authorization_mgmt_client = AuthorizationManagementClient(
            user_token_creds, self.config.subscription_id)
        role_id = list(
            authorization_mgmt_client.role_definitions.list(
                scope='/', filter=filter_str))[0].id

        # create a role assignment granting the key vault service principal this role
        role_params = RoleAssignmentCreateParameters(
            role_definition_id=role_id,
            # the Azure Key Vault service id
            principal_id='93c27d83-f79b-4cb2-8dd4-4aa716542e74')
        authorization_mgmt_client.role_assignments.create(
            scope=sa.id,
            role_assignment_name=str(uuid.uuid4()),
            parameters=role_params)

        # since the set_storage_account can only be called by a user account with access to the keys of
        # the storage account, we grant the user that created the storage account access to the vault
        # and add the storage account to the vault
        vault = self.get_sample_vault()

        # grant the user access the vault
        self.grant_access_to_sample_vault(vault, self._user_oid)

        # add the storage account to the vault using the users KeyVaultClient
        print('adding storage acount %s to vault %s' %
              (self.config.storage_account_name, vault.name))
        attributes = StorageAccountAttributes(enabled=True)
        self.keyvault_user_client.set_storage_account(
            vault_base_url=self.sample_vault_url,
            storage_account_name=sa.name,
            resource_id=sa.id,
            active_key_name='key1',
            auto_regenerate_key=True,
            regeneration_period='P30D',
            storage_account_attributes=attributes)