Beispiel #1
0
    def Run(self, args):
        holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
        client = holder.client

        instance_ref = flags.INSTANCE_ARG.ResolveAsResource(
            args,
            holder.resources,
            scope_lister=flags.GetInstanceZoneScopeLister(client))

        policy = client.MakeRequests([
            (client.apitools_client.instances, 'GetIamPolicy',
             client.messages.ComputeInstancesGetIamPolicyRequest(
                 resource=instance_ref.instance,
                 zone=instance_ref.zone,
                 project=instance_ref.project))
        ])[0]
        iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
        return client.MakeRequests([
            (client.apitools_client.instances, 'SetIamPolicy',
             client.messages.ComputeInstancesSetIamPolicyRequest(
                 policy=policy,
                 project=instance_ref.project,
                 resource=instance_ref.instance,
                 zone=instance_ref.zone))
        ])[0]
Beispiel #2
0
def RemoveIamPolicyBinding(project_ref,
                           member,
                           role,
                           api_version=DEFAULT_API_VERSION):
    policy = GetIamPolicy(project_ref, api_version=api_version)
    iam_util.RemoveBindingFromIamPolicy(policy, member, role)
    return SetIamPolicy(project_ref, policy, api_version=api_version)
Beispiel #3
0
def RemovePolicyBindingFromKeyRing(key_ring_ref, member, role):
    """Does an atomic Read-Modify-Write, removing the member from the role."""
    policy = GetKeyRingIamPolicy(key_ring_ref)
    iam_util.RemoveBindingFromIamPolicy(policy, member, role)
    return SetKeyRingIamPolicy(key_ring_ref,
                               policy,
                               update_mask='bindings,etag')
  def Run(self, args):
    holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
    client = holder.client

    instance_ref = flags.INSTANCE_ARG.ResolveAsResource(
        args,
        holder.resources,
        scope_lister=flags.GetInstanceZoneScopeLister(client))

    policy = client.MakeRequests(
        [(client.apitools_client.instances, 'GetIamPolicy',
          client.messages.ComputeInstancesGetIamPolicyRequest(
              resource=instance_ref.instance,
              zone=instance_ref.zone,
              project=instance_ref.project))])[0]
    iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
    # TODO(b/78371568): Construct the ZoneSetPolicyRequest directly
    # out of the parsed policy.
    return client.MakeRequests(
        [(client.apitools_client.instances, 'SetIamPolicy',
          client.messages.ComputeInstancesSetIamPolicyRequest(
              zoneSetPolicyRequest=client.messages.ZoneSetPolicyRequest(
                  bindings=policy.bindings,
                  etag=policy.etag),
              project=instance_ref.project,
              resource=instance_ref.instance,
              zone=instance_ref.zone))])[0]
  def AddOrRemoveIamPolicyBinding(self, service_ref, add_binding=True,
                                  member=None, role=None):
    """Add or remove the given IAM policy binding to the provided service.

    If no members or role are provided, set the IAM policy to the current IAM
    policy. This is useful for checking whether the authenticated user has
    the appropriate permissions for setting policies.

    Args:
      service_ref: str, The service to which to add the IAM policy.
      add_binding: bool, Whether to add to or remove from the IAM policy.
      member: str, One of the users for which the binding applies.
      role: str, The role to grant the provided members.

    Returns:
      A google.iam.v1.TestIamPermissionsResponse.
    """
    messages = self.messages_module
    oneplatform_service = resource_name_conversion.K8sToOnePlatform(
        service_ref, self._region)
    policy = self._GetIamPolicy(oneplatform_service)
    # Don't modify bindings if not member or roles provided
    if member and role:
      if add_binding:
        iam_util.AddBindingToIamPolicy(messages.Binding, policy, member, role)
      elif iam_util.BindingInPolicy(policy, member, role):
        iam_util.RemoveBindingFromIamPolicy(policy, member, role)
    request = messages.RunProjectsLocationsServicesSetIamPolicyRequest(
        resource=six.text_type(oneplatform_service),
        setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy))
    result = self._op_client.projects_locations_services.SetIamPolicy(request)
    return result
Beispiel #6
0
 def testRemoveNonExistingBindingFromIamPolicy(self):
     policy = copy.deepcopy(self.TEST_IAM_POLICY)
     message = 'Policy binding with the specified member and role not found!'
     with self.assertRaisesRegex(iam_util.IamPolicyBindingNotFound,
                                 message):
         iam_util.RemoveBindingFromIamPolicy(policy, 'user:[email protected]',
                                             'roles/owner')
    def _GetModifiedIamPolicy(self, args, policy_binding_type):
        """Get the current IAM policy and then add/remove bindings as specified.

    An IAM binding is a pair of role and member. If policy_binding_type is add,
    the member and role specified in args would be added; if policy_binding_type
    is remove, the member and role specified in args would be removed.

    Args:
      args: The argparse parser.
      policy_binding_type: string, add or remove.

    Returns:
      IAM policy.
    """
        get_iam_method = registry.GetMethod(self.spec.request.collection,
                                            'getIamPolicy',
                                            self.spec.request.api_version)
        get_iam_request = self.arg_generator.CreateRequest(
            args,
            use_relative_name=self.spec.request.use_relative_name,
            override_method=get_iam_method)
        policy = get_iam_method.Call(get_iam_request)

        if policy_binding_type == 'add':
            binding = self.method.GetMessageByName('Binding')
            iam_util.AddBindingToIamPolicy(binding, policy, args.member,
                                           args.role)
        elif policy_binding_type == 'remove':
            iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
        else:
            pass

        return policy
Beispiel #8
0
def RemoveIamPolicyBinding(models_client, model, member, role):
    model_ref = ParseModel(model)
    policy = models_client.GetIamPolicy(model_ref)
    iam_util.RemoveBindingFromIamPolicy(policy, member, role)
    ret = models_client.SetIamPolicy(model_ref, policy, 'bindings,etag')
    iam_util.LogSetIamPolicy(model_ref.Name(), 'model')
    return ret
    def Run(self, args):
        """Run 'service-management remove-iam-policy-binding'.

    Args:
      args: argparse.Namespace, The arguments that this command was invoked
          with.

    Returns:
      The response from the access API call.

    Raises:
      ToolException: An error such as specifying a label that doesn't exist
        or a principal that is already a member of the service or visibility
        label.
    """
        messages = services_util.GetMessagesModule()
        client = services_util.GetClientInstance()
        request = messages.ServicemanagementServicesGetIamPolicyRequest(
            servicesId=args.service)

        policy = client.services.GetIamPolicy(request)

        iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)

        # Send updated access policy to backend
        request = messages.ServicemanagementServicesSetIamPolicyRequest(
            servicesId=args.service,
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy))
        return client.services.SetIamPolicy(request)
Beispiel #10
0
def RemovePolicyBindingFromCryptoKey(crypto_key_ref, member, role):
  """Does an atomic Read-Modify-Write, removing the member from the role."""
  policy = GetCryptoKeyIamPolicy(crypto_key_ref)
  policy.version = iam_util.MAX_LIBRARY_IAM_SUPPORTED_VERSION

  iam_util.RemoveBindingFromIamPolicy(policy, member, role)
  return SetCryptoKeyIamPolicy(
      crypto_key_ref, policy, update_mask='bindings,etag')
Beispiel #11
0
 def Run(self, args):
     queues_client = queues.Queues()
     queue_ref = parsers.ParseQueue(args.queue, args.location)
     policy = queues_client.GetIamPolicy(queue_ref)
     iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
     response = queues_client.SetIamPolicy(queue_ref, policy)
     log.status.Print('Updated IAM policy for queue [{}].'.format(
         queue_ref.Name()))
     return response
Beispiel #12
0
def RemoveIamPolicyBinding(project_ref, member, role):
    try:
        policy = GetIamPolicy(project_ref)
    except exceptions.HttpError as error:
        raise projects_util.ConvertHttpError(error)
    iam_util.RemoveBindingFromIamPolicy(policy, member, role)
    try:
        return SetIamPolicy(project_ref, policy)
    except exceptions.HttpError as error:
        raise projects_util.ConvertHttpError(error)
  def Run(self, args):
    policy = self.iam_client.projects_serviceAccounts.GetIamPolicy(
        self.messages.IamProjectsServiceAccountsGetIamPolicyRequest(
            resource=iam_util.EmailToAccountResourceName(args.service_account)))

    iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)

    return self.iam_client.projects_serviceAccounts.SetIamPolicy(
        self.messages.IamProjectsServiceAccountsSetIamPolicyRequest(
            resource=iam_util.EmailToAccountResourceName(args.service_account),
            setIamPolicyRequest=self.messages.SetIamPolicyRequest(
                policy=policy)))
 def Run(self, args):
   holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
   client = holder.client
   image_ref = RemoveIamPolicyBinding.disk_image_arg.ResolveAsResource(
       args, holder.resources)
   get_request = client.messages.ComputeImagesGetIamPolicyRequest(
       resource=image_ref.image, project=image_ref.project)
   policy = client.apitools_client.images.GetIamPolicy(get_request)
   iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
   set_request = client.messages.ComputeImagesSetIamPolicyRequest(
       policy=policy, resource=image_ref.image, project=image_ref.project)
   return client.apitools_client.images.SetIamPolicy(set_request)
Beispiel #15
0
def Run(args):
  """Remove a binding from the IAM policy for a Google Cloud Function."""
  client = util.GetApiClientInstance()
  messages = client.MESSAGES_MODULE
  function_ref = args.CONCEPTS.name.Parse()
  policy = client.projects_locations_functions.GetIamPolicy(
      messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest(
          resource=function_ref.RelativeName()))
  iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
  return client.projects_locations_functions.SetIamPolicy(
      messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest(
          resource=function_ref.RelativeName(),
          setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
Beispiel #16
0
    def testRemoveBindingFromIamPolicy(self):
        parser = argparse.ArgumentParser()
        ai = self.getDummyArgumentInterceptor(parser)
        iam_util.AddArgsForRemoveIamPolicyBinding(ai)
        args = parser.parse_args(
            ['--role=roles/owner', '--member=user:[email protected]'])

        expected_policy = copy.deepcopy(self.TEST_IAM_POLICY)
        expected_policy.bindings[0].members.remove('user:[email protected]')

        actual_policy = copy.deepcopy(self.TEST_IAM_POLICY)
        iam_util.RemoveBindingFromIamPolicy(actual_policy, args.member,
                                            args.role)

        self.assertEqual(actual_policy, expected_policy)
Beispiel #17
0
        def RemoveIamPolicyBinding(self, object_ref, member, role):
            """Adds an IAM role for a member on an object.

      Args:
        self: The self of the class this is set on
        object_ref: Resource, reference for object IAM policy belongs to
        member: the member the binding is removed for
        role: the role which is being removed from the member

      Returns:
        The IAM policy
      """
            policy = self.GetIamPolicy(object_ref)
            iam_util.RemoveBindingFromIamPolicy(policy, member, role)
            return self.SetIamPolicy(object_ref, policy, 'bindings,etag')
Beispiel #18
0
 def Run(self, args):
     holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
     client = holder.client
     snapshot_ref = RemoveIamPolicyBinding.snapshot_arg.ResolveAsResource(
         args, holder.resources)
     get_request = client.messages.ComputeSnapshotsGetIamPolicyRequest(
         resource=snapshot_ref.snapshot, project=snapshot_ref.project)
     policy = client.apitools_client.snapshots.GetIamPolicy(get_request)
     iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
     set_request = client.messages.ComputeSnapshotsSetIamPolicyRequest(
         resource=snapshot_ref.snapshot,
         globalSetPolicyRequest=client.messages.GlobalSetPolicyRequest(
             bindings=policy.bindings, etag=policy.etag),
         project=snapshot_ref.project)
     return client.apitools_client.snapshots.SetIamPolicy(set_request)
  def Run(self, args):
    try:
      policy = self.iam_client.projects_serviceAccounts.GetIamPolicy(
          self.messages.IamProjectsServiceAccountsGetIamPolicyRequest(
              resource=iam_util.EmailToAccountResourceName(args.name)))

      iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)

      return self.iam_client.projects_serviceAccounts.SetIamPolicy(
          self.messages.IamProjectsServiceAccountsSetIamPolicyRequest(
              resource=iam_util.EmailToAccountResourceName(args.name),
              setIamPolicyRequest=self.messages.SetIamPolicyRequest(
                  policy=policy)))
    except exceptions.HttpError as error:
      raise iam_util.ConvertToServiceAccountException(error, args.name)
Beispiel #20
0
    def RemoveIamPolicyBinding(self, subscription_ref, member, role):
        """Removes an IAM Policy binding from a Subscription.

    Args:
      subscription_ref (Resource): Resource reference for subscription to
        remove IAM policy binding from.
      member (str): The member to add.
      role (str): The role to assign to the member.
    Returns:
      Policy: the updated policy.
    Raises:
      api_exception.HttpException: If either of the requests failed.
    """
        policy = self.GetIamPolicy(subscription_ref)
        iam_util.RemoveBindingFromIamPolicy(policy, member, role)
        return self.SetIamPolicy(subscription_ref, policy)
Beispiel #21
0
def RemoveFunctionIamPolicyBindingIfFound(
    function_resource_name,
    member='allUsers',
    role='roles/cloudfunctions.invoker'):
  """Removes the specified policy binding if it is found."""
  client = GetApiClientInstance()
  messages = client.MESSAGES_MODULE
  policy = GetFunctionIamPolicy(function_resource_name)
  if iam_util.BindingInPolicy(policy, member, role):
    iam_util.RemoveBindingFromIamPolicy(policy, member, role)
    client.projects_locations_functions.SetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest(
            resource=function_resource_name,
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
    return True
  else:
    return False
  def Run(self, args):
    messages = self.OrganizationsMessages()

    get_policy_request = (
        messages.CloudresourcemanagerOrganizationsGetIamPolicyRequest(
            organizationsId=args.id,
            getIamPolicyRequest=messages.GetIamPolicyRequest()))
    policy = self.OrganizationsClient().GetIamPolicy(get_policy_request)

    iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)

    set_policy_request = (
        messages.CloudresourcemanagerOrganizationsSetIamPolicyRequest(
            organizationsId=args.id,
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))

    return self.OrganizationsClient().SetIamPolicy(set_policy_request)
Beispiel #23
0
 def Run(self, args):
     holder = base_classes.ComputeApiHolder(self.ReleaseTrack())
     client = holder.client
     image_ref = RemoveIamPolicyBinding.disk_image_arg.ResolveAsResource(
         args, holder.resources)
     get_request = client.messages.ComputeImagesGetIamPolicyRequest(
         resource=image_ref.image, project=image_ref.project)
     policy = client.apitools_client.images.GetIamPolicy(get_request)
     iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
     # TODO(b/78371568): Construct the GlobalSetPolicyRequest directly
     # out of the parsed policy.
     set_request = client.messages.ComputeImagesSetIamPolicyRequest(
         globalSetPolicyRequest=client.messages.GlobalSetPolicyRequest(
             bindings=policy.bindings, etag=policy.etag),
         resource=image_ref.image,
         project=image_ref.project)
     return client.apitools_client.images.SetIamPolicy(set_request)
Beispiel #24
0
def Run(args, release_track):
    """Removes a binding from the IAM policy for a Google Cloud Function."""
    client = api_util.GetClientInstance(release_track=release_track)
    messages = api_util.GetMessagesModule(release_track=release_track)

    function_ref = args.CONCEPTS.name.Parse()
    function_relative_name = function_ref.RelativeName()

    policy = client.projects_locations_functions.GetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest(
            resource=function_relative_name))

    iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)

    return client.projects_locations_functions.SetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest(
            resource=function_relative_name,
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy)))
    def Run(self, args):
        """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      Some value that we want to have printed later.
    """
        adapter = self.context['api_adapter']
        location_get = self.context['location_get']
        location = location_get(args)

        policy = adapter.GetIamPolicy(adapter.ParseCluster(
            args.name, location))
        iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
        return adapter.SetIamPolicy(adapter.ParseCluster(args.name, location),
                                    policy)
  def _GetModifiedIamPolicyRemoveIamBinding(self, args, add_condition=False):
    """Get the IAM policy and remove the specified binding to it.

    Args:
      args: an argparse namespace.
      add_condition: True if support condition.

    Returns:
      IAM policy.
    """
    if add_condition:
      condition = iam_util.ValidateAndExtractCondition(args)
      policy = self._GetIamPolicy(args)
      iam_util.RemoveBindingFromIamPolicyWithCondition(
          policy, args.member, args.role, condition, all_conditions=args.all)
    else:
      policy = self._GetIamPolicy(args)
      iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
    return policy
    def Run(self, args):
        apitools_client = genomics_util.GetGenomicsClient()
        messages = genomics_util.GetGenomicsMessages()

        dataset_resource = resources.REGISTRY.Parse(
            args.id, collection='genomics.datasets')

        policy_request = messages.GenomicsDatasetsGetIamPolicyRequest(
            resource='datasets/{0}'.format(dataset_resource.Name()),
            getIamPolicyRequest=messages.GetIamPolicyRequest(),
        )
        policy = apitools_client.datasets.GetIamPolicy(policy_request)

        iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)

        policy_request = messages.GenomicsDatasetsSetIamPolicyRequest(
            resource='datasets/{0}'.format(dataset_resource.Name()),
            setIamPolicyRequest=messages.SetIamPolicyRequest(policy=policy),
        )
        return apitools_client.datasets.SetIamPolicy(policy_request)
  def Run(self, args):
    """This is what gets called when the user runs this command.

    Args:
      args: an argparse namespace. All the arguments that were provided to this
        command invocation.

    Returns:
      The specified function with its description and configured filter.
    """
    client = util.GetApiClientInstance()
    messages = client.MESSAGES_MODULE
    function_ref = args.CONCEPTS.name.Parse()
    policy = client.projects_locations_functions.GetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsGetIamPolicyRequest(
            resource=function_ref.RelativeName()))
    iam_util.RemoveBindingFromIamPolicy(policy, args.member, args.role)
    return client.projects_locations_functions.SetIamPolicy(
        messages.CloudfunctionsProjectsLocationsFunctionsSetIamPolicyRequest(
            resource=function_ref.RelativeName(),
            setIamPolicyRequest=messages.SetIamPolicyRequest(
                policy=policy)))
Beispiel #29
0
    def Run(self, args):
        datafusion = df.Datafusion()
        instance_ref = args.CONCEPTS.instance.Parse()

        if not args.namespace:
            get_request = datafusion.messages.DatafusionProjectsLocationsInstancesGetIamPolicyRequest(
                resource=instance_ref.RelativeName())
            iam_policy = datafusion.client.projects_locations_instances.GetIamPolicy(
                get_request)
        else:
            get_request = datafusion.messages.DatafusionProjectsLocationsInstancesNamespacesGetIamPolicyRequest(
                resource='%s/namespaces/%s' %
                (instance_ref.RelativeName(), args.namespace))
            iam_policy = datafusion.client.projects_locations_instances_namespaces.GetIamPolicy(
                get_request)

        iam_util.RemoveBindingFromIamPolicy(iam_policy, args.member, args.role)
        results = data_fusion_iam_util.DoSetIamPolicy(instance_ref,
                                                      args.namespace,
                                                      iam_policy,
                                                      datafusion.messages,
                                                      datafusion.client)
        return results
Beispiel #30
0
def RemoveDatabaseIamPolicyBinding(database_ref, member, role):
    """Removes a policy binding from a database IAM policy."""
    policy = databases.GetIamPolicy(database_ref)
    iam_util.RemoveBindingFromIamPolicy(policy, member, role)
    return databases.SetPolicy(database_ref, policy)