o
     iK                     @   s  d Z ddlZddl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
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
ZdZdZdZeejdd Zeejdd Zeejdd ZdZeg dZdZdZ dZ!dZ"G dd dej#j$j%Z&G dd dZ'G dd dZ(G d d! d!e	j)Z*G d"d# d#Z+G d$d% d%Z,G d&d' d'ej-Z.G d(d) d)ej-Z/G d*d+ d+ej0Z1G d,d- d-ej0Z2G d.d/ d/ej3Z4G d0d1 d1e4Z5G d2d3 d3e4Z6dS )4z1Firebase token minting and validation sub module.    N)credentials)iam)jwt)	transport)
exceptions)_auth_utils)_http_clientzhttps://securetoken.google.com/zXhttps://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.comz$https://session.firebase.google.com/zEhttps://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys   )minutes   )days   )hourszYhttps://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit)acramrat_hashaud	auth_timeazpcnfc_hashexpfirebaseiatissjtinbfnoncesubzZhttp://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/emailRS256nonez"firebase-auth-emulator@example.comc                   @   s    e Zd ZdZdd Zdd ZdS )_EmulatedSignerNc                 C   s   d S N selfr#   r#   y/var/www/snowflake_co_dev_github/snow_flake_back_end_deploy/env/lib/python3.10/site-packages/firebase_admin/_token_gen.py__init__B      z_EmulatedSigner.__init__c                 C   s   dS )N    r#   r%   messager#   r#   r&   signE   r(   z_EmulatedSigner.sign)__name__
__module____qualname__key_idr'   r,   r#   r#   r#   r&   r!   ?   s    r!   c                   @   sd   e Zd ZdZefddZedd Zedd Zedd	 Z	e
d
d Ze
dd Ze
dd ZdS )_SigningProviderz2Stores a reference to a google.auth.crypto.Signer.c                 C   s   || _ || _|| _d S r"   )_signer_signer_email_alg)r%   signersigner_emailalgr#   r#   r&   r'   L   s   
z_SigningProvider.__init__c                 C      | j S r"   )r2   r$   r#   r#   r&   r5   Q      z_SigningProvider.signerc                 C   r8   r"   )r3   r$   r#   r#   r&   r6   U   r9   z_SigningProvider.signer_emailc                 C   r8   r"   )r4   r$   r#   r#   r&   r7   Y   r9   z_SigningProvider.algc                 C   s   t |j|jS r"   )r1   r5   r6   )clsgoogle_credr#   r#   r&   from_credential]      z _SigningProvider.from_credentialc                 C   s   t |||}t||S r"   )r   Signerr1   )r:   requestr;   service_accountr5   r#   r#   r&   from_iama   s   
z_SigningProvider.from_iamc                 C   s   t t ttS r"   )r1   r!   AUTH_EMULATOR_EMAILALGORITHM_NONE)r:   r#   r#   r&   for_emulatorf   r=   z_SigningProvider.for_emulatorN)r-   r.   r/   __doc__ALGORITHM_RS256r'   propertyr5   r6   r7   classmethodr<   rA   rD   r#   r#   r#   r&   r1   I   s    




r1   c                   @   sD   e Zd ZdZdZdddZdd Zedd	 Zdd
dZ	dd Z
dS )TokenGeneratorz,Generates custom tokens and session cookies.z)https://identitytoolkit.googleapis.com/v1Nc                 C   s>   || _ || _tj | _|p| j}| d|j | _d | _	d S )Nz
/projects/)
apphttp_clientr   requestsRequestr?   ID_TOOLKIT_URL
project_idbase_url_signing_provider)r%   rJ   rK   url_override
url_prefixr#   r#   r&   r'   p   s   

zTokenGenerator.__init__c                 C   s   t  rt S | jj }t|tj	j
jrt|S | jjd}|r,t| j||S t|tjr7t|S | jtddid}|jdkrPtd|j  d|j }t| j||S )zPInitializes a signing provider by following the go/firebase-admin-sign protocol.serviceAccountIdzMetadata-FlavorGoogle)urlheaders   z.Failed to contact the local metadata service: .)r   is_emulatedr1   rD   rJ   
credentialget_credential
isinstancegoogleoauth2r@   Credentialsr<   optionsgetrA   r?   r   SigningMETADATA_SERVICE_URLstatus
ValueErrordatadecode)r%   r;   r@   respr#   r#   r&   _init_signing_providerx   s"   



z%TokenGenerator._init_signing_providerc              
   C   sT   | j s'z	|  | _ W | j S  ty& } zd}td| d| d|d}~ww | j S )z@Initializes and returns the SigningProvider instance to be used.z@https://firebase.google.com/docs/auth/admin/create-custom-tokensz%Failed to determine service account: z. Make sure to initialize the SDK with service account credentials or specify a service account ID with iam.serviceAccounts.signBlob permission. Please refer to z, for more details on creating custom tokens.N)rQ   rj   	Exceptionrf   )r%   errorrV   r#   r#   r&   signing_provider   s    zTokenGenerator.signing_providerc              
   C   s,  |dur7t |tstdt| t@ }|r7t|dkr*dd| d}t|dd| d}t||rDt |trDt|d	krHtd
| j	}t
t }|j|jt|||t d}|rd||d< |durl||d< d|ji}	z
tj|j||	dW S  tjjjy }
 zd|
 }t||
|
d}
~
ww )z.Builds and signs a Firebase custom auth token.Nz%developer_claims must be a dictionaryr   zDeveloper claims z, z& are reserved and cannot be specified.zDeveloper claim z% is reserved and cannot be specified.   z2uid must be a string between 1 and 128 characters.)r   r   r   uidr   r   	tenant_idclaimsr7   )headerzFailed to sign custom token. )r]   dictrf   setkeysRESERVED_CLAIMSlenjoinstrrm   inttimer6   FIREBASE_AUDIENCEMAX_TOKEN_LIFETIME_SECONDSr7   r   encoder5   r^   authr   TransportErrorTokenSignError)r%   ro   developer_claimsrp   disallowed_keyserror_messagerm   nowpayloadrr   rl   msgr#   r#   r&   create_custom_token   sF   


z"TokenGenerator.create_custom_tokenc              
   C   s,  t |tr
|dn|}t |tr|std| dt |tjr't| }t |t	s1t |ts9td| d|t
k rHtd| dt
 d|tkrWtd| dt d| j d	}||d
}z| jjd||d\}}W n tjjy } zt|d}~ww |r|dstjd|d|dS )z4Creates a session cookie from the provided ID token.utf-8zIllegal ID token provided: z&. ID token must be a non-empty string.zIllegal expiry duration: rY   z. Duration must be at least z	 seconds.z. Duration must be at most z:createSessionCookie)idTokenvalidDurationpost)jsonNsessionCookiez Failed to create session cookie.)http_response)r]   bytesrh   ry   rf   datetime	timedeltarz   total_secondsbool#MIN_SESSION_COOKIE_DURATION_SECONDS#MAX_SESSION_COOKIE_DURATION_SECONDSrP   rK   body_and_responserL   r   RequestExceptionr   handle_auth_backend_errorrb   UnexpectedResponseError)r%   id_token
expires_inrV   r   body	http_resprl   r#   r#   r&   create_session_cookie   sH   


z$TokenGenerator.create_session_cookier"   )NN)r-   r.   r/   rE   rN   r'   rj   rG   rm   r   r   r#   r#   r#   r&   rI   k   s    


-rI   c                   @   s<   e Zd ZdZdddZedd Zedd Zdd
dZdS )CertificateFetchRequestzyA google-auth transport that supports HTTP cache-control.

    Also injects a timeout to each outgoing HTTP request.
    Nc                 C   s*   t t | _tj| j| _|| _	d S r"   )
cachecontrolCacheControlrL   Session_sessionr   rM   session	_delegate_timeout_seconds)r%   timeout_secondsr#   r#   r&   r'      s   
z CertificateFetchRequest.__init__c                 C   r8   r"   )r   r$   r#   r#   r&   r      r9   zCertificateFetchRequest.sessionc                 C   r8   r"   )r   r$   r#   r#   r&   r     r9   z'CertificateFetchRequest.timeout_secondsGETc                 K   s&   |p| j }| j|f||||d|S )N)methodr   rW   timeout)r   r   )r%   rV   r   r   rW   r   kwargsr#   r#   r&   __call__  s   
z CertificateFetchRequest.__call__r"   )r   NNN)	r-   r.   r/   rE   r'   rG   r   r   r   r#   r#   r#   r&   r      s    


r   c                   @   s,   e Zd ZdZdd Zd
ddZd
ddZd	S )TokenVerifierz'Verifies ID tokens and session cookies.c              
   C   sX   |j dtj}t|| _t|jdddtt	t
jtd| _t|jdddttttd| _d S )NhttpTimeoutzID tokenzverify_id_token()z<https://firebase.google.com/docs/auth/admin/verify-id-tokens)rO   
short_name	operationdoc_urlcert_urlissuerinvalid_token_errorexpired_token_errorzsession cookiezverify_session_cookie())ra   rb   r   DEFAULT_TIMEOUT_SECONDSr   r?   _JWTVerifierrO   ID_TOKEN_CERT_URIID_TOKEN_ISSUER_PREFIXr   InvalidIdTokenErrorExpiredIdTokenErrorid_token_verifierCOOKIE_CERT_URICOOKIE_ISSUER_PREFIXInvalidSessionCookieErrorExpiredSessionCookieErrorcookie_verifier)r%   rJ   r   r#   r#   r&   r'     s(   
zTokenVerifier.__init__r   c                 C      | j || j|S r"   )r   verifyr?   )r%   r   clock_skew_secondsr#   r#   r&   verify_id_token$     zTokenVerifier.verify_id_tokenc                 C   r   r"   )r   r   r?   )r%   cookier   r#   r#   r&   verify_session_cookie'  r   z#TokenVerifier.verify_session_cookieNr   )r-   r.   r/   rE   r'   r   r   r#   r#   r#   r&   r     s
    
r   c                   @   s*   e Zd ZdZdd Zd
ddZdd Zd	S )r   z6Verifies Firebase JWTs (ID tokens or session cookies).c                 K   s   | d| _| d| _| d| _| d| _| d| _| d| _| jd  dv r5d	| j | _nd
| j | _| d| _	| d| _
d S )NrO   r   r   r   r   r   r   aeiouzan za r   r   )poprO   r   r   rV   r   r   lowerarticled_short_name_invalid_token_error_expired_token_error)r%   r   r#   r#   r&   r'   .  s   z_JWTVerifier.__init__r   c              
   C   s"  t |tr
|dn|}t |tr|s#td| j d| d| j d| js/td| j d|dk s7|d	kr?td
| d| |\}}|	d}|	d}|	d}| j
| j }	d| j d}
d| j d| j d}t }d}|tkr| j d| j d}n|s|	ds|	ddkr|	ddkrd|	di v r| j d| j d}nd| j d}n{|s|	dd krd| j d!|	d d"| }nb|| jkrd| j d#| j d$| d"|
 d%| 
}nI||	krd| j d&|	 d$| d"|
 d%| 
}n2|du st |tsd| j d'| }n|sd| j d(| }nt|d)kr-d| j d*| }|r5| |z|r<|}ntjjj||| j| j|d+}|d |d< |W S  tjjjyk } z	tt||d,|d}~w ty } zd-t|v r| jt||d,| jt||d,d}~ww ).z5Verifies the signature and data for the provided JWT.r   zIllegal z provided: z. z must be a non-empty string.zfFailed to ascertain project ID from the credential or the environment. Project ID is required to call z. Initialize the app with a credentials.Certificate or set your Firebase project ID as an app option. Alternatively set the GOOGLE_CLOUD_PROJECT environment variable.r   <   z"Illegal clock_skew_seconds value: z&. Must be between 0 and 60, inclusive.r   r   r   zMake sure the z[ comes from the same Firebase project as the service account used to authenticate this SDK.zSee z  for details on how to retrieve rY   Nz	 expects z, but was given a custom token.kidr7   HS256vro   dz&, but was given a legacy custom token.z	Firebase z has no "kid" claim.r   z4 has incorrect algorithm. Expected "RS256" but got "z". z1 has incorrect "aud" (audience) claim. Expected "z" but got " z/ has incorrect "iss" (issuer) claim. Expected "z has no "sub" (subject) claim. z, has an empty string "sub" (subject) claim. rn   z9 has a "sub" (subject) claim longer than 128 characters. )r?   audience	certs_urlclock_skew_in_secondscausezToken expired)r]   ry   r~   r   rf   r   rO   r   _decode_unverifiedrb   r   rV   r   rZ   r|   r   rw   r   r^   r_   r   verify_tokenr   r   r   r   CertificateFetchErrorr   )r%   tokenr?   r   rr   r   r   r   subjectexpected_issuerproject_id_match_msgverify_id_token_msgemulatedr   verified_claimsrl   r#   r#   r&   r   <  s   










z_JWTVerifier.verifyc              
   C   sN   zt |}t j|dd}||fW S  ty& } z	| jt||dd }~ww )NF)r   r   )r   decode_headerrh   rf   r   ry   )r%   r   rr   r   rl   r#   r#   r&   r     s   

z_JWTVerifier._decode_unverifiedNr   )r-   r.   r/   rE   r'   r   r   r#   r#   r#   r&   r   +  s
    
_r   c                   @      e Zd ZdZdd ZdS )r   z7Unexpected error while signing a Firebase custom token.c                 C      t j| || d S r"   r   UnknownErrorr'   r%   r+   r   r#   r#   r&   r'        zTokenSignError.__init__Nr-   r.   r/   rE   r'   r#   r#   r#   r&   r         r   c                   @   r   )r   zHFailed to fetch some public key certificates required to verify a token.c                 C   r   r"   r   r   r#   r#   r&   r'     r   zCertificateFetchError.__init__Nr   r#   r#   r#   r&   r     r   r   c                   @   r   )r   z!The provided ID token is expired.c                 C   r   r"   r   r   r'   r   r#   r#   r&   r'     r   zExpiredIdTokenError.__init__Nr   r#   r#   r#   r&   r     r   r   c                   @   r   )RevokedIdTokenErrorz'The provided ID token has been revoked.c                 C   s   t j| | d S r"   r   r*   r#   r#   r&   r'     r   zRevokedIdTokenError.__init__Nr   r#   r#   r#   r&   r     r   r   c                   @   s   e Zd ZdZdddZdS )r   z;The provided string is not a valid Firebase session cookie.Nc                 C   r   r"   )r   InvalidArgumentErrorr'   r   r#   r#   r&   r'     r   z"InvalidSessionCookieError.__init__r"   r   r#   r#   r#   r&   r     s    r   c                   @   r   )r   z'The provided session cookie is expired.c                 C   s   t | || d S r"   r   r'   r   r#   r#   r&   r'     r   z"ExpiredSessionCookieError.__init__Nr   r#   r#   r#   r&   r     r   r   c                   @   r   )RevokedSessionCookieErrorz-The provided session cookie has been revoked.c                 C   s   t | | d S r"   r   r*   r#   r#   r&   r'     s   z"RevokedSessionCookieError.__init__Nr   r#   r#   r#   r&   r     r   r   )7rE   r   r{   r   rL   google.authr   r   r   r   google.auth.exceptionsr^   google.oauth2.id_tokengoogle.oauth2.service_accountfirebase_adminr   r   r   r   r   r   r   rz   r   r   r   r   r}   r|   rt   rv   rd   rF   rC   rB   r   cryptr>   r!   r1   rI   rM   r   r   r   r   r   r   r   r   r   r   r   r   r   r#   r#   r#   r&   <module>   sT   
" 
y