o
    àejl2  ã                   @  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 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	d2d3dd„Z	d4dddddddœd5d)d*„Z	+d6ddd,œd7d.d/„ZG d0d1„ d1ƒZ dS )8é    )ÚannotationsN)ÚAnyÚCallableÚ	TypedDictÚcast)ÚPath)ÚLiteralÚNotRequiredé   )ÚDefaultHttpx2Client)Ú
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   úU/var/www/html/choboyeo/PHP/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   9   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   

r1   úhttps://management.azure.com/z
2018-02-01ç      $@)Ú	object_idÚ	client_idÚ
msi_res_idÚapi_versionÚtimeoutÚhttp_clientÚresourcer   r4   ú
str | Noner5   r6   r7   r8   Úfloatr9   ú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-versionr:   r4   r5   r6   ÚMetadataÚtrue©ÚparamsÚheadersr8   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*   )ÚurlrA   rD   ÚclientÚdatar,   r-   ©r7   r5   r9   r6   r4   r:   r8   r   r   r   _   s<   

ÿ
þ
ÿ€ÿz8azure_managed_identity_token_provider.<locals>.get_tokenr   r/   Nr0   r   )r:   r4   r5   r6   r7   r8   r9   r   r   rO   r   Ú%azure_managed_identity_token_providerF   s   
 rP   úhttps://api.openai.com/v1)r8   r9   Ú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/identityrR   zMetadata-FlavorÚGoogler@   z=Failed to fetch GCP subject token from metadata server: HTTP rC   z+GCP metadata server returned an empty tokenz8Failed to fetch GCP subject token from metadata server: )	rF   rG   rH   rI   r   rJ   Útextr)   r*   )rL   rA   rD   rM   r,   r-   ©rR   r9   r8   r   r   r   ”   s*   
ÿ
þ
€ÿz(gcp_id_token_provider.<locals>.get_tokenr   r/   Nr0   r   )rR   r8   r9   r   r   rU   r   Úgcp_id_token_provider‚   s   
rV   c                   @  sŒ   e Zd Zed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 )0ÚWorkloadIdentityAuthF)Útoken_exchange_urlÚ_use_httpx2Úworkload_identityr   rX   r   rY   Úboolc                C  sF   || _ || _|| _d | _d | _d | _d| _t ¡ | _	t 
| j	¡| _d S ©NF)rZ   rX   rY   Ú_cached_tokenÚ"_cached_token_expires_at_monotonicÚ"_cached_token_refresh_at_monotonicÚ_refreshingÚ	threadingÚLockÚ_lockÚ	ConditionÚ
_condition)ÚselfrZ   rX   rY   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)rc   r`   Ú_token_unusablere   ÚwaitÚ_needs_refreshr   r   r]   ÚRuntimeErrorÚ_perform_refreshÚ
notify_all)rf   r,   r   r   r   r   Á   sJ   
ÿ
û
ÿóñ
ýþû*þþzWorkloadIdentityAuth.get_tokenc                 Ã  s   �t | jƒI d H S ©N)r   r   ©rf   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 rn   )rc   r]   r^   r_   ro   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_inrE   )Ú_fetch_token_from_exchangeÚtimeÚ	monotonicrc   r]   r^   Ú_refresh_delay_secondsr_   )rf   Ú
token_dataÚnowrs   r   r   r   rl   ç   s   

"ýz%WorkloadIdentityAuth._perform_refreshúdict[str, Any]c              	   C  sº   |   ¡ }| jd d }t |¡}|d u r#td|›dd t ¡ ¡› �ƒ‚| jr+tdd�nt	 
¡ }|�"}|j| jt||| jd | jd	 d
œdd�}|  |¡W  d   ƒ S 1 sVw   Y  d S )Nr   r   zUnsupported token type: z. Supported types: z, F)Úfollow_redirectsr   r   )Ú
grant_typeÚsubject_tokenÚsubject_token_typer   r   r3   )rK   r8   )Ú_get_subject_tokenrZ   ÚSUBJECT_TOKEN_TYPESrF   r   ÚjoinÚkeysrY   r   rG   rH   ÚpostrX   ÚTOKEN_EXCHANGE_GRANT_TYPEÚ_handle_token_response)rf   r}   r   r~   Úexchange_clientrM   rD   r   r   r   rt   ñ   s*   
ÿû÷$ôz/WorkloadIdentityAuth._fetch_token_from_exchangerD   ú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“  )rD   Úbodyz4Token exchange succeeded but response body was emptyrE   rs   z<Token exchange response did not include a valid access_tokenz:Token exchange response did not include a valid expires_in)rE   rs   z"Token exchange failed with status )ÚcontentrK   Ú
ValueErrorrJ   r   Ú
is_successr   rF   Ú
isinstancer   Úintr<   )rf   rD   rˆ   rE   rs   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)rZ   r   )rf   r   r}   r   r   r   r   "  s
   

z'WorkloadIdentityAuth._get_subject_tokenc                 C  s   | j d u p|  ¡ S rn   )r]   Ú_token_expiredro   r   r   r   rh   )  s   z$WorkloadIdentityAuth._token_unusablec                 C  ó   | j d u rdS t ¡ | j kS )NT)r^   ru   rv   ro   r   r   r   rŽ   ,  ó   
z#WorkloadIdentityAuth._token_expiredc                 C  r�   r\   )r_   ru   rv   ro   r   r   r   rj   1  r�   z#WorkloadIdentityAuth._needs_refreshrs   r<   c                 C  s*   | j  dt¡}t||d ƒ}t|| dƒS )Nr    r
   g        )rZ   rF   ÚDEFAULT_REFRESH_BUFFER_SECONDSÚminÚmax)rf   rs   Úconfigured_bufferÚeffective_bufferr   r   r   rw   6  s   z+WorkloadIdentityAuth._refresh_delay_secondsN)rZ   r   rX   r   rY   r[   r0   )r%   rq   )r%   rz   )rD   r‡   r%   rz   )r%   r[   )rs   r<   r%   r<   )r   r   r   ÚDEFAULT_TOKEN_EXCHANGE_URLrg   r   rp   rr   rl   rt   r…   r   rh   rŽ   rj   rw   r   r   r   r   rW   ®   s    û










rW   )r"   )r#   r$   r%   r   )r2   )r:   r   r4   r;   r5   r;   r6   r;   r7   r   r8   r<   r9   r=   r%   r   )rQ   )rR   r   r8   r<   r9   r=   r%   r   )!Ú
__future__r   ru   ra   Útypingr   r   r   r   Úpathlibr   Útyping_extensionsr   r	   rG   Ú_httpx2r   Ú_exceptionsr   r   r   Ú_utils._syncr   r„   r–   r‘   r€   r   r   r1   rP   rV   rW   r   r   r   r   Ú<module>   sF    þÿÿø=ÿü,