o
    ØRWj‰1  ã                   @  s  d dl mZ d dlZd dlZd dlmZmZmZmZ d dl	m
Z
 d dlmZmZ d dlZddlmZmZmZ ddlmZ d	Zd
ZdZdddœZG dd„ deƒZG dd„ deƒZ	d1d2dd„Z	d3dddddddœd4d(d)„Z	*d5ddd+œd6d-d.„ZG d/d0„ d0ƒZdS )7é    )ÚannotationsN)ÚAnyÚCallableÚ	TypedDictÚcast)ÚPath)ÚLiteralÚNotRequiredé   )Ú
OAuthErrorÚOpenAIErrorÚSubjectTokenProviderError)Ú	to_threadz/urn:ietf:params:oauth:grant-type:token-exchangez#https://auth.openai.com/oauth/tokeni°  z$urn:ietf:params:oauth:token-type:jwtz)urn:ietf:params:oauth:token-type:id_token)ÚjwtÚidc                   @  s   e Zd ZU ded< ded< dS )ÚSubjectTokenProviderzLiteral['jwt', 'id']Ú
token_typezCallable[[], str]Ú	get_tokenN)Ú__name__Ú
__module__Ú__qualname__Ú__annotations__© r   r   úd/home/esfera/Documents/content_generation/venv/lib/python3.10/site-packages/openai/auth/_workload.pyr      s   
 r   c                   @  s8   e Zd ZU dZded< 	 ded< 	 ded< 	 ded< d	S )
ÚWorkloadIdentityz(Identity provider resource id in WIFAPI.ÚstrÚidentity_provider_idÚservice_account_idr   ÚproviderzNotRequired[float]Úrefresh_buffer_secondsN)r   r   r   Ú__doc__r   r   r   r   r   r      s   
 r   ú3/var/run/secrets/kubernetes.io/serviceaccount/tokenÚtoken_file_pathú
str | PathÚreturnc                   s   d‡ fdd„}d|dœS )	aK  
    Get a subject token provider for Kubernetes clusters with Workload Identity configured.

    Cloud providers typically mount the subject token as a file in the container.

    Args:
        token_file_path: path to the mounted service account token file. Defaults to `/var/run/secrets/kubernetes.io/serviceaccount/token`.
    r$   r   c               
     s†   z+t ˆ dƒ�} |  ¡  ¡ }|stdˆ › d�ƒ‚|W  d   ƒ W S 1 s$w   Y  W d S  tyB } ztdˆ › d|› �ƒ|‚d }~ww )NÚrzThe token file at z
 is empty.z!Failed to read the token file at z: )ÚopenÚreadÚstripr   Ú	Exception)ÚfÚtokenÚe©r"   r   r   r   8   s   (ü€ÿz5k8s_service_account_token_provider.<locals>.get_tokenr   ©r   r   N©r$   r   r   )r"   r   r   r-   r   Ú"k8s_service_account_token_provider,   s   

r0   úhttps://management.azure.com/z
2018-02-01ç      $@)Ú	object_idÚ	client_idÚ
msi_res_idÚapi_versionÚtimeoutÚhttp_clientÚresourcer   r3   ú
str | Noner4   r5   r6   r7   Úfloatr8   úhttpx.Client | Nonec                  s$   d‡ ‡‡‡‡‡‡fdd„}d|dœS )	aŽ  
    Get a subject token provider for Azure Managed Identities.

    See: https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http

    Args:
        resource: the resource URI to request a token for. Defaults to `https://management.azure.com/` (Azure Resource Manager).
        object_id: the object ID of the managed identity to use, when multiple are assigned.
        client_id: the client ID of the managed identity to use, when multiple are assigned.
        msi_res_id: the ARM resource ID of the managed identity to use, when multiple are assigned.
        api_version: the Azure IMDS API version. Defaults to `2018-02-01`.
        timeout: the request timeout in seconds. Defaults to 10.0.
        http_client: optional httpx.Client instance to use for requests. If not provided, a new client will be created for each request.
    r$   r   c               
     s  zrd} ˆ ˆdœ}ˆd urˆ|d< ˆd urˆ|d< ˆd ur ˆ|d< ˆd ur0ˆj | |ddiˆd�}nt ¡ �}|j | |ddiˆd�}W d   ƒ n1 sJw   Y  |jr\td	|j› �|d
�‚| ¡ }|  d¡}|smtd|d
�‚tt|ƒW S  t	y† } ztd|› �ƒ|‚d }~ww )Nz5http://169.254.169.254/metadata/identity/oauth2/token)zapi-versionr9   r3   r4   r5   ÚMetadataÚtrue©ÚparamsÚheadersr7   z4Failed to fetch Azure subject token from IMDS: HTTP ©ÚresponseÚaccess_tokenz3Azure IMDS response did not include an access_tokenz/Failed to fetch Azure subject token from IMDS: )
ÚgetÚhttpxÚClientÚis_errorr   Ústatus_codeÚjsonr   r   r)   )Úurlr@   rC   ÚclientÚdatar+   r,   ©r6   r4   r8   r5   r3   r9   r7   r   r   r   ^   s<   

ÿ
þ
ÿ€ÿz8azure_managed_identity_token_provider.<locals>.get_tokenr   r.   Nr/   r   )r9   r3   r4   r5   r6   r7   r8   r   r   rN   r   Ú%azure_managed_identity_token_providerE   s   
 rO   úhttps://api.openai.com/v1)r7   r8   Úaudiencec                  s   d‡ ‡‡fdd„}d|dœS )	a5  
    Get a subject token provider for GCP VM instances using the instance metadata server.

    See: https://cloud.google.com/compute/docs/instances/verifying-instance-identity

    Args:
        audience: the unique URI agreed upon by both the instance and the system verifying
            the instance's identity. Defaults to `https://api.openai.com/v1`.
        timeout: the request timeout in seconds. Defaults to 10.0.
        http_client: optional httpx.Client instance to use for requests. If not provided, a new client will be created for each request.
    r$   r   c               
     sÎ   zRd} dˆ i}ˆd urˆj | |ddiˆd�}nt ¡ �}|j | |ddiˆd�}W d   ƒ n1 s1w   Y  |jrCtd|j› �|d�‚|j ¡ }|sPtd|d�‚|W S  tyf } ztd	|› �ƒ|‚d }~ww )
Nz]http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identityrQ   zMetadata-FlavorÚGoogler?   z=Failed to fetch GCP subject token from metadata server: HTTP rB   z+GCP metadata server returned an empty tokenz8Failed to fetch GCP subject token from metadata server: )	rE   rF   rG   rH   r   rI   Útextr(   r)   )rK   r@   rC   rL   r+   r,   ©rQ   r8   r7   r   r   r   “   s*   
ÿ
þ
€ÿz(gcp_id_token_provider.<locals>.get_tokenr   r.   Nr/   r   )rQ   r7   r8   r   r   rT   r   Úgcp_id_token_provider�   s   
rU   c                   @  sŠ   e Zd Zedœd'dd„Zd(d	d
„Zd(dd„Zd)dd„Zd)dd„Zd*dd„Z	d+dd„Z
d(dd„Zd,dd„Zd,dd„Zd,d d!„Zd-d$d%„Zd&S ).ÚWorkloadIdentityAuth)Útoken_exchange_urlÚworkload_identityr   rW   r   c                C  s@   || _ || _d | _d | _d | _d| _t ¡ | _t 	| j¡| _
d S ©NF)rX   rW   Ú_cached_tokenÚ"_cached_token_expires_at_monotonicÚ"_cached_token_refresh_at_monotonicÚ_refreshingÚ	threadingÚLockÚ_lockÚ	ConditionÚ
_condition)ÚselfrX   rW   r   r   r   Ú__init__®   s   
zWorkloadIdentityAuth.__init__r$   c                 C  sÀ  | j �X | jr|  ¡ r| j ¡  | jr|  ¡ s|  ¡ s,|  ¡ s,tt| jƒW  d   ƒ S | jrQ| jr:| j ¡  | js2| j}|  ¡ rEt	dƒ‚tt|ƒW  d   ƒ S d| _W d   ƒ n1 s^w   Y  z`|  
¡  | j �2 |  ¡ rtt	dƒ‚tt| jƒW  d   ƒ W | j � d| _| j ¡  W d   ƒ S 1 s—w   Y  S 1 s w   Y  W | j � d| _| j ¡  W d   ƒ d S 1 s½w   Y  d S | j � d| _| j ¡  W d   ƒ w 1 sÚw   Y  w )Nz)Token is unusable after refresh completedTF)r`   r]   Ú_token_unusablerb   ÚwaitÚ_needs_refreshr   r   rZ   ÚRuntimeErrorÚ_perform_refreshÚ
notify_all)rc   r+   r   r   r   r   ¾   sJ   
ÿ
û
ÿóñ
ýþû*þþzWorkloadIdentityAuth.get_tokenc                 Ã  s   �t | jƒI d H S ©N)r   r   ©rc   r   r   r   Úget_token_asyncÛ   s   €z$WorkloadIdentityAuth.get_token_asyncÚNonec                 C  s>   | j � d | _d | _d | _W d   ƒ d S 1 sw   Y  d S rk   )r`   rZ   r[   r\   rl   r   r   r   Úinvalidate_tokenÞ   s
   "ýz%WorkloadIdentityAuth.invalidate_tokenc                 C  sh   |   ¡ }t ¡ }|d }| j� |d | _|| | _||  |¡ | _W d   ƒ d S 1 s-w   Y  d S )NÚ
expires_inrD   )Ú_fetch_token_from_exchangeÚtimeÚ	monotonicr`   rZ   r[   Ú_refresh_delay_secondsr\   )rc   Ú
token_dataÚnowrp   r   r   r   ri   ä   s   

"ýz%WorkloadIdentityAuth._perform_refreshúdict[str, Any]c              	   C  s¦   |   ¡ }| jd d }t |¡}|d u r#td|›dd t ¡ ¡› �ƒ‚t ¡ �"}|j	| j
t||| jd | jd dœd	d
�}|  |¡W  d   ƒ S 1 sLw   Y  d S )Nr   r   zUnsupported token type: z. Supported types: z, r   r   )Ú
grant_typeÚsubject_tokenÚsubject_token_typer   r   r2   )rJ   r7   )Ú_get_subject_tokenrX   ÚSUBJECT_TOKEN_TYPESrE   r   ÚjoinÚkeysrF   rG   ÚpostrW   ÚTOKEN_EXCHANGE_GRANT_TYPEÚ_handle_token_response)rc   ry   r   rz   rL   rC   r   r   r   rq   î   s(   
ÿ
û÷$ôz/WorkloadIdentityAuth._fetch_token_from_exchangerC   úhttpx.Responsec                 C  s¸   z|j r| ¡ nd }W n ty   d }Y nw |jdv r"t||d�‚|jrT|d u r-tdƒ‚| d¡}| d¡}t|t	ƒr>|sBtdƒ‚t|t
tfƒsMtdƒ‚|t|ƒdœS td	|j› �ƒ‚)
N)i�  i‘  i“  )rC   Úbodyz4Token exchange succeeded but response body was emptyrD   rp   z<Token exchange response did not include a valid access_tokenz:Token exchange response did not include a valid expires_in)rD   rp   z"Token exchange failed with status )ÚcontentrJ   Ú
ValueErrorrI   r   Ú
is_successr   rE   Ú
isinstancer   Úintr;   )rc   rC   rƒ   rD   rp   r   r   r   r�     s(   ÿ



ÿz+WorkloadIdentityAuth._handle_token_responsec                 C  s$   | j d }|d ƒ }|stdƒ‚|S )Nr   r   z>The workload identity provider returned an empty subject token)rX   r   )rc   r   ry   r   r   r   r{     s
   

z'WorkloadIdentityAuth._get_subject_tokenÚboolc                 C  s   | j d u p|  ¡ S rk   )rZ   Ú_token_expiredrl   r   r   r   re   %  s   z$WorkloadIdentityAuth._token_unusablec                 C  ó   | j d u rdS t ¡ | j kS )NT)r[   rr   rs   rl   r   r   r   rŠ   (  ó   
z#WorkloadIdentityAuth._token_expiredc                 C  r‹   rY   )r\   rr   rs   rl   r   r   r   rg   -  rŒ   z#WorkloadIdentityAuth._needs_refreshrp   r;   c                 C  s*   | j  dt¡}t||d ƒ}t|| dƒS )Nr   r
   g        )rX   rE   ÚDEFAULT_REFRESH_BUFFER_SECONDSÚminÚmax)rc   rp   Úconfigured_bufferÚeffective_bufferr   r   r   rt   2  s   z+WorkloadIdentityAuth._refresh_delay_secondsN)rX   r   rW   r   r/   )r$   rn   )r$   rw   )rC   r‚   r$   rw   )r$   r‰   )rp   r;   r$   r;   )r   r   r   ÚDEFAULT_TOKEN_EXCHANGE_URLrd   r   rm   ro   ri   rq   r�   r{   re   rŠ   rg   rt   r   r   r   r   rV   ­   s    ü










rV   )r!   )r"   r#   r$   r   )r1   )r9   r   r3   r:   r4   r:   r5   r:   r6   r   r7   r;   r8   r<   r$   r   )rP   )rQ   r   r7   r;   r8   r<   r$   r   )Ú
__future__r   rr   r^   Útypingr   r   r   r   Úpathlibr   Útyping_extensionsr   r	   rF   Ú_exceptionsr   r   r   Ú_utils._syncr   r€   r’   r�   r|   r   r   r0   rO   rU   rV   r   r   r   r   Ú<module>   sD    þÿÿø=ÿü,