
    +3                     V   d Z ddlmZ ddlmZ ddlmZ ddlZddl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Z G d dej*                        Z G d de      Z G d de      Zd ZddZd Z G d de      Z G d dej:                        Zy)z%Utilities for the iamcredentials API.    )absolute_import)division)unicode_literalsN
exceptions)http_wrapper)apis_internal)
properties)	resources)	transport)clientz&https://iamcredentials.googleapis.com/c                       e Zd ZdZy)Errorz*Exception that are defined by this module.N__name__
__module____qualname____doc__     1lib/googlecloudsdk/api_lib/iamcredentials/util.pyr   r   '   s    2r   r   c                       e Zd ZdZy)InvalidImpersonationAccountz1Exception when the service account id is invalid.Nr   r   r   r   r   r   +   s    9r   r   c                       e Zd ZdZy)&ImpersonatedCredGoogleAuthRefreshErrorzAException for google auth impersonated credentials refresh error.Nr   r   r   r   r   r   /   s    Ir   r   c                 ~   ddl m} t        j                  j	                  | dd| d      }|j                  dt        j                  d      }t        j                  d	d
|      }	 |j                  j                  |j                  j                  |j                         |j                  j                  |                  }|S # t         j"                  $ r7}t%        j&                  |dj)                  |j*                  |             d}~wt         j,                  $ r}t%        j&                  |      d}~ww xY w)z8Generates an access token for the given service account.r   
transportsiamcredentials.serviceAccounts-
projectsIdserviceAccountsId
collectionparamsFenable_resource_quotaresponse_encodingallow_account_impersonationiamcredentialsv1http_client)scope)namegenerateAccessTokenRequestzError {code} (Forbidden) - failed to impersonate [{service_acc}]. Make sure the account that's trying to impersonate it has access to the service account itself and the "roles/iam.serviceAccountTokenCreator" role.)codeservice_accerror_formatN)googlecloudsdk.core.credentialsr   r   REGISTRYParseGetApitoolsTransportr   ENCODINGr	   _GetClientInstanceprojects_serviceAccountsGenerateAccessTokenMESSAGES_MODULE?IamcredentialsProjectsServiceAccountsGenerateAccessTokenRequestRelativeNameGenerateAccessTokenRequestapitools_exceptionsHttpForbiddenErrorr   HttpExceptionformatstatus_code	HttpError)service_account_idscopesr   service_account_refr.   
iam_clientresponsees           r   r=   r=   3   sC    9!**00%E6HI 1 K //!!**"' 0 )+
 //+7*&22FF""	H	H$113'1'A'A''f'5 
I 

H O		/	/ N

"
"	 $Vmm9K $ MN N 
	&	& &

"
"1
%%&s%   'AC D<2DD<"D77D<c           	         ddl m} t        j                  j	                  | dd| d      }|j                  dt        j                  d      }t        j                  d	d
|      }|j                  j                  |j                  j                  |j                         |j                  j                  ||                  }|j                   S )z4Generates an id token for the given service account.r   r   r   r    r!   r$   Fr'   r+   r,   r-   )audienceincludeEmail)r0   generateIdTokenRequest)r6   r   r   r7   r8   r9   r   r:   r	   r;   r<   GenerateIdTokenr>   ;IamcredentialsProjectsServiceAccountsGenerateIdTokenRequestr@   GenerateIdTokenRequesttoken)rH   rO   include_emailr   rJ   r.   rK   rL   s           r   rR   rR   [   s     9!**00%E6HI 1 K //!!**"' 0 )+
 //+7* 00@@  BB"//1!+!;!;!!8-!P C ( 
r   c                     t         j                  j                  j                  j	                         r2t         j                  j                  j                  j                         S t         j                  j                  j                  } | j                         | j                  k7  r$t        j                  d| j                               S t        S )a  Returns the effective IAM endpoint.

  (1) If the [api_endpoint_overrides/iamcredentials] property is explicitly set,
  return the property value.
  (2) Otherwise if [core/universe_domain] value is not default, return
  "https://iamcredentials.{universe_domain_value}/".
  (3) Otherise return "https://iamcredentials.googleapis.com/"

  Returns:
    str: The effective IAM endpoint.
  zgoogleapis.com)r
   VALUESapi_endpoint_overridesr+   IsExplicitlySetGetcoreuniverse_domaindefaultIAM_ENDPOINT_GDUreplace)universe_domain_propertys    r   GetEffectiveIamEndpointrb   w   s     --<<LLN33BBFFHH'..33CC!!#'?'G'GG##2668  
r   c                   H    e Zd ZdZd Zd Zd Zd Zed        Z	ed        Z
y)	 ImpersonationAccessTokenProviderzzA token provider for service account elevation.

  This supports the interface required by the core/credentials module.
  c                 |    d|v rt        d      t        ||      }t        ||j                  |j                  |      S )N,zMore than one service accounts were specified, which is not supported. If being set, please unset the auth/disable_load_google_auth property and retry.)r   r=   ImpersonationCredentialsaccessToken
expireTime)selfrH   rI   rL   s       r   GetElevationAccessTokenz8ImpersonationAccessTokenProvider.GetElevationAccessToken   sP    
  '>? ? ##5v>H#H00(2E2EvO Or   c                     t        |||      S N)rR   )rj   rH   rO   rV   s       r   GetElevationIdTokenz4ImpersonationAccessTokenProvider.GetElevationIdToken   s    -xGGr   c                    ddl m} ddl m} ddlm} |j                         }|j                  |       |j                  ||||      }	| j                          	 |	j                  |       |	S # |j                  $ r}
dj                  |      }d}	 t        j                  |
j                  d	         }|d
z   |d   d   z   |d   d<   t        j                  d|d   d   it        j                   |      d      }t"        j$                  j'                  |      }n# t(        $ r Y nw xY w|rt        j*                  |d      t-        |      d}
~
ww xY w)zCCreates a fresh impersonation credential using google-auth library.r   r   impersonated_credentialsrequests)source_credentialstarget_principaltarget_scopes	delegateszFailed to impersonate [{service_acc}]. Make sure the account that's trying to impersonate it has access to the service account itself and the "roles/iam.serviceAccountTokenCreator" role.)r3   N    errormessagestatusr2   )infocontentrequest_urlz{message} {details?
{?}}r4   )google.authr   rq   googlecloudsdk.corers   GoogleAuthRequestrefreshCredentialsPerformIamEndpointsOverrideRefreshErrorrE   jsonloadsargsr   ResponsedumpsrB   rG   FromResponse	ExceptionrD   r   )rj   rt   ru   rw   rI   google_auth_exceptions$google_auth_impersonated_credentialscore_requestsrequest_clientcredrM   original_message
http_errorr~   http_responses                  r   !GetElevationAccessTokenGoogleAuthzBImpersonationAccessTokenProvider.GetElevationAccessTokenGoogleAuth   s    A\= #446N ~./;;-)	 < D 	$$&-E
ll>"\ K[ ".. +EBBH&* CI C  j **QVVAY' s"WW%5i%@@ 	#
 %--GG,V45JJw'

 )22??N
  
&&%@
 	

 33CDDW+Es=   A- -E<EBDE	D&#E%D&&'EEc                     ddl m} ddlm} |j	                  |||      }|j                         }| j                          |j                  |       |S )z=Creates an ID token credentials for impersonated credentials.r   rp   rr   )target_audiencerV   )r   rq   r   rs   IDTokenCredentialsr   r   r   )rj   %google_auth_impersonation_credentialsrO   rV   r   r   r   r   s           r   GetElevationIdTokenGoogleAuthz>ImpersonationAccessTokenProvider.GetElevationIdTokenGoogleAuth   sW     ]=/BB- # C D
 #446N$$&LL Kr   c                 ^    ddl m} t        |t              xs t        ||j                        S )Nr   rp   )r   rq   
isinstancerg   r   )clsr   r   s      r   IsImpersonationCredentialz:ImpersonationAccessTokenProvider.IsImpersonationCredential   s0     ]d45 2>>: r   c                    ddl m} t               }|j                  j	                  t
        |      |_        |j                  j	                  t
        |      |_        |j                  j	                  t
        |      |_        y)a.  Perform IAM endpoint override if needed.

    We will override IAM generateAccessToken, signBlob, and generateIdToken
    endpoint under the following conditions.
    (1) If the [api_endpoint_overrides/iamcredentials] property is explicitly
    set, we replace "https://iamcredentials.googleapis.com/" with the given
    property value in these endpoints.
    (2) If the property above is not set, and the [core/universe_domain] value
    is not default, we replace "googleapis.com" with the [core/universe_domain]
    property value in these endpoints.
    r   )iamN)r   r   rb   _IAM_ENDPOINTr`   r_   _IAM_SIGN_ENDPOINT_IAM_IDTOKEN_ENDPOINT)r   google_auth_iameffective_iam_endpoints      r   r   z<ImpersonationAccessTokenProvider.PerformIamEndpointsOverride  s|     3 56%%--"	
 ! 	**22"	
 & 	--55"	
 )r   N)r   r   r   r   rk   rn   r   r   classmethodr   r   r   r   r   rd   rd      sG    
OHGR"   " "r   rd   c                   2     e Zd ZdZdZ fdZd Zd Z xZS )rg   zNImplementation of a credential that refreshes using the iamcredentials API.
  z%Y-%m-%dT%H:%M:%SZc           
      l    || _         | j                  |      }t        t        |   |d d d |d d |       y )N)rI   )_service_account_id_ConvertExpiryTimesuperrg   __init__)rj   rH   access_tokentoken_expiryrI   	__class__s        r   r   z!ImpersonationCredentials.__init__/  sB    1D**<8L	
"D2dD$dD 3 Qr   c                     t        | j                  t        | j                              }|j                  | _        | j                  |j                        | _        y rm   )	r=   r   listrI   rh   r   r   ri   r   )rj   httprL   s      r   _refreshz!ImpersonationCredentials._refresh5  sF     #4#;#;T$++=NOH ,,D//0C0CDDr   c                 ^    t         j                   j                  |t        j                        S rm   )datetimestrptimerg   _EXPIRY_FORMAT)rj   values     r   r   z+ImpersonationCredentials._ConvertExpiryTime<  s(    %%e&>&M&MO Or   )	r   r   r   r   r   r   r   r   __classcell__)r   s   @r   rg   rg   *  s    '.QEOr   rg   )F)r   
__future__r   r   r   r   r   apitools.base.pyr   rB   r   googlecloudsdk.api_lib.utilr	   r   core_exceptionsr
   r   r   oauth2clientr   r_   r   r   r   r=   rR   rb   objectrd   OAuth2Credentialsrg   r   r   r   <module>r      s     , &  '   > ) 5 2 = * ) )  < 3O!! 3:% :JU J%&P8.Yv YxOv77 Or   