1# -*- coding: utf-8 -*- # 2# Copyright 2018 Google LLC. All Rights Reserved. 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15 16"""API helpers for interacting with IAM.""" 17 18from __future__ import absolute_import 19from __future__ import division 20from __future__ import unicode_literals 21 22from googlecloudsdk.api_lib.container.binauthz import apis 23from googlecloudsdk.command_lib.iam import iam_util 24 25 26class Client(object): 27 """A client for interacting with IAM.""" 28 29 def __init__(self, api_version=None): 30 self.client = apis.GetClientInstance(api_version) 31 self.messages = apis.GetMessagesModule(api_version) 32 33 def Get(self, any_ref): 34 """Gets the IamPolicy associated with a resource.""" 35 return self.client.projects_policy.GetIamPolicy( 36 self.messages.BinaryauthorizationProjectsPolicyGetIamPolicyRequest( 37 resource=any_ref.RelativeName(), 38 ) 39 ) 40 41 def Set(self, any_ref, policy): 42 """Sets a resource's IamPolicy to the one provided. 43 44 If 'policy' has no etag specified, this will BLINDLY OVERWRITE the IAM 45 policy! 46 47 Args: 48 any_ref: A resources.Resource naming the resource. 49 policy: A protorpc.Message instance of an IamPolicy object. 50 51 Returns: 52 The IAM Policy. 53 """ 54 return self.client.projects_policy.SetIamPolicy( 55 self.messages.BinaryauthorizationProjectsPolicySetIamPolicyRequest( 56 resource=any_ref.RelativeName(), 57 setIamPolicyRequest=self.messages.SetIamPolicyRequest( 58 policy=policy, 59 ), 60 ) 61 ) 62 63 def AddBinding(self, any_ref, member, role): 64 """Does an atomic Read-Modify-Write, adding the member to the role.""" 65 policy = self.Get(any_ref) 66 iam_util.AddBindingToIamPolicy(self.messages.Binding, policy, member, role) 67 return self.Set(any_ref, policy) 68 69 def RemoveBinding(self, any_ref, member, role): 70 """Does an atomic Read-Modify-Write, removing the member from the role.""" 71 policy = self.Get(any_ref) 72 iam_util.RemoveBindingFromIamPolicy(policy, member, role) 73 return self.Set(any_ref, policy) 74