
    d                         d 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ZdZ	dZ
d	Zd
 Zd Zd Zd Zd Zd Zd 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,Utils for GKE Hub Identity Service commands.    )absolute_import)division)unicode_literalsN)
exceptions      i  c                 V   t        | j                        dk7  rt        j                  d      | j                  d   }t	        |       t        |      }t        |      }||t        j                  d      |j                         }t        ||      |_	        t        ||      |_        |S )a  Load FeatureSpec MemberConfig from the parsed ClientConfig CRD yaml file.

  Args:
    loaded_config: YamlConfigFile, The data loaded from the ClientConfig CRD
      yaml file given by the user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: The MemberConfig configuration containing the AuthMethods for
      the IdentityServiceFeatureSpec.
     z1Input config file must contain one YAML document.r   zOA valid 'spec.identityServiceOptions' or 'spec.authentication' must be provided)lendatar   Errorvalidate_clientconfig_metaget_auth_methodsget_identity_service_optionsIdentityServiceMembershipSpec5validate_and_construct_identity_service_options_protoidentityServiceOptions)validate_and_construct_auth_methods_protoauthMethods)loaded_configmsgclientconfigauth_methodsidentity_service_optionsmember_configs         Hlib/googlecloudsdk/command_lib/container/fleet/identity_service/utils.pyparse_configr   #   s     			!


N
OO##A&,\*!,/,9,G6>


	 
 335-;
"C &
 HC- 
    c                 X    | d   }|d|vry |d   st        j                  d      |d   S )Nspecr   z?Must provide a valid option under 'spec.identityServiceOptions'r   r   r   r    s     r   r   r   K   sI    	f	$	\-T9	&	'


I  
&	''r   c           	          | yt         t        d}|j                         }| D ]A  }||vr$t        j                  dj                  |            t        || ||   ||              C |S )a  Constructs an IdentityServiceMembershipSpec.IdentityServiceIdentityServiceOptions instance from the provided `identity_service_options_config` config.

  Args:
    identity_service_options_config: a map of non-protocol-related configuration
      options from the applied configuration.
    msg: The gkehub message package

  Returns:
    an instance of
    IdentityServiceMembershipSpec.IdentityServiceIdentityServiceOptions

  Raises:
    exceptions.Error: if an unsupported option is found under
    `spec.IdentityServiceOptions`
  N)sessionDurationdiagnosticInterfacez@Invalid option '{}' provided under 'spec.identityServiceOptions')parse_session_durationparse_diagnostic_interface%IdentityServiceIdentityServiceOptionsr   r   formatsetattr)identity_service_options_configr   supported_optionsidentity_service_options_protooptions        r   r   r   V   s    $ %,/7 $'#L#L#N /f&&
L6&>  &!&!#'FG 0 
('r   c                     |d   }t        |t              r|t        k  s	|t        kD  r-t	        j
                  dj                  t        t                    t        |dz        dz   S )Nr$   zS'spec.identityServiceOptions.sessionDuration' must be an integer between {} and {}.<   s)
isinstanceintSESSION_DURATION_MINSESSION_DURATION_MAXr   r   r)   str)_r+   session_durations      r   r&   r&   }   si    45FG	$c	*--	0	0


	$f%9;OP  
"	#c	))r   c                    |d   }t        |t              rd|vsd|vrt        j                  d      | j	                         }|D ]w  }|dk(  r|d   |_        |dk(  r=	 t        j                  j                  |d   j                         d      }|d   |_	        Ut        j                  dj                  |             |S # t        $ r t        dj                  |d               w xY w)a  Constructs an IdentityServiceDiagnosticInterface instance from the provided config `identity_service_options_config`.

  Args:
    msg: The gkehub message package
    identity_service_options_config: a map of non-protocol-related configuration
      options from the applied configuration.

  Returns:
    an instance of IdentityServiceDiagnosticInterface

  Raises:
     ValueError: if the value provided in `diagnosticInterface.expirationTime`
     is not RFC3339-compliant.
  r%   enabledexpirationTimezhRequired fields 'diagnosticInterface.enabled' and 'diagnosticInterface.expirationTime' must be provided.z%Y-%m-%dT%H:%M:%S%zz'{}' is invalid for the field 'diagnosticInterface.expirationTime'. Please, provide a valid date in the '%Y-%m-%dT%H:%M:%S%z' format.zPUnknown field '{}' found under 'spec.identityServiceOptions.diagnosticInterface')r2   dictr   r   "IdentityServiceDiagnosticInterfacer:   datetimestrptime__str__r;   
ValueErrorr)   )r   r+   diagnostic_interface_configdiagnostic_interface_protokeyr7   s         r   r'   r'      s/    !@! 0$
7	5	5	!<	<


	B   #EEG(c
i+F
, ( 
 	 
&&'(89AAC!
 5P5
"1 ??Evc{ / )6 
$#  
99?+,<=:
 	

s   ;C'C(c                 X    | d   }|d|vry |d   st        j                  d      |d   S )Nr    authenticationz>Must provide a valid configuration under 'spec.authentication'r!   r"   s     r   r   r      sI    	f	$	\%T1		


H  
	r   c                    | g S t        |       }|t        kD  r+dj                  |t              }t        j                  |      t
        t        t        t        t        d}ddh}g }| D ]  }|j                         D cg c]	  }||vs| }	}t        |	      dk7  rt        j                  d      |	d   }
|
|vr$t        j                  dj                  |
             ||
   ||      }|j                  |        |S c c}w )	a  Constructs a list of IdentityServiceMembershipSpec.IdentityServiceAuthMethod from the given auth methods config.

  Args:
    auth_methods_config: A list of providers from the applied configuration
    msg: The GKE Hub message package

  Returns:
    a list of
    IdentityServiceMembershipSpec.IdentityServiceAuthMethod

  Raises:
    exceptions.Error: if the provided config is invalid
  ziThe provided configuration contains {} identity providers. The maximum number that can be provided is {}.)oidcgoogleazureADsamlldapnameproxyr
   zIExactly one identity protocol can be configured per authentication methodr   zEUnsupported identity protocol [{}] found under 'spec.authentication'.)r   MAX_AUTH_PROVIDERSr)   r   r   provision_oidc_configprovision_google_configprovision_azuread_configprovision_saml_configprovision_ldap_configkeysappend)auth_methods_configr   auth_methods_counterr_msgsupported_protocolsauth_method_metaauth_methods_protoauth_method_configrD   	protocolsprotocolauth_methods               r   r   r      s@     I./,,	9f!34  

7
###')## g&/)..00C?O4O0   9~  |H**$$*F8$4  0%h/0BCHKk*! 0" 
!s   =	C>C>c                 6    d| vrt        j                  d      y)zValidate the basics of the parsed clientconfig yaml for AIS Hub Feature Spec.

  Args:
    clientconfig: The data field of the YamlConfigFile.
  r    zMissing required field 'spec'.Nr!   )r   s    r   r   r     s#     <


;
<<  r   c                     |j                         }d| vrt        j                  d      | d   |_        d| v r
| d   |_        d| v rt        | d   d      |_        |S )a  Provision FeatureSpec LdapConfig Server from the parsed yaml file.

  Args:
    ldap_server_config: YamlConfigFile, The ldap server data loaded from the
      yaml file given by the user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing server details of a
    single LDAP auth method for the IdentityServiceFeatureSpec.
  hostz4LDAP Authentication method must contain server host.connectionTypecertificateAuthorityDatazutf-8)IdentityServiceServerConfigr   r   rc   rd   bytesre   )ldap_server_configr   servers      r   provision_ldap_server_configrj     s     **,& %%


>  #6*&+ ++./?@F#55&+56'F# 
-r   c                 H   | t        j                  d      |j                         }d| v rc|j                         |_        | d   }|d   r|d   st        j                  d      |d   |j                  _        |d   |j                  _        |S t        j                  d      )a  Provision FeatureSpec LdapConfig ServiceAccount from the parsed yaml file.

  Args:
    ldap_service_account_config: YamlConfigFile, The ldap service account data
      loaded from the yaml file given by the user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing the service account
     details of a single LDAP auth method for the IdentityServiceFeatureSpec.
  z@LDAP Authentication method must contain Service Account details.simpleBindCredentialsdnpasswordzNLDAP Authentication method must contain non-empty Service Account credentials.zHUnknown service account type. Supported types are: simpleBindCredentials)r   r   #IdentityServiceServiceAccountConfig$IdentityServiceSimpleBindCredentialsrl   rm   rn   )ldap_service_account_configr   service_accountldap_simple_bind_credentialss       r   %provision_ldap_service_account_configrt   /  s     !(


J  ;;=/  ;;002 ) $?$  ).+J7  0L0O)), 	%Z0 ))2 P	 r   c                     |j                         }d| vrt        j                  d      | d   |_        d| v r
| d   |_        d| v r
| d   |_        d| v r
| d   |_        |S )a  Provision FeatureSpec LdapConfig User from the parsed yaml file.

  Args:
    ldap_user_config: YamlConfigFile, The ldap user data loaded from the yaml
      file given by the user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing the user details of a
    single LDAP auth method for the IdentityServiceFeatureSpec.
  baseDnz4LDAP Authentication method must contain user baseDn.loginAttributeidAttributefilter)IdentityServiceUserConfigr   r   rv   rw   rx   ry   )ldap_user_configr   users      r   provision_ldap_user_configr}   ^  s     
	&	&	($ %%


>  !*$+ ))*+;<D&&'6D!!"8,DK	+r   c                     |j                         }d| vrt        j                  d      | d   |_        d| v r
| d   |_        d| v r
| d   |_        |S )a  Provision FeatureSpec LdapConfig Group from the parsed yaml file.

  Args:
    ldap_group_config: YamlConfigFile, The ldap group data loaded from the yaml
      file given by the user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing the group details of
    a single LDAP auth method for the IdentityServiceFeatureSpec.
  rv   z5LDAP Authentication method must contain group baseDn.rx   ry   )IdentityServiceGroupConfigr   r   rv   rx   ry   )ldap_group_configr   groups      r   provision_ldap_group_configr     ss     
(
(
*% &&


?  #8,%, '')-8E""$X.EL	,r   c                    d| vrt        j                  d      |j                         }| d   |_        d| v r
| d   |_        | d   }d|vsd|vsd|vr)dj                  | d         }t        j                  |      |j                         |_        t        |d   |      |j                  _	        t        |d   |      |j                  _        t        |d   |      |j                  _        d	|v rt        |d	   |      |j                  _        |S )
a  Provision FeatureSpec LdapConfig from the parsed yaml file.

  Args:
    auth_method: YamlConfigFile, The data loaded from the yaml file given by the
      user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing a single
    LDAP auth method for the IdentityServiceFeatureSpec.
  rM   z-LDAP Authentication method must contain name.rN   rL   ri   r|   serviceAccountzPAuthentication method [{}] must contain server, user and serviceAccount details.r   )r   r   IdentityServiceAuthMethodrM   rN   r)   IdentityServiceLdapConfig
ldapConfigrj   ri   rt   r   r}   r|   r   r   )r`   r   auth_method_protoldap_configrY   s        r   rT   rT     sB    ;


J
KK335&v.)'2F#+ k!	{	"		,	3f[ !  

7
##!$!>!>!@(D(S)% ,K8H,I3O - 'A&3'#
 )DGc*  & 
r   c                 B   d| vrt        j                  d      |j                         }| d   |_        | d   }d|vsd|vrt        j                  d      |j	                         |_        |d   |j
                  _        |d   |j
                  _        t        |j
                  j                  | d          d| v r
| d   |_	        d|v r|d   |j
                  _
        d	|v r|d	   |j
                  _        d
|v r|d
   |j
                  _        d|v r|d   |j
                  _        d|v r|d   |j
                  _        |j
                  j                  s=|j
                  j                  r't        j                  dj                  | d               d|v r|d   |j
                  _        d|v r|d   |j
                  _        d|v r|d   |j
                  _        d|v r|d   |j
                  _        d|v r|d   |j
                  _        d|v r|d   |j
                  _        |S )a  Provision FeatureSpec OIDCConfig from the parsed yaml file.

  Args:
    auth_method: YamlConfigFile, The data loaded from the yaml file given by the
      user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing a single
      OIDC auth method for the IdentityServiceFeatureSpec.
  rM   z-OIDC Authentication method must contain name.rH   	issuerURIclientIDzBinput config file OIDC Config must contain issuerURI and clientID.rN   re   deployCloudConsoleProxyextraParamsgroupPrefixgroupsClaimzIgroupPrefix should be empty for method [{}] because groupsClaim is empty.kubectlRedirectURIscopes	userClaim
userPrefixclientSecretenableAccessToken)r   r   r   rM   IdentityServiceOidcConfig
oidcConfig	issuerUriclientIdvalidate_issuer_urirN   re   r   r   r   r   r)   kubectlRedirectUrir   r   r   r   r   )r`   r   r   oidc_configs       r   rP   rP     sw    ;


J
KK335&v.F#+ #z'D


L  "%!>!>!@+6{+C(*5j*A'"",,k&.A
 )'2  ;.<G"=  9 +-;F!<  8 k!/:=/I  ,k!/:=/I  ,k!/:=/I  , 
&
&
2
2

&
&
2
2


	&V,- 
 [(6A7  3 *5h*?  'K-8-E  *[ .9,.G  +{"0;N0K  -K'5@6  2 
r   c                    d| vrt        j                  d      |j                         }| d   |_        | d   }|j	                         |_        g d}|D cg c]  }||vr|
 }}|r7t        j                  dj                  | d   dj                  |                  |d   |j
                  _        |d   |j
                  _	        |d	   |j
                  _
        d
|v r|d
   |j
                  _        d|v r|d   |j
                  _        d|v r|d   |j
                  _        d|v r|d   |j
                  _        d|v r|j                  j                         |j
                  _        |d   j#                         D ]f  \  }}|j                  j                  j%                         }	||	_        ||	_        |j
                  j                   j*                  j-                  |	       h |S c c}w )a  Provision FeatureSpec SamlConfig from the parsed configuration file.

  Args:
    auth_method: YamlConfigFile, The data loaded from the yaml file given by the
      user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing a single SAML
    auth method for the IdentityServiceFeatureSpec.
  rM   z-SAML Authentication method must contain name.rK   )idpEntityIDidpSingleSignOnURIidpCertificateDataListzFThe following fields are not set for the authentication method {} : {}z, r   r   r   userAttributegroupsAttributer   r   attributeMapping)r   r   r   rM   IdentityServiceSamlConfig
samlConfigr)   joinidentityProviderIdidentityProviderSsoUriidentityProviderCertificatesr   r   r   r   AttributeMappingValuer   itemsAdditionalPropertyrD   valueadditionalPropertiesrV   )
r`   r   r   saml_configrequired_fields
field_nameunset_required_fieldsattribute_keyattribute_valueattribute_map_items
             r   rS   rS   *  s.    ;


J
KK335&v.F#+!$!>!>!@/ ('*	;	& '  
 


P	F#TYY/D%E	F  5@4N18C95 ?J?;
 #1<_1M  .+%3>4  0 [ .9,.G  +k!/:=/I  ,;&%%;;=   1 +6+eg+& 
'
'
=
=
P
P
R   -!0""33HHOO
+ 
as   G%c                 :   d| vrt        j                  d      |j                         }| d   |_        | d   }|j	                         |_        d| v r
| d   |_        d|vr't        j                  dj                  | d               |d   |j
                  _        |S )a  Provision FeatureSpec GoogleConfig from the parsed configuration file.

  Args:
    auth_method: YamlConfigFile, The data loaded from the yaml file given by the
      user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing a single Google
    auth method for the IdentityServiceFeatureSpec.
  rM   z/Google Authentication method must contain name.rI   rN   disablezAThe "disable" field is not set for the authentication method "{}")	r   r   r   rM   IdentityServiceGoogleConfiggoogleConfigrN   r)   r   )r`   r   r   google_configs       r   rQ   rQ   z  s     ;


L
MM335&v.h'-#&#B#B#D  )'2 m#


K	F#	$& & ,9+C  (	r   c                 .   d| vrt        j                  d      |j                         }| d   |_        |j	                         |_        d| v r
| d   |_        | d   }d|vsd|vsd|vr)dj                  | d         }t        j                  |      |d   |j
                  _        |d   |j
                  _	        |d   |j
                  _
        d	|v r|d	   |j
                  _        d
|v r|d
   |j
                  _        d|v r|d   |j
                  _        |S )a  Provision FeatureSpec AzureADConfig from the parsed yaml file.

  Args:
    auth_method: YamlConfigFile, The data loaded from the yaml file given by the
      user. YamlConfigFile is from
      googlecloudsdk.command_lib.anthos.common.file_parsers.
    msg: The gkehub messages package.

  Returns:
    member_config: A MemberConfig configuration containing a single
    Azure AD auth method for the IdentityServiceFeatureSpec.
  rM   z0AzureAD Authentication method must contain name.rN   rJ   r   r   tenantzQAuthentication method [{}] must contain clientID, kubectlRedirectURI, and tenant.r   r   groupFormat)r   r   r   rM   IdentityServiceAzureADConfigazureadConfigrN   r)   r   r   r   r   r   r   )r`   r   r   azuread_configrY   s        r   rR   rR     sU    ;


M
NN335&v.$'$D$D$F!)'2y). &	^	3		'	4f[ !  

7
##-;J-G!!*7E8!!4 ,:(+C!!( ~%3A4##0 N"0>{0K##-n$2@2O##/	r   c                 (   t         j                  j                  |       }|j                  dk7  r$t	        j
                  dj                  |            |j                  4d|j                  v r%t	        j
                  dj                  |d            yy)zValidates Issuer URI field of OIDC config.

  Args:
    issuer_uri: issuer uri to be validated
    auth_method_name: auth method name that has this field
  httpsz:issuerURI is invalid for method [{}]. Scheme is not https.Nz .well-known/openid-configurationzHissuerURI is invalid for method [{}]. issuerURI should not contain [{}].)urllib3util	parse_urlschemer   r   r)   path)
issuer_uriauth_method_nameurls      r   r   r     s     	z*#ZZ7


DKK	
 
 	XX@CHHL


	(*LM  Mr   )__doc__
__future__r   r   r   r>   googlecloudsdk.corer   r   rO   r4   r5   r   r   r   r&   r'   r   r   r   rj   rt   r}   r   rT   rP   rS   rQ   rR   r    r   r   <module>r      s    3 &  '  *      %P($(N
*7$t 2j=B,^D@5pOdM` F3lr   