o
    ˷eK                     @   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#   P/var/www/ideatree/venv/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{0}/projects/{1})apphttp_clientr   requestsRequestr?   ID_TOOLKIT_URLformat
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rOtd|j |j }t| j||S )zPInitializes a signing provider by following the go/firebase-admin-sign protocol.serviceAccountIdzMetadata-FlavorGoogle)urlheaders   z2Failed to contact the local metadata service: {0}.)r   is_emulatedr1   rD   rJ   
credentialget_credential
isinstancegoogleoauth2r@   Credentialsr<   optionsgetrA   r?   r   SigningMETADATA_SERVICE_URLstatus
ValueErrorrO   datadecode)r%   r;   r@   respr#   r#   r&   _init_signing_providerx   s"   



z%TokenGenerator._init_signing_providerc              
   C   sL   | j s#z	|  | _ W | j S  ty" } z
d}t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-tokenszFailed to determine service account: {0}. Make sure to initialize the SDK with service account credentials or specify a service account ID with iam.serviceAccounts.signBlob permission. Please refer to {1} for more details on creating custom tokens.N)rR   rj   	Exceptionrf   rO   )r%   errorrW   r#   r#   r&   signing_provider   s   zTokenGenerator.signing_providerc              
   C   s&  |dur5t |tstdt| t@ }|r5t|dkr)dd|}t|dd|}t||rBt |t	rBt|dkrFtd| j
}tt }|j|jt|||t d	}|rb||d
< |durj||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 {0} are reserved and cannot be specified.z, z8Developer claim {0} 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. {0})r]   dictrf   setkeysRESERVED_CLAIMSlenrO   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   sR   



z"TokenGenerator.create_custom_tokenc              
   C   s  t |tr
|dn|}t |tr|std|t |tjr&t|	 }t |t
s0t |ts7td||tk rCtd|t|tkrOtd|td| j}||d}z| jjd||d	\}}W n tjjyz } zt|d
}~ww |r|dstjd|d|dS )z4Creates a session cookie from the provided ID token.utf-8zDIllegal ID token provided: {0}. ID token must be a non-empty string.zIllegal expiry duration: {0}.zDIllegal expiry duration: {0}. Duration must be at least {1} seconds.zCIllegal expiry duration: {0}. Duration must be at most {1} seconds.z{0}:createSessionCookie)idTokenvalidDurationpost)jsonNsessionCookiez Failed to create session cookie.)http_response)r]   bytesrh   ry   rf   rO   datetime	timedeltarz   total_secondsbool#MIN_SESSION_COOKIE_DURATION_SECONDS#MAX_SESSION_COOKIE_DURATION_SECONDSrQ   rK   body_and_responserL   r   RequestExceptionr   handle_auth_backend_errorrb   UnexpectedResponseError)r%   id_token
expires_inrW   r   body	http_resprl   r#   r#   r&   create_session_cookie   sB   

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   rX   timeout)r   r   )r%   rW   r   r   rX   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                   @   (   e Zd ZdZdd Zdd Z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)rP   
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?   _JWTVerifierrP   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__c                 C      | j || jS r"   )r   verifyr?   )r%   r   r#   r#   r&   verify_id_token$     zTokenVerifier.verify_id_tokenc                 C   r   r"   )r   r   r?   )r%   cookier#   r#   r&   verify_session_cookie'  r   z#TokenVerifier.verify_session_cookieN)r-   r.   r/   rE   r'   r   r   r#   r#   r#   r&   r     s
    r   c                   @   r   )	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 )NrP   r   r   r   r   r   r   aeiouzan {0}za {0}r   r   )poprP   r   r   rW   r   r   lowerrO   articled_short_name_invalid_token_error_expired_token_error)r%   r   r#   r#   r&   r'   .  s   z_JWTVerifier.__init__c              
   C   s  t |tr
|dn|}t |tr|std| j|| js'td| j| 	|\}}|
d}|
d}|
d}| j| j }d| j}	d| j| j}
t }d	}|tkrdd
| j| j}n|s|
ds|
ddkr|
ddkrd|
di v rd| j| j}ndd| j}n]|s|
ddkrd| j|
d|
}nH|| jkrd| j| j||	|
}n7||krd| j|||	|
}n(|d	u st |tsd| j|
}n|sd| j|
}nt|dkrd| j|
}|r| |z|r|}ntjjj||| j| jd}|d |d< |W S  tjjjy( } ztt||dd	}~w tyM } 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 {0} provided: {1}. {0} must be a non-empty string.a  Failed to ascertain project ID from the credential or the environment. Project ID is required to call {0}. 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   r   r   zlMake sure the {0} comes from the same Firebase project as the service account used to authenticate this SDK.z+See {0} for details on how to retrieve {1}.Nz.{0} expects {1}, but was given a custom token.kidr7   HS256vr   ro   dz5{0} expects {1}, but was given a legacy custom token.z Firebase {0} has no "kid" claim.r   zIFirebase {0} has incorrect algorithm. Expected "RS256" but got "{1}". {2}zXFirebase {0} has incorrect "aud" (audience) claim. Expected "{1}" but got "{2}". {3} {4}zVFirebase {0} has incorrect "iss" (issuer) claim. Expected "{1}" but got "{2}". {3} {4}z.Firebase {0} has no "sub" (subject) claim. {1}z;Firebase {0} has an empty string "sub" (subject) claim. {1}rn   zHFirebase {0} has a "sub" (subject) claim longer than 128 characters. {1})r?   audience	certs_urlcausezToken expired)r]   ry   r~   r   rf   rO   r   rP   r   _decode_unverifiedrb   r   rW   r   rZ   r|   r   rw   r   r^   r_   r   verify_tokenr   r   r   r   CertificateFetchErrorr   )r%   tokenr?   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_unverifiedN)r-   r.   r/   rE   r'   r   r   r#   r#   r#   r&   r   +  s
    Zr   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'        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'     r   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   
" 
t