
    .5                        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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mZ ddlmZ ddlmZ ddlZdZdZ G d dej:                        Z G d dej:                        Z G d de      Z d Z!d Z"d Z#d Z$d Z%d Z&d  Z'd! Z(d,d"Z)d# Z*d$ Z+d% Z,d& Z-d,d'Z.d( Z/d) Z0d* Z1d-d+Z2y).z4Command line processing utilities for access levels.    )absolute_import)division)unicode_literals)encoding)util)waiter)base)concepts)common)policies)	arg_utils)concept_parsers)
exceptions)	resources)yamlN0accesscontextmanager.accessPolicies.accessLevelsa  
Invalid format: {}

The valid fields for the YAML objects in this file type are [{}].

For an access level condition file, an example of the YAML-formatted list of conditions will look like:

 - ipSubnetworks:
   - 162.222.181.197/24
   - 2001:db8::/48
 - members:
   - user:user@example.com

For access levels file, an example of the YAML-formatted list of access levels will look like:

 - name: accessPolicies/my_policy/accessLevels/my_level
   title: My Level
   description: Level for foo.
   basic:
     combiningFunction: AND
     conditions:
     - ipSubnetworks:
       - 192.168.100.14/24
       - 2001:db8::/48
     - members:
       - user1:user1@example.com
c                        e Zd Z fdZ xZS )ParseResponseErrorc                 J    t         t        |   dj                  |             y )NzIssue parsing response: {})superr   __init__format)selfreason	__class__s     =lib/googlecloudsdk/command_lib/accesscontextmanager/levels.pyr   zParseResponseError.__init__F   s"    	

5<<VDE    __name__
__module____qualname__r   __classcell__r   s   @r   r   r   D   s    F Fr   r   c                        e Zd Z fdZ xZS )
ParseErrorc                 L    t         t        |   dj                  ||             y )NzIssue parsing file [{}]: {})r   r%   r   r   )r   pathr   r   s      r   r   zParseError.__init__M   s#    	*
6==dFKLr   r   r#   s   @r   r%   r%   K   s    M Mr   r%   c                        e Zd Z fdZ xZS )InvalidFormatErrorc           	          |j                         D cg c]  }|j                   }}t        t        |   |t
        j                  |dj                  |                   y c c}w )N, )
all_fieldsnamer   r)   r   _INVALID_FORMAT_ERRORr   join)r   r'   r   message_classfvalid_fieldsr   s         r   r   zInvalidFormatError.__init__T   s^    $1$<$<$>?$>qAFF$>L?	

 5==dii- / 0 @s   A!r   r#   s   @r   r)   r)   R   s    0 0r   r)   c                     	 t        j                  |       S # t         j                  $ r }t        | dj	                  |            d }~wt         j
                  $ r }t        | dj	                  |            d }~ww xY w)NzProblem loading file: {}z Problem parsing data as YAML: {})r   	load_pathFileLoadErrorr%   r   YAMLParseError)r'   errs     r   	_LoadDatar8   [   sq    K>>$			 C
T5<<SA
BB			 K
T=DDSI
JJKs     A;AA;A66A;c                     t               }|D ]2  }|j                         s|j                  |j                                4 |r7t        | dj	                  dj                  |            t        |d               y NUnrecognized fields: [{}]r+   r   setall_unrecognized_fieldsupdater)   r   r/   type)r'   
conditionsunrecognized_fields	conditions       r   *_ValidateAllBasicConditionFieldsRecognizedrD   d   su    i((*  !B!B!DE  
#**4995H+IJZ]  r   c           	          |j                         rBt        | dj                  dj                  |j                                     t	        |            y )Nr;   r+   )r>   r)   r   r/   r@   )r'   exprs     r   "_ValidateAllCustomFieldsRecognizedrG   p   sO    	!!#
)00((*2, -.24j: : $r   c                     t               }|D ]2  }|j                         s|j                  |j                                4 |r7t        | dj	                  dj                  |            t        |d               y r:   r<   )r'   levelsrB   levels       r   !_ValidateAllLevelFieldsRecognizedrK   w   st    e$$&  !>!>!@A  
#**4995H+IJVAY  r   c                       fd}|S )zFWrapper around ParseReplaceAccessLevelsResponse to accept api version.c                 D   t        j                        }t        j                  j	                  | j
                  d      }t        j                  |j                  |j                  |      }t        j                  ||dj                  |j                                     S )a~  Parse the Long Running Operation response of the ReplaceAccessLevels call.

    Args:
      lro: Long Running Operation response of ReplaceAccessLevels.
      unused_args: not used.

    Returns:
      The replacement Access Levels created by the ReplaceAccessLevels call.

    Raises:
      ParseResponseError: if the response could not be parsed into the proper
      object.
    versionzaccesscontextmanager.operations)
collectionz0Waiting for Replace Access Levels operation [{}])r   	GetClientr   REGISTRYParser-   r   BulkAPIOperationPolleraccessPolicies_accessLevels
operationsr   WaitForr   Name)lrounused_argsclientoperation_refpollerapi_versions        r   )VersionedParseReplaceAccessLevelsResponsezSParseReplaceAccessLevelsResponse.<locals>.VersionedParseReplaceAccessLevelsResponse   s     ^^K0F&&,,> - @M**6+M+M+1+<+<mMF >>:AA 	"# #r    )r^   r_   s   ` r    ParseReplaceAccessLevelsResponsera      s    #2 
32r   c                       fd}|S )6Wrapper around ParseCustomLevel to accept api version.c                 ^   t        j                  |       }|st        | d      t        j                        }|j
                  }	 |D cg c]  }t        j                  ||       }}t        | |       |S c c}w # t        $ r%}t        | t        j                  |      |      d}~ww xY w)a	  Parse a YAML representation of basic level conditions.

    Args:
      path: str, path to file containing basic level conditions

    Returns:
      list of Condition objects.

    Raises:
      ParseError: if the file could not be read into the proper object
    File is emptyrN   N)r   r4   r%   r   GetMessages	Conditionr   DictToMessage	Exceptionr)   six	text_typerD   )r'   datamessagesr0   crA   r7   r^   s          r   "VersionedParseBasicLevelConditionszEParseBasicLevelConditions.<locals>.VersionedParseBasicLevelConditions   s     >>$Dt_--4H&&MHFJKdH**1m<djK /tZ@ L HtS]]3%7GGH*   A> A9)A> 9A> >	B, B''B,r`   )r^   ro   s   ` r   ParseBasicLevelConditionsrq      s    8 
,+r   c                       fd}|S )rc   c                 :   t        j                  |       }|st        | d      t        j                        }|j
                  }	 t        j                  ||      }t        | |       |S # t        $ r%}t        | t        j                  |      |      d}~ww xY w)a
  Parse a YAML representation of custom level conditions.

    Args:
      path: str, path to file containing custom level expression

    Returns:
      string of CEL expression.

    Raises:
      ParseError: if the file could not be read into the proper object
    re   rN   N)r   r4   r%   r   rf   Exprr   rh   ri   r)   rj   rk   rG   )r'   rl   rm   r0   rF   r7   r^   s         r   VersionedParseCustomLevelz3ParseCustomLevel.<locals>.VersionedParseCustomLevel   s     >>$Dt_--4HMMMH##D-8d 'tT2K	  HtS]]3%7GGHs   A, ,	B5 BBr`   )r^   ru   s   ` r   ParseCustomLevelrv      s    6 
#"r   c                       fd}|S )z7Wrapper around ParseAccessLevels to accept api version.c                 ^   t        j                  |       }|st        | d      t        j                        }|j
                  }	 |D cg c]  }t        j                  ||       }}t        | |       |S c c}w # t        $ r%}t        | t        j                  |      |      d}~ww xY w)a4  Parse a YAML representation of a list of Access Levels with basic/custom level conditions.

    Args:
      path: str, path to file containing basic/custom access levels

    Returns:
      list of Access Level objects.

    Raises:
      ParseError: if the file could not be read into the proper object
    re   rN   N)r   r4   r%   r   rf   AccessLevelr   rh   ri   r)   rj   rk   rK   )r'   rl   rm   r0   rn   rI   r7   r^   s          r   VersionedParseAccessLevelsz5ParseAccessLevels.<locals>.VersionedParseAccessLevels   s     >>$Dt_--4H((MHBFG$Q&&q-8$fG &dF3M H HtS]]3%7GGHrp   r`   )r^   rz   s   ` r   ParseAccessLevelsr{      s    6 
$#r   c                 h    ~ ||S |j                  d      s|j                  j                  d       |S )zFClear basic field (and default combine function) if spec not provided.basic_level_specbasic)IsSpecifiedaccessLevelreset)refargsreqs      r   (ClearCombiningFunctionUnlessBasicSpecSetr     s5    	[J			,	-OO'"	*r   c                  0    t        j                  dd      S )NrJ   zThe ID of the access level.)r-   	help_text)r
    ResourceParameterAttributeConfigr`   r   r   GetAttributeConfigr     s    		2	2;
= =r   c                  h    t        j                  ddt        j                         t                     S )Nr   rJ   )resource_nameaccessPoliciesIdaccessLevelsId)r
   ResourceSpecr   r   r`   r   r   GetResourceSpecr     s-    			8224')	
+ +r   c                     t         j                  j                  dt               dj	                  |      d      j                  |        y)Add a resource argument for an access level.

  NOTE: Must be used only if it's the only resource arg in the command.

  Args:
    parser: the parser for the command.
    verb: str, the verb to describe the resource, such as 'to update'.
  rJ   The access level {}.TrequiredNr   ConceptParserForResourcer   r   AddToParserparserverbs     r   AddResourceArgr     sC     ++##D)	 ,  ![(r   c                     t         j                  j                  dt               dj	                  |      d      j                  |        y)r   z--levelr   Tr   Nr   r   s     r   AddResourceFlagArgr   /  sC     ++##D)	 ,  ![(r   c                     t        j                  dt        j                  |       j                  j
                  ddddd      S )	Nz--combine-functionrN   andor)ANDORFz:For a basic level, determines how conditions are combined.)custom_mappingsr   help_str)r   ChoiceEnumMapperr   rf   
BasicLevel CombiningFunctionValueValuesEnumr^   s    r   GetCombineFunctionEnumMapperr   ?  sG    		#	#
)z*J*J K

 
r   c                     t        j                  d      t        j                  d      g}|D ]  }|j                  |         y)z1Add common args for level create/update commands.zaccess levelN)r   GetDescriptionArgGetTitleArgr   )r   r   args      r   AddLevelArgsr   M  s?     ~.(
$ cOOF r   c                     d}t        j                  d|t        |            }t        |      j                  }|j                  |        |j                  |        y)z.Add args for basic spec (with no custom spec).as  Path to a file containing a list of basic access level conditions.

An access level condition file is a YAML-formatted list of conditions, which are YAML objects representing a Condition as described in the API reference. For example:

    ```
     - ipSubnetworks:
       - 162.222.181.197/24
       - 2001:db8::/48
     - members:
       - user:user@example.com
    ```--basic-level-spechelpr@   r   N)r	   Argumentrq   r   
choice_argr   )r   r^   basic_level_help_textbasic_level_spec_argbasic_level_combine_args        r   AddBasicSpecArgsr   W  s`    
   $[13 9)z  ""6*%%f-r   c                    d}d}t        j                  d|t        |            }t        |      j                  }t        j
                  d      }|j                  |       |j                  |       t        j                  d|t        |            }t        j
                  d	      }|j                  |       t        j
                  d
d      }	|	j                  |       |	j                  |       |	j                  |        y)z7Add args for basic and custom specs (grouped together).ar  Path to a file containing a list of basic access level conditions.

An access level condition file is a YAML-formatted list of conditions,which are YAML objects representing a Condition as described in the API reference. For example:

    ```
     - ipSubnetworks:
       - 162.222.181.197/24
       - 2001:db8::/48
     - members:
       - user:user@example.com
    ```zPath to a file representing an expression for an access level.

The expression is in the Common Expression Langague (CEL) format.For example:

    ```
     expression: "origin.region_code in ['US', 'CA']"
    ```r   r   r   zBasic level specification.)r   z--custom-level-speczCustom level specification.zLevel specification.T)r   mutexN)	r	   r   rq   r   r   ArgumentGroupAddArgumentrv   r   )
r   r^   r   custom_level_help_textr   r   basic_level_spec_groupcustom_level_spec_argcustom_level_spec_grouplevel_spec_groups
             r   AddBasicAndCustomSpecArgsr   p  s    
    $[13 9)z   --3OP$$%9:$$%<=--!K(* !..(*%%&;<''-C4P5667v&r   c                 b    |i }|j                  dd      rt        | |       yt        | |       y)z/Add arguments for in-file level specifications.Ncustom_levelsF)getr   r   )r   r^   feature_masks      r   AddLevelSpecArgsr     s1    Lou-fk2V[)r   )N)NN)3__doc__
__future__r   r   r   apitools.base.pyr   +googlecloudsdk.api_lib.accesscontextmanagerr   googlecloudsdk.api_lib.utilr   googlecloudsdk.callioper	    googlecloudsdk.calliope.conceptsr
   /googlecloudsdk.command_lib.accesscontextmanagerr   r   $googlecloudsdk.command_lib.util.apisr   (googlecloudsdk.command_lib.util.conceptsr   googlecloudsdk.corer   r   r   rj   
COLLECTIONr.   Errorr   r%   r)   r8   rD   rG   rK   ra   rq   rv   r{   r   r   r   r   r   r   r   r   r   r   r`   r   r   <module>r      s    ; &  ' % < . ( 5 B D : D * ) $ 
?
 :F)) FM!! M0 0K	:	3>,D#B$B	=
+) ) .21'h*r   