
    I+                     (   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddl	Z	dd	l
mZ dd
lmZ ddlmZ  eg d      Z eg d      ZdZ eddg      Z edddg      Z edddg      ZdZd Zd Zd Zd Zd Zd Zd Zd Z d Z!d Z"y) z"Helper module for the IAM command.    )absolute_import)print_function)division)unicode_literals)defaultdict)
namedtupleN)	protojson)CommandException)storage_v1_messages)
userzdeleted:userserviceAccountzdeleted:serviceAccountgroupzdeleted:groupdomain	principalprincipalSetprincipalHierarchy)projectOwnerprojectEditorprojectViewera  Assigning roles (e.g. objectCreator, legacyBucketOwner) for project convenience groups is not supported by gsutil, as it goes against the principle of least privilege. Consider creating and using more granular groups with which to assign permissions. See https://cloud.google.com/iam/docs/using-iam-securely for more information. Assigning a role to a project group can be achieved by setting the IAM policy directly (see gsutil help iam for specifics).allUsersallAuthenticatedUsersBindingsTupleis_grantbindingsBindingsDictTuple c                 ~    | j                   | j                  D cg c]  }t        j                  |       c}fS c c}w )aS  Serializes the BindingsValueListEntry instances in a BindingsTuple.

  This is necessary when passing instances of BindingsTuple through
  Command.Apply, as apitools_messages classes are not by default pickleable.

  Args:
    bindings_tuple: A BindingsTuple instance to be serialized.

  Returns:
    A serialized BindingsTuple object.
  )r   r   r	   encode_message)bindings_tuplets     )platform/gsutil/gslib/utils/iam_helper.pySerializeBindingsTupler"   N   sA     
!
!0>0G0G
H0G19##A&0G
H
J J
Hs   :c           
          | \  }}t        ||D cg c]0  }t        j                  t        j                  j
                  |      2 c}      S c c}w )Nr   r   )r   r	   decode_messageapitools_messagesPolicyBindingsValueListEntry)serialized_bindings_tupler   r   r    s       r!   DeserializeBindingsTupler*   ^   s\    28X	 ,4! ,4a %33077NN "+3!
 !s   5A
c                     t        t              }| D ]*  }||j                     j                  |j                         , |S )zReformats policy bindings metadata.

  Args:
    bindings: A list of BindingsValueListEntry instances.

  Returns:
    A {role: set(members)} dictionary.
  )r   setroleupdatemembersr   tmp_bindingsbindings      r!   BindingsMessageToUpdateDictr3   h   s9     S!,g%%goo6 	    c                 f    t        t              }| D ]  }||d      j                  |d           |S )a  Reformats policy bindings metadata.

  Args:
    bindings: List of dictionaries representing BindingsValueListEntry
      instances. e.g.:
      {
        "role": "some_role",
        "members": ["allAuthenticatedUsers", ...]
      }

  Returns:
    A {role: set(members)} dictionary.
  r-   r/   )r   r,   r.   r0   s      r!   BindingsDictToUpdateDictr6   x   s:     S!,g!(();< 	r4   c                 X    t        | |      \  }}|j                   xr |j                   S )N)DiffBindingsr   )abgrantedremoveds       r!   IsEqualBindingsr=      s0    #Aq)7G		6g&6&6"66r4   c           
         t        |       }t        |      }t        g       }t        g       }t        j                  |      D ]+  \  }}||   j                  |j	                  ||                - t        j                  |      D ]+  \  }}||   j                  |j	                  ||                - t        j                  |      D 	cg c]1  \  }}	|	r*t
        j                  j                  |t        |	            3 }}}	t        j                  |      D 	cg c]1  \  }}	|	r*t
        j                  j                  |t        |	            3 }}}	t        d|      t        d|      fS c c}	}w c c}	}w )a]  Computes the difference between two BindingsValueListEntry lists.

  Args:
    old: The original list of BindingValuesListEntry instances
    new: The updated list of BindingValuesListEntry instances

  Returns:
    A pair of BindingsTuple instances, one for roles granted between old and
      new, and one for roles removed between old and new.
  r-   r/   TF)
r3   six	iteritemsr.   
differencer&   r'   r(   listr   )
oldnewtmp_oldtmp_newr;   r<   r-   r/   rms
             r!   r8   r8      sY    (,'',''+''+'w/otWDM++GDM:; 0w/otWDM++GDM:; 0
 MM'**&1a	
 551d1g5N* 
  MM'**&1a	
 551d1g5N* 
  g
&eW(E	FF
s   6E-6E3c                 Z   |r?t        j                  |      D ]&  \  }}|st        d      | |   j                  |       ( n9| D ]4  }| |   j	                  ||          | |   j	                  |t
                  6 t        j                  |       D ci c]  \  }}|s	|| c}}S c c}}w )a  Patches a diff list of BindingsValueListEntry to the base.

  Will remove duplicate members for any given role on a grant operation.

  Args:
    base (dict): A dictionary returned by BindingsMessageToUpdateDict or
      BindingsDictToUpdateDict representing a resource's current
      IAM policy.
    diff (dict): A dictionary returned by BindingsMessageToUpdateDict or
      BindingsDictToUpdateDict representing the IAM policy bindings to
      add/remove from `base`.
    is_grant (bool): True if `diff` should be added to `base`, False
      if it should be removed from `base`.

  Returns:
    A {role: set(members)} dictionary created by applying `diff` to `base`.
  z+Role must be specified for a grant request.)r@   rA   r
   r.   difference_updateDROP_ALL)basediffr   r-   r/   s        r!   PatchBindingsrO      s    & ==.wLMM
4j  /
 
4j""4:.
4j""4>2 
 .1]]4-@	L-@MD'G$--@	LL	Ls   
B'B'c                    |j                  d      s|dz  }|j                  d      }t        D ci c]  }|j                         | }}t        D ci c]  }|j                         | }}t
        D ci c]  }|j                         | }}|d   j                         }|d   j                         d|d   j                         }||v r	||   |d<   n;||v r	||   |d<   n.||v r	||   |d<   n!||v r||   j                  d      \  |d<   |d<   dj                  |      }|  xr |d   t
        v }	|j                  d      dk(  rV|d   d|d   t        v rt        d|z        |d   t        v r|\  }
}n|d   t        v s|	r	|}
t        }nt        d|z        |j                  d      dk(  rF|d   d|d   t        v r	|}
t        }n}|	r|\  }}}|d|}
nm|\  }}}t        ||       |d|}
nS|j                  d      dk(  r1|j                  d      \  }}}}|d|}t        ||       |d|}
nt        d|z        | r|st        d      |j                  d	      D cg c]  }t        |       }}t        |      D cg c]  }||
gd

 }}t        | |      S c c}w c c}w c c}w c c}w c c}w )a  Parses an iam ch bind string to a list of binding tuples.

  Args:
    is_grant: If true, binding is to be appended to IAM policy; else, delete
              this binding from the policy.
    input_str: A string representing a member-role binding.
               e.g. user:foo@bar.com:objectAdmin
                    user:foo@bar.com:objectAdmin,objectViewer
                    user:foo@bar.com
                    allUsers
                    deleted:user:foo@bar.com?uid=123:objectAdmin,objectViewer
                    deleted:serviceAccount:foo@bar.com?uid=123

  Raises:
    CommandException in the case of invalid input.

  Returns:
    A BindingsDictTuple instance.
  :r      z+Incorrect public member type for binding %s      zInvalid ch format %szMust specify a role to grant.,r?   r$   )countsplitPUBLIC_MEMBERSlowerTYPESDISCOURAGED_TYPESjoinr
   rL   _check_member_typeResolveRoler,   r   )r   	input_strtokensspublic_memberstypesdiscouraged_typespossible_public_member_or_typepossible_typeremoving_discouraged_typememberrolesmember_type
project_id	member_idmember_type_p1member_type_p2rH   r   s                      r!   BindingStringToTuplero      s   * 
	I ??3&*89.QAGGIqL..9!&
'A1779a<%
'->?->qwwy!|->?#)!9??#4 #AY__.q	0AB-#~5=>F1I%.45F1I%)::!"@AF1I"=177<VAYq	hhv) #+lMvay<M/M__SQ)VAY'50J&' ( (	n	$ovu	e	8feJ&' ( (sq )VAY'50fe	")/&{J%z2f(.%{Iui0%y1fsq 9B9M6^^Y+^<K{I.#Y/F
1I=
>>e
:
;;#(;;s#3
4#3a;q>#3%
48;E
C
1qfX.
(C	Hx	@@u :
'?j 5Cs   J)J.4J3,J8J=c                 ^    | t         v rt        t              | t        vrt        d|z        y )Nz$Incorrect member type for binding %s)r[   r
   DISCOURAGED_TYPES_MSGrZ   )rj   r_   s     r!   r]   r]   /  s5    %%
0
11%
AIM
NN  r4   c                 (    | st         S d| v r| S d| z  S )Nzroles/zroles/storage.%s)rL   )r-   s    r!   r^   r^   6  s"    	OK	d	""r4   )#__doc__
__future__r   r   r   r   collectionsr   r   r@   apitools.base.protorpcliter	   gslib.exceptionr
   "gslib.third_party.storage_apitoolsr   r&   r,   rZ   r[   rq   rX   r   r   rL   r"   r*   r3   r6   r=   r8   rO   ro   r]   r^    r4   r!   <module>rz      s    ) & %  ' # " 
 0 , W  	
    K    ?Z,DE2Z4LM  J  *7
!GHMBUApO#r4   