o
    ni2                     @  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   U/var/www/html/arapca_proje/venv/lib/python3.10/site-packages/openai/auth/_workload.pyr      s   
 r   c                   @  sB   e Zd ZU dZded< 	 ded< 	 ded< 	 ded< 	 ded	< d
S )WorkloadIdentityz+A unique string that identifies the client.str	client_id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   ;   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_idr   
msi_res_idapi_versiontimeouthttp_clientresourcer   r4   
str | Noner   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   r4   r   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   r   r8   r5   r4   r9   r7   r   r   r   a   s<   



z8azure_managed_identity_token_provider.<locals>.get_tokenr   r/   Nr0   r   )r9   r4   r   r5   r6   r7   r8   r   r   rN   r   %azure_managed_identity_token_providerH   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/   Nr0   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 sw   Y  S 1 sw   Y  W | j  d| _| j  W d    d S 1 sw   Y  d S | j  d| _| j  W d    w 1 sw   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 | jd d	d
d}| |W  d    S 1 sPw   Y  d S )Nr   r   zUnsupported token type: z. Supported types: z, r   r   r   )
grant_typer   subject_tokensubject_token_typer   r   r3   )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   1  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   6  s   z+WorkloadIdentityAuth._refresh_delay_secondsN)rX   r   rW   r   r0   )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   )r2   )r9   r   r4   r:   r   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   r1   rO   rU   rV   r   r   r   r   <module>   sD    =,