
                            S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKrSSKJ	r
  SSKJr  SSKJr  SSKJ	r  SS	KJr  SS
KJr  SSKJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJ r   SSK!r!\RD                  " SS5      r#\#RH                  RJ                  r&\#RN                  RP                  r)\#RT                  RP                  r+\#RX                  RZ                  r.\#R^                  R`                  r1Sr2Sr3Sr4\Rj                  " SS5      r6\Rj                  " SS5      r7Sr8SS0r9\:" 5       r;SS0r<S r= " S S \R|                  5      r? " S! S"\R|                  5      r@ " S# S$\R|                  5      rA " S% S&\A5      rBSnS' jrCS( rDS) rES* rF SoS+ jrGS, rHS- rIS. rJS/ rKS0 rL   SpS1 jrM    SqS2 jrNS3 rOS4 rPS5 rQS6 rRSrS7 jrSS8 rTS9 rUS: rVS; rWS< rXS= rYS> rZS? r[S@ r\ SsSA jr]SB r^SC r_SD r`SE raSF rbSG rcSH rdSI reSJ rf\74SK jrgSL rhSM riSN rjSO rk    StSP jrl   SuSQ jrm   SuSR jrnSvSS jroST rpSU rqSV rrSW rsSX rtSY ruSZ rvS[ rwS\ rxS] ryS^ rzS_ r{SwS` jr|  SxSa jr}SwSb jr~Sc rSd rSySe jrSf rSg rSh rSi rSj rSk rSl rSm rg)zz,General IAM utilities used by the Cloud SDK.    )absolute_import)division)unicode_literalsN)messages)encoding)apis)arg_parsers)
exceptions)
completers)log)
properties)	resources)yaml)
console_io)filesiamv1ziam.projects.serviceAccountsz8table(displayName:label="DISPLAY NAME", email, disabled)a  
    table(
        name.scope(keys):label=KEY_ID,
        validAfterTime:label=CREATED_AT,
        validBeforeTime:label=EXPIRES_AT,
        disabled:label=DISABLED,
        disable_reason:label=DISABLE_REASON,
        extended_status:label=EXTENDED_STATUS
    )
	conditionzcondition must be either `None` or a list of key=value pairs. If not `None`, `expression` and `title` are required keys.
Example: --condition=expression=[expression],title=[title],description=[description]zcondition-from-filezcondition-from-file must be a path to a YAML or JSON file containing the condition. `expression` and `title` are required keys. `description` is optional. To specify a `None` condition, use --condition=None.   AllNonec                     U [         :H  $ N)_ALL_CONDITIONSr   s    .lib/googlecloudsdk/command_lib/iam/iam_util.py_IsAllConditionsr   W   s    	o	%%    c                       \ rS rSrSrSrg)IamEtagReadError[   z8IamEtagReadError is raised when etag is badly formatted. N__name__
__module____qualname____firstlineno____doc____static_attributes__r"   r   r   r    r    [       @r   r    c                       \ rS rSrSrSrg)IamPolicyBindingNotFound_   z:Raised when the specified IAM policy binding is not found.r"   Nr#   r"   r   r   r,   r,   _   s    Br   r,   c                       \ rS rSrSrSrg)IamPolicyBindingInvalidErrorc   z8Raised when the specified IAM policy binding is invalid.r"   Nr#   r"   r   r   r/   r/   c   r*   r   r/   c                       \ rS rSrSrSrg)IamPolicyBindingIncompleteErrorg   z;Raised when the specified IAM policy binding is incomplete.r"   Nr#   r"   r   r   r2   r2   g   s    Cr   r2   c                 x    SR                  US9nSU;   a  US-  nU(       d  US-  nU R                  SSUUS/S	9  g
)z'Create --member flag and add to parser.zThe principal {verb}. Should be of the form `user|group|serviceAccount:email` or
`domain:domain`.

Examples: `user:test-user@gmail.com`, `group:admins@example.com`,
`serviceAccount:test123@example.domain.com`, or
`domain:example.domain.com`.
      )verbremovez
Deleted principals have an additional `deleted:` prefix and a `?uid=UID` suffix,
where ``UID'' is a unique identifier for the principal. Example:
`deleted:user:test-user@gmail.com?uid=123456789012345678901`.
      a@  
Some resources also accept the following special values:
* `allUsers` - Special identifier that represents anyone who is on the internet,
   with or without a Google account.
* `allAuthenticatedUsers` - Special identifier that represents anyone who is
   authenticated with a Google account or a service account.
      z--member	PRINCIPALz--principal)metavarrequiredhelpsuggestion_aliasesN)formatadd_argument)parserr5   hide_special_member_typesr9   help_strs        r   AddMemberFlagrA   k   sm    
 6t6   
 H
 
# 
 H 	'  *r   c                  R    [         [         [         S S.n [        R                  " U SS9$ )N)
expressiontitledescriptionr   T)specallow_key_only)strr	   ArgDict)condition_specs    r   _ConditionArgDictrK      s*    	. 
		.	FFr   c                 $    SR                  U S9nU$ )z"Get the help text for --condition.a  {intro}

When using the `--condition` flag, include the following key-value pairs:

*expression*::: (Required) Condition expression that evaluates to True or False.
This uses a subset of Common Expression Language syntax.

If the condition expression includes a comma, use a different delimiter to
separate the key-value pairs. Specify the delimiter before listing the
key-value pairs. For example, to specify a colon (`:`) as the delimiter, do the
following: `--condition=^:^title=TITLE:expression=EXPRESSION`. For more
information, see https://cloud.google.com/sdk/gcloud/reference/topic/escaping.

*title*::: (Required) A short string describing the purpose of the expression.

*description*::: (Optional) Additional description for the expression.
      )intror<   )rM   	help_texts     r   _ConditionHelpTextrP      s"    
" 66# $ 
r   c                     Sn[        U5      nSnU R                  5       nUR                  S[        5       SUS9  UR                  S[        R
                  " 5       US9  g)	-Create flags for condition and add to parser.a  A condition to include in the binding. When the condition is explicitly
specified as `None` (`--condition=None`), a binding without a condition is
added. When the condition is specified and is not `None`, `--role` cannot be a
basic role. Basic roles are `roles/editor`, `roles/owner`, and `roles/viewer`.
For more on conditions, refer to the conditions overview guide:
https://cloud.google.com/iam/docs/conditions-overvieww
Path to a local JSON or YAML file that defines the condition.
To see available fields, see the help for `--condition`.--condition	KEY=VALUE)typer8   r:   --condition-from-filerV   r:   NrP   add_mutually_exclusive_groupr=   rK   r	   FileContents)r>   condition_introhelp_str_conditionhelp_str_condition_from_filecondition_groups        r   *_AddConditionFlagsForAddBindingToIamPolicyr`      sw    9/ */:"< 779/	   ##%'  )r   c                     Sn[        U5      nSnSnU R                  5       nUR                  S[        5       SUUS9  UR                  S[        R
                  " 5       US9  UR                  S	S
US9  g)rR   a  The condition of the binding that you want to remove. When the condition is
explicitly specified as `None` (`--condition=None`), a binding without a
condition is removed. Otherwise, only a binding with a condition that exactly
matches the specified condition (including the optional description) is removed.
For more on conditions, refer to the conditions overview guide:
https://cloud.google.com/iam/docs/conditions-overviewrS   zR
Remove all bindings with this role and principal, irrespective of any
conditions.rT   rU   )rV   r8   	completerr:   rW   rX   z--all
store_true)actionr:   NrY   )r>   condition_completerr\   r]   r^   help_str_condition_allr_   s          r   /_AddConditionFlagsForRemoveBindingFromIamPolicyrg      s    9/ */:"< 779/#   ##%'  )
 l)?  Ar   c                     SU ;   a  SU ;   d  SU ;   d  SU ;   a  Ueg U R                  S5      (       a  U R                  S5      (       d  Ueg )Nr   rC   rE   rD   )get)r   	exceptions     r   ValidateConditionArgumentrk      sU    y	!]i%?9o 	 ==&&immG.D.Do /Er   c                 p    / SQn[        U 5      (       a"  [        U 5      (       d  X;   a  [        S5      eg g g )N)roles/editorzroles/ownerzroles/viewerz|Binding with a condition and a basic role is not allowed. Basic roles are `roles/editor`, `roles/owner`, and `roles/viewer`.)_ConditionIsSpecified_IsNoneConditionr/   )r   roleprimitive_roless      r   'ValidateMutexConditionAndPrimitiveRolesrr      sC    C/I&&/?	/J/J

&	   0K&r   c                 F    [        U 5      n[        XR                  5        U$ )zFExtract IAM condition from arguments and validate conditon/role mutex.)ValidateAndExtractConditionrr   rp   argsr   s     r   $ValidateAndExtractConditionMutexRolerw      s    )$/)))YY?	r   c                     SnU R                  S5      (       a&  [        U R                  [        5        U R                  nU R                  S5      (       a  [	        U R
                  5      nU$ )z%Extract IAM condition from arguments.Nr   condition_from_file)IsSpecifiedrk   r   CONDITION_FORMAT_EXCEPTIONParseYamlOrJsonConditionry   ru   s     r   rt   rt     sX    )	k""dnn.HII	+,,()A)ABI	r   c                 &    U R                  SSSS9  g)zAdds the IAM policy file argument to the given parser.

Args:
  parser: An argparse.ArgumentParser-like object to which we add the argss.

Raises:
  ArgumentError if one of the arguments is already defined in the parser.
policy_filePOLICY_FILEa*          Path to a local JSON or YAML formatted file containing a valid policy.

        The output of the `get-iam-policy` command is a valid file, as is any
        JSON or YAML file conforming to the structure of a
        [Policy](https://cloud.google.com/iam/reference/rest/v1/Policy).
        )r8   r:   N)r=   )r>   s    r   AddArgForPolicyFiler     s"     	  	r   c                 j    SnU R                  SSXS9  [        U SU5        U(       a  [        U 5        gg)a"  Adds the IAM policy binding arguments for role and members.

Args:
  parser: An argparse.ArgumentParser-like object to which we add the argss.
  role_completer: A command_lib.iam.completers.IamRolesCompleter class to
    complete the `--role` flag value.
  add_condition: boolean, If true, add the flags for condition.
  hide_special_member_types: boolean. If true, help text for member does not
    include special values `allUsers` and `allAuthenticatedUsers`.

Raises:
  ArgumentError if one of the arguments is already defined in the parser.
z
    Role name to assign to the principal. The role name is the complete path of
    a predefined role, such as `roles/logging.viewer`, or the role ID for a
    custom role, such as `organizations/{ORGANIZATION_ID}/roles/logging.viewer`.
  --roleTr9   rb   r:   zto add the binding forN)r=   rA   r`   )r>   role_completeradd_conditionr?   rO   s        r   AddArgsForAddIamPolicyBindingr   %  sD    $) 	  I02KL.v6 r   c                 d    U R                  SSUSS9  [        U SU5        U(       a
  [        XS9  gg)ah  Adds the IAM policy binding arguments for role and members.

Args:
  parser: An argparse.ArgumentParser-like object to which we add the args.
  role_completer: A command_lib.iam.completers.IamRolesCompleter class to
    complete the --role flag value.
  add_condition: boolean, If true, add the flags for condition.
  condition_completer: A completer to complete the condition flag value.
  hide_special_member_types: boolean. If true, help text for member does not
    include special values `allUsers` and `allAuthenticatedUsers`.

Raises:
  ArgumentError if one of the arguments is already defined in the parser.
r   Tz&The role to remove the principal from.r   zto remove the binding for)re   N)r=   rA   rg   )r>   r   r   re   r?   s        r    AddArgsForRemoveIamPolicyBindingr   E  sF    & 	3	  5
 35NO39 r   c                 P   UR                    H&  nUR                  U:X  d  M  X$R                  ;   d  M&    g   UR                    H0  nUR                  U:X  d  M  UR                  R                  U5          g   UR                   R                  U " U/SR	                  U5      S95        g)a  Given an IAM policy, add new bindings as specified by args.

An IAM binding is a pair of role and member. Check if the arguments passed
define both the role and member attribute, create a binding out of their
values, and append it to the policy.

Args:
  binding_message_type: The protorpc.Message of the Binding to create
  policy: IAM policy to which we want to add the bindings.
  member: The member to add to IAM policy.
  role: The role the member should have.

Returns:
  boolean, whether or not the policy was updated.
FTz{0})membersrp   )bindingsrp   r   appendr<   )binding_message_typepolicymemberrp   bindings        r   AddBindingToIamPolicyr   c  s    * g||t	??	" ! g||tooV$ ! 	//F8%,,t2DEG	r   c                 "    U SL=(       a    SU ;   $ )z#When user specify --condition=None.Nr   r"   r   s    r   ro   ro     s    	$		66Y#66r   c                 
    U SL$ )zWhen --condition is specified.Nr"   r   s    r   rn   rn     s    	$	r   c                    [        U5      (       a]  [        U5      (       dM  [        R                  " 5       (       d  Sn[	        U5      e[        U5      n[        U[        5        [        XT5        [        U5      (       d6  [        U5      (       a&  [        U5      (       d  [        R                  " S5        [        U5      (       a  SOUn[        U XUXE5        g)a	  Given an IAM policy, add a new role/member binding with condition.

An IAM binding is a pair of role and member with an optional condition.
Check if the arguments passed define both the role and member attribute,
create a binding out of their values, and append it to the policy.

Args:
  binding_message_type: The protorpc.Message of the Binding to create.
  condition_message_type: the protorpc.Message of the Expr.
  policy: IAM policy to which we want to add the bindings.
  member: The member of the binding.
  role: The role the member should have.
  condition: The condition of the role/member binding.

Raises:
  IamPolicyBindingIncompleteError: when user adds a binding without specifying
    --condition to a policy containing conditions in the non-interactive mode.
zAdding a binding without specifying a condition to a policy containing conditions is prohibited in non-interactive mode. Run the command again with `--condition=None`zAdding binding with condition to a policy without condition will change the behavior of add-iam-policy-binding and remove-iam-policy-binding commands.N)_PolicyContainsConditionrn   r   	CanPromptr2   (_PromptForConditionAddBindingToIamPolicyrk   r{   rr   ro   r   warning#_AddBindingToIamPolicyWithCondition)r   condition_message_typer   r   rp   r   messages          r   "AddBindingToIamPolicyWithConditionr     s    * f%%.CI.N.N!!@  ,G448@Ii)CD+I<
"6
*
*I&&/?	/J/JKK 6 7 'y11dy)%&:&<f&*7r   c                 t   0 nU R                    HD  nUb  XR                  ;   d  M  Ub  X$R                  :X  d  M+  UR                  nXS[	        U5      '   MF     SnSU;   a  SnUS	 UR                  5        VVs/ s H  u  puXu4PM
     nnn[        US S9nU(       a  UR                  S[        45        U$ s  snnf )a
  Select conditions in bindings which have the given role and member.

Search bindings from policy and return their conditions which has the given
role and member if role and member are given. If member and role are not
given, return all conditions. Duplicates are not returned.

Args:
  policy: IAM policy to collect conditions
  member: member which should appear in the binding to select its condition
  role: role which should be the role of binding to select its condition

Returns:
  A list of conditions got selected
Fr   Tc                     U S   $ )Nr   r"   )xs    r   <lambda>%_ConditionsInPolicy.<locals>.<lambda>  s    !r   )key)	r   r   rp   r   _ConditionToStringitemssortedr   _NONE_CONDITION)r   r   rp   
conditionsr   r   contain_nonecondition_strs           r   _ConditionsInPolicyr     s     *g&OO3$,:>,,:N##i2;#I./	 !
 ,zL60:0@0@0BD0B,M *0B  Djn5*v/0	Ds   7B4c           
          U c  g/ SQn/ nU HG  n[        X5      c  M  UR                  SR                  UR                  5       [        X5      S95        MI     SR	                  U5      $ )Nr   rC   rD   rE   z{key}={value})r   value, )getattrr   r<   upperjoin)r   keys
key_valuesr   s       r   r   r     sk    	/$*cy*..iik!8 / : ;  
:	r   c                     [        U 5      nU(       a#  US   S   S:w  a  UR                  S[        45        UR                  S[        45        U$ )ao  The choices in a prompt for condition when adding binding to policy.

All conditions in the policy will be returned. Two more choices (i.e.
`None` and `Specify a new condition`) are appended.
Args:
  policy: the IAM policy which the binding is added to.

Returns:
  a list of conditions appearing in policy plus the choices of `None` and
  `Specify a new condition`.
r   r   zSpecify a new condition)r   r   r   _NEW_CONDITION)r   r   s     r   %PromptChoicesForAddBindingToIamPolicyr     sN     #6**JrN1%/v/0.?@	r   c                 Z    [        XU5      nU(       a  UR                  S[        45        U$ )aS  The choices in a prompt for condition when removing binding from policy.

Args:
  policy: the IAM policy which the binding is removed from.
  member: the member of the binding to be removed.
  role: the role of the binding to be removed.

Returns:
  a list of conditions from the policy whose bindings contain the given member
  and role.
zall conditions)r   r   r   )r   r   rp   r   s       r   *PromptChoicesForRemoveBindingFromIamPolicyr     s-     #648*'9:	r   c                 d    [        U [        5      (       a  U $ 0 nS H  n[        X5      X'   M     U$ )Nr   )
isinstancedictr   )r   return_conditionr   s      r   _ToDictConditionr     s9    	4  3c#I3 4	r   c                     Sn[        U 5      nU Vs/ s H  o3S   PM	     nn[        R                  " XAS9nU[        U5      S-
  :X  a
  [	        5       $ [        X%   S   5      $ s  snf )z0Prompt user for a condition when adding binding.zThe policy contains bindings with conditions, so specifying a condition is required when adding a binding. Please specify a condition.r   prompt_string   )r   r   PromptChoicelen_PromptForNewConditionr   )r   prompt_messager   ccondition_keyscondition_indexs         r   r   r     sp    ;. 5V<*",-*QaD*.-++4/J!++!##	*5a8	99 .s   A"c                     [        XU5      nU(       d  [        S5      eSnU Vs/ s H  oUS   PM	     nn[        R                  " XdS9nU[	        U5      S-
  :X  a  [
        $ [        X7   S   5      $ s  snf )z2Prompt user for a condition when removing binding.?Policy binding with the specified principal and role not found!zThe policy contains bindings with conditions, so specifying a condition is required when removing a binding. Please specify a condition.r   r   r   )r   r,   r   r   r   r   r   )r   r   rp   r   r   r   r   r   s           r   -_PromptForConditionRemoveBindingFromIamPolicyr   )  s    9&$O*	
"	 ;. #--*QaD*.-++4/J!++	*5a8	99 .s   A1c                  V    Sn [         R                  " U 5      n[        5       " U5      nU$ )NzCondition is either `None` or a list of key=value pairs. If not `None`, `expression` and `title` are required keys.
Example: --condition=expression=[expression],title=[title],description=[description].
Specify the condition)r   PromptWithDefaultrK   )r   condition_stringcondition_dicts      r   r   r   <  s3    : 
  11.A$&'78.	r   c                     U c  Uc  gU b  Uc  gU R                   UR                  S5      :H  =(       aC    U R                  UR                  S5      :H  =(       a    U R                  UR                  S5      :H  $ )NTFrC   rD   rE   )rC   ri   rD   rE   binding_conditioninput_conditions     r   _EqualConditionsr   G  s{    ?#:/"9

&
&/*=*=l*K
K N

!
!_%8%8%A
AN

'
'?+>+>}+M
MOr   c                    UR                    HZ  nUR                  U:X  d  M  [        UR                  US9(       d  M0  X6R                  ;  a  UR                  R                  U5          g   SnUb5  U" UR                  S5      UR                  S5      UR                  S5      S9nUR                   R                  U " U/SR                  U5      US95        g)	zBGiven an IAM policy, add a new role/member binding with condition.r   NrC   rD   rE   r   z{})r   rp   r   )r   rp   r   r   r   r   ri   r<   )r   r   r   r   rp   r   r   condition_messages           r   r   r   Q  s     g||t 0!++Y!H !H		&v& ! .==.mmG$MM-02 	//(T!2%'(r   c                 @   U(       dS  [        U 5      (       aC  [        U5      (       d3  [        R                  " 5       (       d  Sn[	        U5      e[        XU5      nU(       d  [        U5      (       a  [        XU5        g[        U5      (       a  SOUn[        XX#5        g)a  Given an IAM policy, remove bindings as specified by the args.

An IAM binding is a pair of role and member with an optional condition.
Check if the arguments passed define both the role and member attribute,
search the policy for a binding that contains this role, member and condition,
and remove it from the policy.

Args:
  policy: IAM policy from which we want to remove bindings.
  member: The member to remove from the IAM policy.
  role: The role of the member should be removed from.
  condition: The condition of the binding to be removed.
  all_conditions: If true, all bindings with the specified member and role
    will be removed, regardless of the condition.

Raises:
  IamPolicyBindingNotFound: If specified binding is not found.
  IamPolicyBindingIncompleteError: when user removes a binding without
    specifying --condition to a policy containing conditions in the
    non-interactive mode.
a(  Removing a binding without specifying a condition from a policy containing conditions is prohibited in non-interactive mode. Run the command again with `--condition=None` to remove a binding without condition or run command with `--all` to remove all bindings of the specified principal and role.N)
r   rn   r   r   r2   r   r   (_RemoveBindingFromIamPolicyAllConditionsro   (_RemoveBindingFromIamPolicyWithCondition)r   r   rp   r   all_conditionsr   s         r   'RemoveBindingFromIamPolicyWithConditionr   h  s    4 
4 +I66!!:  ,G44=I '	22,VTB(33I,VTMr   c                 R   SnU R                    HB  nX$R                  :X  d  M  XR                  ;   d  M%  UR                  R                  U5        SnMD     U(       d  [	        S5      eU R                    Vs/ s H  oUR                  (       d  M  UPM     snU R                   SS& gs  snf )zDRemove all member/role bindings from policy regardless of condition.FTz@Policy bindings with the specified principal and role not found!Nr   rp   r   r6   r,   )r   r   rp   conditions_removedr   bs         r   r   r     s    g||// 9ooV$ ! 

"	  $*??@?aii?@&//!@s   5B$B$c                 r   U R                    H[  nX$R                  :X  d  M  [        UR                  US9(       d  M/  XR                  ;   d  M@  UR                  R                  U5          O   [        S5      eU R                    Vs/ s H  oUR                  (       d  M  UPM     snU R                   SS& gs  snf )z>Remove the member/role binding with the condition from policy.r   zKPolicy binding with the specified principal, role, and condition not found!N)r   rp   r   r   r   r6   r,   )r   r   rp   r   r   r   s         r   r   r     s    g!1!++Y"H "H//!ooV$ ! #	)* * $*??@?aii?@&//!@s   B4B4c                 P    U R                    H  nUR                  (       d  M    g   g)a  Investigate if policy has bindings with condition.

Given an IAM policy and return True if the policy contains any binding
which has a condition. Return False otherwise.

Args:
  policy: IAM policy.

Returns:
  True if policy has bindings with conditions, otherwise False.
TF)r   r   )r   r   s     r   r   r     s&     g ! 
r   c                 p    U R                    H&  nUR                  U:X  d  M  XR                  ;   d  M&    g   g)z6Returns True if policy contains the specified binding.TF)r   rp   r   )r   r   rp   r   s       r   BindingInPolicyr     s-    g||t// 9 ! 
r   c                 B   U R                    HA  nUR                  U:X  d  M  XR                  ;   d  M&  UR                  R                  U5          O   Sn[	        U5      eU R                    Vs/ s H  oUR                  (       d  M  UPM     snU R                   SS& gs  snf )a  Given an IAM policy, remove bindings as specified by the args.

An IAM binding is a pair of role and member. Check if the arguments passed
define both the role and member attribute, search the policy for a binding
that contains this role and member, and remove it from the policy.

Args:
  policy: IAM policy from which we want to remove bindings.
  member: The member to remove from the IAM policy.
  role: The role the member should be removed from.

Raises:
  IamPolicyBindingNotFound: If specified binding is not found.
r   Nr   )r   r   rp   r   r   r   s         r   RemoveBindingFromIamPolicyr     sy    $ g||t// 9ooV$ !
 PG
"7
++ $*??@?aii?@&//!@s   -BBc                     [         R                  " U 5      n[        R                  " U5      nSR	                  [        UR                  5       5      5      $ )zConstruct a FieldMask based on input policy.

Args:
  policy_file_path: Path to the JSON or YAML IAM policy file.

Returns:
  a FieldMask containing policy fields to be modified, based on which fields
  are present in the input file.
,)r   ReadFileContentsr   loadr   r   r   )policy_file_pathr~   r   s      r   ConstructUpdateMaskFromPolicyr     s?     &&'78+99[!& 
&'	((r   c                 t    [        U U5      u  p#UR                  (       d  Sn[        R                  " USSS9  U$ )a  Construct an IAM Policy protorpc.Message from a JSON/YAML formatted file.

Args:
  policy_file_path: Path to the JSON or YAML IAM policy file.
  policy_message_type: Policy message type to convert JSON or YAML to.

Returns:
  a protorpc.Message of type policy_message_type filled in from the JSON or
  YAML policy file.
Raises:
  BadFileException if the JSON or YAML file is malformed.
The specified policy does not contain an "etag" field identifying a specific version to replace. Changing a policy without an "etag" can overwrite concurrent policy changes.Replace existing policyTr   r   cancel_on_noParseYamlOrJsonPolicyFileetagr   PromptContinue)r   policy_message_typer   unused_maskmsgs        r   ParsePolicyFiler     sF     22B2EG& 
C #<4Q	-r   c                 v    [        U U5      u  p#UR                  (       d  Sn[        R                  " USSS9  X#4$ )a  Construct an IAM Policy protorpc.Message from a JSON/YAML formatted file.

Also contructs a FieldMask based on input policy.
Args:
  policy_file_path: Path to the JSON or YAML IAM policy file.
  policy_message_type: Policy message type to convert JSON or YAML to.

Returns:
  a tuple of (policy, updateMask) where policy is a protorpc.Message of type
  policy_message_type filled in from the JSON or YAML policy file and
  updateMask is a FieldMask containing policy fields to be modified, based on
  which fields are present in the input file.
Raises:
  BadFileException if the JSON or YAML file is malformed.
  IamEtagReadError if the etag is badly formatted.
r   r   Tr   r   )r   r   r   update_maskr   s        r   ParsePolicyFileWithUpdateMaskr     sJ    " 22B2EG& 
C #<4Q
	r   c           	         [         R                  " U 5      n [        R                  " X5      nSR	                  [        UR                  5       5      5      nX44$ ! [         a?  n[        R                  " SR                  U [        R                  " U5      5      5      eSnAf[        R                  [        R                   4 a4  n[#        SR                  U [        R                  " U5      5      5      eSnAff = f)a  Create an IAM Policy protorpc.Message from a YAML or JSON formatted file.

Returns the parsed policy object and FieldMask derived from input dict.
Args:
  policy_file_path: Path to the YAML or JSON IAM policy file.
  policy_message_type: Policy message type to convert YAML to.

Returns:
  a tuple of (policy, updateMask) where policy is a protorpc.Message of type
  policy_message_type filled in from the JSON or YAML policy file and
  updateMask is a FieldMask containing policy fields to be modified, based on
  which fields are present in the input file.
Raises:
  BadFileException if the YAML or JSON file is malformed.
  IamEtagReadError if the etag is badly formatted.
r   zKPolicy file [{0}] is not a properly formatted YAML or JSON policy file. {1}Nz<The etag of policy file [{0}] is not properly formatted. {1})r   	load_pathr   PyValueToMessager   r   r   AttributeErrorgcloud_exceptionsBadFileExceptionr<   six	text_typeapitools_messagesDecodeErrorbinasciiErrorr    )r   r   policy_to_parser   r   es         r   r   r   6  s    " NN#34/1&&':LF((6/"6"6"89:K 	  G

,
,	!6"2CMM!4DEG G 
'
'	8 1
FMMcmmA.	01 11s#   >A 
C8#:B'C8/C33C8c                 H    [         R                  " U 5      n[        X!5        U$ )aj  Create a condition of IAM policy binding from content of YAML or JSON file.

Args:
  condition_file_content: string, the content of a YAML or JSON file
    containing a condition.
  file_format_exception: InvalidArgumentException, the exception to throw when
    condition file is incorrectly formatted.

Returns:
  a dictionary representation of the condition.
)r   r   rk   )condition_file_contentfile_format_exceptionr   s      r   r|   r|   X  s!     ii./)I=	r   c           	         [         R                  " U 5      nSU;   a  US   R                  5       US'    [        R                  " X5      nU$ ! [
         a?  n[        R                  " SR                  U [        R                  " U5      5      5      eSnAf[        R                  [        R                  4 a4  n[        SR                  U [        R                  " U5      5      5      eSnAff = f)a\  Construct an IAM Role protorpc.Message from a Yaml formatted file.

Args:
  file_path: Path to the Yaml IAM Role file.
  role_message_type: Role message type to convert Yaml to.

Returns:
  a protorpc.Message of type role_message_type filled in from the Yaml
  role file.
Raises:
  BadFileException if the Yaml file is malformed or does not exist.
stagez=Role file {0} is not a properly formatted YAML role file. {1}Nz8The etag of role file {0} is not properly formatted. {1})r   r   r   r   r   r   r  r  r<   r  r  r  r  r  r  r    )	file_pathrole_message_typerole_to_parserp   r
  s        r   ParseYamlToRoler  l  s     ..+-*7399;M'*$$%6FD 
+  *

,
,GNNs}}Q'	)* * 
'
'	8 *
BIIs}}Q'	)* **s#   A 
C+:B'C+7/C&&C+c                 d    [         R                  " U [        R                  5      nUR                  $ )zConstruct a TrustStore protorpc.Message from the content of a Yaml file.

Args:
  yaml_dict: YAML file content to parse.

Returns:
  a TrustStore from the parsed YAML file.
Raises:
  DecodeError if the Yaml file content could not be parsed.
)messages_utilDictToMessageWithErrorCheckmsgsX509
trustStore	yaml_dictconfigs     r   ParseYamlToTrustStorer    s&     44Y		J&			r   c                 d    [         R                  " U [        R                  5      nUR                  $ )a  Construct a InlineCertificateIssuanceConfig protorpc.Message from the content of a Yaml file.

Args:
  yaml_dict: YAML file content to parse.

Returns:
  a InlineCertificateIssuanceConfig from the parsed YAML file.
Raises:
  DecodeError if the Yaml file content could not be parsed.
)r  r  r  WorkloadIdentityPoolinlineCertificateIssuanceConfigr  s     r   0ParseYamlOrJsonToInlineCertificateIssuanceConfigr!    s-     44**& 
	/	//r   c                 d    [         R                  " U [        R                  5      nUR                  $ )zConstruct a InlineTrustConfig protorpc.Message from the content of a Yaml file.

Args:
  yaml_dict: YAML file content to parse.

Returns:
  a InlineTrustConfig from the parsed YAML file.
Raises:
  DecodeError if the Yaml file content could not be parsed.
)r  r  r  r  inlineTrustConfigr  s     r   "ParseYamlOrJsonToInlineTrustConfigr$    s-     44**& 
	!	!!r   c                     U(       d  SU -   nU(       d  SnU(       a  US-   OSnU(       a  SOSnSR                  XP5      S[        R                  " S	R                  U UUUUS
95      S.$ )a  Returns a detailed_help for a set-iam-policy command.

Args:
  collection: Name of the command collection (ex: "project", "dataset")
  example_id: Collection identifier to display in a sample command (ex:
    "my-project", '1234')
  example_see_more: Optional "See ... for details" message. If not specified,
    includes a default reference to IAM managing-policies documentation
  additional_flags: str, additional flags to include in the example command
    (after the command name and before the ID of the resource).
   use_an: If True, uses "an" instead of "a" for the article preceding uses of
     the collection.

Returns:
  a dict with boilerplate help text for the set-iam-policy command
zexample-z
          See https://cloud.google.com/iam/docs/managing-policies for details
          of the policy file format and contents.  anazSet IAM policy for {0} {1}.{description}z          The following command will read an IAM policy from 'policy.json' and
          set it for {a} {collection} with '{id}' as the identifier:

            $ {{command}} {flags}{id} policy.json

          {see_more})
collectionidsee_moreflagsr)  briefDESCRIPTIONEXAMPLES)r<   textwrapdedent)r+  
example_idexample_see_moreadditional_flagsuse_anr)  s         r   GetDetailedHelpForSetIamPolicyr9    s    . 
j(J	5 0@%+Rd#! (
.
.q
=

//  #'$  
 r   c           	          U(       a  SOSnSnSR                  XP5      SSR                  XX%S9S.nU(       a  US	   S
R                  XX%S9-   US	'   SR                  US	   U/5      US	'   U$ )a  Returns a detailed_help for an add-iam-policy-binding command.

Args:
  collection: Name of the command collection (ex: "project", "dataset")
  example_id: Collection identifier to display in a sample command
      (ex: "my-project", '1234')
  role: The sample role to use in the documentation. The default of
    'roles/editor' is usually sufficient, but if your command group's users
    would more likely use a different role, you can override it here.
  use_an: If True, uses "an" instead of "a" for the article preceding uses of
    the collection.
  condition: If True, add help text for condition.

Returns:
  a dict with boilerplate help text for the add-iam-policy-binding command
r(  r)  zgSee https://cloud.google.com/iam/docs/managing-policies for details of policy role and principal types.z#Add IAM policy binding for {0} {1}.r*  a  To add an IAM policy binding for the role of `{role}` for the user
`test-user@gmail.com` on {a} {collection} with identifier
`{example_id}`, run:

  $ {{command}} {example_id} --member='user:test-user@gmail.com' --role='{role}'

To add an IAM policy binding for the role of `{role}` to the service
account `test-proj1@example.domain.com`, run:

  $ {{command}} {example_id} --member='serviceAccount:test-proj1@example.domain.com' --role='{role}'

To add an IAM policy binding for the role of `{role}` for all
authenticated users on {a} {collection} with identifier
`{example_id}`, run:

  $ {{command}} {example_id} --member='allAuthenticatedUsers' --role='{role}'
  )r+  r5  rp   r)  r/  r2  a  

To add an IAM policy binding that expires at the end of the year 2018 for the
role of `{role}` and the user `test-user@gmail.com` on {a} {collection} with
identifier `{example_id}`, run:

  $ {{command}} {example_id} --member='user:test-user@gmail.com' --role='{role}' --condition='expression=request.time < timestamp("2019-01-01T00:00:00Z"),title=expires_end_of_2018,description=Expires at midnight on 2018-12-31'
  
r<   r   r+  r5  rp   r8  r   r)  notedetailed_helps           r   %GetDetailedHelpForAddIamPolicyBindingr@    s    * d#!0$ 0
6
6q
E
  f
fJ--0  -j 9 = f  D!DM* #iiz)BD(IJ-
	r   c                     U(       a  SOSnSnSR                  XP5      SSR                  XUS9S.nU(       a  US	   S
R                  XSS9-   US	'   SR                  US	   U/5      US	'   U$ )a  Returns a detailed_help for a remove-iam-policy-binding command.

Args:
  collection: Name of the command collection (ex: "project", "dataset")
  example_id: Collection identifier to display in a sample command
      (ex: "my-project", '1234')
  role: The sample role to use in the documentation. The default of
    'roles/editor' is usually sufficient, but if your command group's users
    would more likely use a different role, you can override it here.
  use_an: If True, uses "an" instead of "a" for the article preceding uses of
    the collection.
  condition: If True, add help text for condition.

Returns:
  a dict with boilerplate help text for the remove-iam-policy-binding command
r(  r)  zdSee https://cloud.google.com/iam/docs/managing-policies for details of policy role and member types.z&Remove IAM policy binding for {0} {1}.r*  a  To remove an IAM policy binding for the role of `{role}` for the
user `test-user@gmail.com` on {collection} with identifier
`{example_id}`, run:

  $ {{command}} {example_id} --member='user:test-user@gmail.com' --role='{role}'

To remove an IAM policy binding for the role of `{role}` from all
authenticated users on {collection} `{example_id}`, run:

  $ {{command}} {example_id} --member='allAuthenticatedUsers' --role='{role}'
  )r+  r5  rp   r/  r2  a*  

To remove an IAM policy binding with a condition of
`expression='request.time < timestamp("2019-01-01T00:00:00Z"),
title='expires_end_of_2018'`, and
description=`Expires at midnight on 2018-12-31` for the role of `{role}` for
the user `test-user@gmail.com` on {collection}
with identifier `{example_id}`, run:

  $ {{command}} {example_id} --member='user:test-user@gmail.com' --role='{role}' --condition='expression=request.time < timestamp("2019-01-01T00:00:00Z"),title=expires_end_of_2018,description=Expires at midnight on 2018-12-31'

To remove all IAM policy bindings regardless of the condition for the role of
`{role}` and for the user `test-user@gmail.com` on {collection} with
identifier `{example_id}`, run:

  $ {{command}} {example_id} --member='user:test-user@gmail.com' --role='{role}' --all
  zroles/browserr;  r<  r=  s           r   (GetDetailedHelpForRemoveIamPolicyBindingrB  /  s    * d#!*  3
9
9!
H
 f
fE#-&  -j 9 = f  J!JM*" #iiz)BD(IJ-
	r   c                      SR                  U S9$ )zReturns a hint message for commands treating service account as a resource.

Args:
  action: the action to take on the service account resource (with necessary
    prepositions), such as 'add iam policy bindings to'.
aE  When managing IAM roles, you can treat a service account either as a resource or as an identity. This command is to {action} a service account resource. There are other gcloud commands to manage IAM policies for other types of resources. For example, to manage IAM policies on a project, use the `$ gcloud projects` commands.rd   rN   rD  s    r    GetHintForServiceAccountResourcerE  r  s    
 fFf+-r   c                     U S:X  a  [         R                  /$ U S:X  a  [         R                  /$ U S:X  a  / $ [         R                  /$ )aF  Parses a string into a MANAGED_BY enum.

MANAGED_BY is an enum of who manages a service account key resource. IAM
will rotate any SYSTEM_MANAGED keys by default.

Args:
  managed_by: A string representation of a MANAGED_BY. Can be one of *user*,
    *system* or *any*.

Returns:
  A KeyTypeValueValuesEnum (MANAGED_BY) value.
usersystemany)
MANAGED_BYUSER_MANAGEDSYSTEM_MANAGEDKEY_TYPE_UNSPECIFIED)
managed_bys    r   ManagedByFromStringrO    sN     6##$$X%%&&UI++,,r   c                 z    U S:X  a  [         R                  $ U S:X  a  [         R                  $ [         R                  $ )zParses a string into a KeyType enum.

Args:
  key_str: A string representation of a KeyType. Can be either *p12* or
    *json*.

Returns:
  A PrivateKeyTypeValueValuesEnum value.
p12json)	KEY_TYPESTYPE_PKCS12_FILETYPE_GOOGLE_CREDENTIALS_FILETYPE_UNSPECIFIEDkey_strs    r   KeyTypeFromStringrY    s8     %%%&111%%%r   c                     U [         R                  :X  d  U [        R                  :X  a  gU [         R                  :X  d  U [        R                  :X  a  gg)zGet a string version of a KeyType enum.

Args:
  key_type: An enum of either KEY_TYPES or CREATE_KEY_TYPES.

Returns:
  The string representation of the key_type, such that
  parseKeyType(keyTypeToString(x)) is a no-op.
rQ  rR  unspecified)rS  rT  CREATE_KEY_TYPESrU  key_types    r   KeyTypeToStringr_    sG     ),,,"333I:::$AAAr   c                     U [         R                  :X  a  [        R                  $ U [         R                  :X  a  [        R                  $ [        R                  $ )a  Transforms between instances of KeyType enums.

Transforms KeyTypes into CreateKeyTypes.

Args:
  key_type: A ServiceAccountKey.PrivateKeyTypeValueValuesEnum value.

Returns:
  A IamProjectsServiceAccountKeysCreateRequest.PrivateKeyTypeValueValuesEnum
  value.
)rS  rT  r\  rU  rV  r]  s    r   KeyTypeToCreateKeyTypera    sD     +++,,,9999888,,,r   c                     U [         R                  :X  a  [        R                  $ U [         R                  :X  a  [        R                  $ [        R                  $ )z!The inverse of *toCreateKeyType*.)r\  rT  rS  rU  rV  r]  s    r   KeyTypeFromCreateKeyTyperc    sD    !222%%%#@@@111%%%r   c                 $    SR                  U 5      $ )z0Turns a project id into a project resource name.projects/{0}rN   )projects    r   ProjectToProjectResourceNamerg    s    			w	''r   c                 $    SR                  U 5      $ )z4Turns an email into a service account resource name.zprojects/-/serviceAccounts/{0}rN   )emails    r   EmailToAccountResourceNamerj    s    	)	0	0	77r   c                 $    SR                  X5      $ )z3Turns an email and key id into a key resource name.z'projects/-/serviceAccounts/{0}/keys/{1}rN   )ri  r   s     r   EmailAndKeyToResourceNamerl    s    	2	9	9%	EEr   c                 $    SR                  X5      $ )z@Turns an email and identity binding id into a key resource name.z3projects/-/serviceAccounts/{0}/identityBindings/{1}rN   )ri  identity_bindings     r   %EmailAndIdentityBindingToResourceNamero    s    	>	E	E
 r   c                 *    U R                  S5      S   $ )z<Gets the key id from a resource name. No validation is done./   )split)names    r   GetKeyIdFromResourceNameru    s    	C	r   c                 N    U S:X  a  [         R                  $ [         R                  $ )zParses a string into a PublicKeyType enum.

Args:
  key_str: A string representation of a PublicKeyType. Can be either *pem* or
    *raw*.

Returns:
  A PublicKeyTypeValueValuesEnum value.
pem)PUBLIC_KEY_TYPESTYPE_X509_PEM_FILETYPE_RAW_PUBLIC_KEYrW  s    r   PublicKeyTypeFromStringr{    s$     ...		-	--r   c           	      :   U R                  5       n[        R                  [        R                  [        R                  [        R
                  [        R                  S.nX;  a5  [        R                  " SSSR                  [        U5      5      -   S-   5      eX!   $ )zParses a string into a stage enum.

Args:
  stage_str: A string representation of a StageType. Can be *alpha* or *beta*
    or *ga* or *deprecated* or *disabled*.

Returns:
  A StageValueValuesEnum value.
)alphabetaga
deprecateddisabledr  zThe stage should be one of r   .)lowerSTAGE_TYPESALPHABETAGA
DEPRECATEDDISABLEDr  InvalidArgumentExceptionr   r   )	stage_strlower_stage_str
stage_dicts      r   StageTypeFromStringr  	  s     OO%/  NN**&&* &

4
4%
1C(DDsJL L 
	$$r   c                     U c)  Uc&  [         R                  " SSR                  U5      5      eU (       a  U(       a  [         R                  " SS5      egg)zVerify the parent name.Nz--organization or --projectz8Should specify the project or organization name for {0}.organizationrf  )r  RequiredArgumentExceptionr<   ConflictingArgumentsExceptionr  rf  	attributes      r   VerifyParentr  "  sY    go

5
5%BII	  g

9
9	# # \r   c                    UR                  S5      (       a'  U(       d  U (       a  [        R                  " US5      eU$ UR                  S5      (       d  UR                  S5      (       a  [        R                  " US5      eSU;   a  [        R                  " US5      e[        XU5        U (       a  SR	                  X5      $ S	R	                  X5      $ )
z4Gets the Role name from organization Id and role Id.zroles/zThe role id that starts with 'roles/' only stands for predefined role. Should not specify the project or organization for predefined rolesz	projects/zorganizations/zJThe role id should not include any 'projects/' or 'organizations/' prefix.rq  z1The role id should not include any '/' character.zorganizations/{0}/roles/{1}zprojects/{0}/roles/{1})
startswithr  r  r  r<   )r  rf  rp   r  parameter_names        r   GetRoleNamer  .  s     
__X,66
 
 K	__[!!T__5E%F%F

4
4 %& & 	D[

4
4MO O|i0(//CC	!	(	(	77r   c                 l    [        XU5        U (       a  SR                  U 5      $ SR                  U5      $ )zAGets the Role parent name from organization name or project name.zorganizations/{0}re  )r  r<   r  s      r   GetParentNamer  J  s1    |i0%%l33			w	''r   c                 D   U R                  5       n[        R                  " SSU5      n[        R                  " SSU5      n[        R                  R
                  R                  nUR                  5       nUR                  U:w  a  UR                  UUR                  S5      nUR                  S5      (       ah  UR                  S5      nUR                  S5      S   nUR                  S5        SR                  U5      nUR                  SSR                  U5      5      nU$ )	zConvert a full resource URL to a full resource name (FRN).

See https://cloud.google.com/iam/docs/full-resource-names.

Args:
  resource_ref: googlecloudsdk.core.resources.Resource.

Returns:
  str: Full resource name of the resource
z\w+://z//z/v[0-9]+[0-9a-zA-Z]*/rq  r   z//www.r   z//{0}.)SelfLinkresubr   VALUEScoreuniverse_domainGetdefaultreplacer  rs  popr   r<   )resource_ref	full_nameuniverse_domain_propertyr  splitted_listservices         r   GetFullResourceNamer  R  s     ##%)ffYi0)ff-sI>)'..33CC,002/%%8!!/":"B"BAGI (##OOC(Mooc"1%Ga'I!!(HOOG,DEI	r   c                     [         R                  R                  U R                  SU R                  0[
        S9nUR                  5       $ )zTransforms a service account resource into a URL string.

Args:
  resource: The ServiceAccount object

Returns:
  URL to the service account

projectsIdr+  )r   REGISTRYParseuniqueId	projectIdSERVICE_ACCOUNTS_COLLECTIONr  )resourcerefs     r   ServiceAccountsUriFuncr  r  sF     	  ,(:(:;, 	! 	.# 
r   c           	      t    U R                  SS[        5       [        R                  SR	                  U5      S9  g)ay  Adds the IAM service account name argument that supports tab completion.

Args:
  parser: An argparse.ArgumentParser-like object to which we add the args.
  action: Action to display in the help message. Should be something like 'to
    act on' or a relative phrase like 'whose policy to get'.

Raises:
  ArgumentError if one of the arguments is already defined in the parser.
service_accountSERVICE_ACCOUNTzThe service account {}. The account should be formatted either as a numeric service account ID or as an email, like this: 123456789876543212345 or my-iam-account@somedomain.com.)r8   rV   rb   r:   N)r=   GetIamAccountFormatValidatorr   IamServiceAccountCompleterr<   r>   rd   s     r   AddServiceAccountNameArgr    s<     	')55- .4VF^  	>r   c           
      p    U R                  SS[        R                  " 5       SSSR                  U5      S9  g)a[  Adds optional recommend argument to the parser.

Args:
  parser: An argparse.ArgumentParser-like object to which we add the args.
  action: Action to display in the help message. Should be something like
    'deletion' or a noun that describes the action being performed.

Raises:
  ArgumentError if the argument is already defined in the parser.
z--recommendBOOLEAN_VALUEFzIf true, checks Active Assist recommendation for the risk level of service account {}, and issues a warning in the prompt. Optional flag is set to false by default. For details see https://cloud.google.com/recommender/docs/change-risk-recommendations)r8   rV   r  r9   r:   N)r=   r	   
ArgBooleanr<   r  s     r   AddServiceAccountRecommendArgr    s?     	!!#-
 	v  r   c                 `    [         R                  R                  SR                  X5      5        g )NzUpdated IAM policy for {} [{}].)r   statusPrintr<   )rt  kinds     r   LogSetIamPolicyr    s     **4;;DGHr   c                  0    [         R                  " SS5      $ )z5Checks that provided iam account identifier is valid.z^(.+@.+\..+|[0-9]+)$zNot a valid service account identifier. It should be either a numeric string representing the unique_id or an email of the form: my-iam-account@somedomain.com or my-iam-account@PROJECT_ID.iam.gserviceaccount.com)r	   RegexpValidatorr"   r   r   r  r    s    		$	$:
; ;r   c                      S n U $ )z&Checks if the output file is writable.c                     U S:X  a  U $  [         R                  " U SS9 nUR                  5         U sS S S 5        $ ! , (       d  f       g = f! [         R                   a  n[        R
                  " U5      eS nAff = f)N-T)private)r   
FileWritercloser  r  r  )r   fr
  s      r   
IsWritable-GetIamOutputFileValidator.<locals>.IsWritable  sc    |l2E40A		 100 ;; 2..q112s1   A ;	A 
A	A 	A A; A66A;r"   )r  s    r   GetIamOutputFileValidatorr    s    	2 
r   c                 @    U R                   c  [        S5      U l         gg)zUSet the role stage to Alpha if None.

Args:
  role: A protorpc.Message of type Role.
Nr}  )r  r  )rp   s    r   SetRoleStageIfAlphar    s     
ZZ$W-DJ r   c                     U (       a  [         R                  R                  U SS9$ [         R                  R                  USS9$ )zGet the resource reference of a project or organization.

Args:
  project: A project name string.
  organization: An organization id string.

Returns:
  The resource reference of the given project or organization.
zcloudresourcemanager.projectsr  z"cloudresourcemanager.organizations)r   r  r  )rf  r  s     r   GetResourceReferencer    sS     ##; $ = = ##!E $ G Gr   c                 n    U (       a.  SSR                  U 5      -   S-   n[        R                  " USSS9  gg)zPrompt a warning for TESTING permissions with a 'y/n' question.

Args:
  permissions: A list of permissions that need to be warned.
zNote: permissions [r   z] are in 'TESTING' stage which means the functionality is not mature and they can go away in the future. This can break your workflows, so do not use them in production systems!z*Are you sure you want to make this change?Tr   N)r   r   r   permissionsr   s     r   TestingPermissionsWarningr    sB      499[#99!!C
 B r   c                 n    U (       a.  SSR                  U 5      -   S-   n[        R                  " U5        gg)zrPrompt a warning for API diabled permissions.

Args:
  permissions: A list of permissions that need to be warned.
z%API is not enabled for permissions: [r   zB]. Please enable the corresponding APIs to use those permissions.
N)r   r   r   r  s     r   ApiDisabledPermissionsWarningr    s9     /$))K2HHM	N  KK	 r   )Tr   )NFF)NFNF)NN)F)r'  r'  r'  F)rm   FF)zact on)custom roles)r  ROLE_ID)z	to act on)r(   
__future__r   r   r   r  r  r3  apitools.base.protorpcliter   r  apitools.base.pyr   googlecloudsdk.api_lib.utilr   	core_apisr  googlecloudsdk.callioper	   r
   r  googlecloudsdk.command_lib.iamr   googlecloudsdk.corecore_exceptionsr   r   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   r  GetMessagesModuler  )IamProjectsServiceAccountsKeysListRequestKeyTypesValueValuesEnumrJ  CreateServiceAccountKeyRequestPrivateKeyTypeValueValuesEnumr\  ServiceAccountKeyrS  (IamProjectsServiceAccountsKeysGetRequestPublicKeyTypeValueValuesEnumrx  RoleStageValueValuesEnumr  r  SERVICE_ACCOUNT_FORMATSERVICE_ACCOUNT_KEY_FORMATr  r{   CONDITION_FILE_FORMAT_EXCEPTION!MAX_LIBRARY_IAM_SUPPORTED_VERSIONr   objectr   r   r   r  r    r,   r/   r2   rA   rK   rP   r`   rg   rk   rr   rw   rt   r   r   r   r   ro   rn   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r|   r  r  r!  r$  r9  r@  rB  rE  rO  rY  r_  ra  rc  rg  rj  rl  ro  ru  r{  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r"   r   r   <module>r     sL   3 &  '  	  D % 9 A / C 5 = # * ) $ 2 * 
 ""5$/22JJ  	''EE ##AA	11NN yy--< & 	  /GG !  #4"L"LE#F  %& !$-4.&A,, AC44 CA?#8#8 AD&B D*BG0)6 IMAD, 2605<A7B 59389=?D	9<%P7

'7TB	&$::&O(6 <A	+N\AA$A<)&4<H :(>0""& 3p 0>1649	:~ 3A497<	@F- -.&$(-.&(
8
F

.%2	# )(	88(@ >06I;".G$$
r   