
    Yj=                       U d dl mZ d dlZd dlZd dlmZmZmZmZm	Z	m
Z
 d dlmZ d dlmZmZmZmZ d dlZddlmZ ddlmZ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e	      Z" G d de	      Z#e#Z$de%d<    G d de	      Z& ede#e&      Z'dd	 	 	 	 	 	 	 d'dZ(	 d(	 	 	 d)dZ)	 d*ddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d+d Z*	 d,ddd!	 	 	 	 	 	 	 d-d"Z+ G d# d$ee'         Z, G d% d&e,e#         Z-y).    )annotationsN)AnyGenericTypeVarCallable	TypedDictcast)Path)Literal	TypeAliasNotRequiredoverride   )is_dict)DefaultHttpx2Client_loaded_legacy_httpx)
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                  "    e Zd ZU ded<   ded<   y)SubjectTokenProviderzLiteral['jwt', 'id']
token_typezCallable[[], str]	get_tokenN)__name__
__module____qualname____annotations__     T/var/www/html/vmm-quimica/venv/lib/python3.12/site-packages/openai/auth/_workload.pyr   r      s    $$  r"   r   c                  @    e Zd ZU dZded<   	 ded<   	 ded<   	 ded<   y	)
WorkloadIdentityz(Identity provider resource id in WIFAPI.stridentity_provider_idservice_account_idr   providerNotRequired[float]refresh_buffer_secondsNr   r   r   __doc__r    r!   r"   r#   r%   r%      s&    2GE""..r"   r%   r   SubjectTokenWorkloadIdentityc                  :    e Zd ZU dZded<   ded<   ded<   ded<   y	)
X509WorkloadIdentityzJAuthenticate with the client certificate configured on the HTTP transport.zLiteral['x509']typer&   r'   r(   r*   r+   Nr,   r!   r"   r#   r0   r0   1   s    T
..r"   r0   _WorkloadIdentityT)r+   c                     d| |d}|||d<   |S )zHConfigure X.509 workload identity without handling certificate material.x509)r1   r'   r(   r+   r!   )r'   r(   r+   identitys       r#   x509_workload_identityr6   =   s,      40&H
 )-C)*Or"   c                     d f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`.
    c                     	 t        d      5 } | j                         j                         }|st        d d      |cd d d        S # 1 sw Y   y xY w# t        $ r}t        d d|       |d }~ww xY 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token_file_paths      r#   r   z5k8s_service_account_token_provider.<locals>.get_tokenZ   s    	oos+ q(36HHYYc4dee	  
  	o+.OP_O``bcdbe,fgmnn	os4   A 1A
 	A 
AA A 	A6A11A6r   r   r   returnr&   r!   )rA   r   s   ` r#   "k8s_service_account_token_providerrE   N   s    o  i88r"   z
2018-02-01      $@)	object_id	client_id
msi_res_idapi_versiontimeouthttp_clientc               2     d f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 httpx2.Client instance to use for requests. If not provided, a new client will be created for each request.
    c                    	 d} d}|d<   |d<   

|d<   		j                  | |ddi      }n4t        j                         5 }|j                  | |ddi      }d d d        j                  rt	        d	|j
                   |
      |j                         }|j                  d      }|st	        d|
      t        t        |      S # 1 sw Y   oxY w# t        $ r}t	        d|       |d }~ww xY w)Nz5http://169.254.169.254/metadata/identity/oauth2/token)zapi-versionresourcerG   rH   rI   MetadatatrueparamsheadersrK   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httpx2Clientis_errorr   status_codejsonr	   r&   r=   )urlrS   rV   clientdatar?   r@   rJ   rH   rL   rI   rG   rO   rK   s          r#   r   z8azure_managed_identity_token_provider.<locals>.get_token   sC   	jIC5@h%WF$&/{#$&/{#%'1|$&&??3v
TZG[el?m]]_ m%zz#fzSYFZdkzlHm   /J8K_K_J`a%  ==?DHH^,E/IT\  U##m m  	j+.]^_]`,abhii	js1   A
C C%A-C CC 	C<(C77C<r   rB   rC   r!   )rO   rG   rH   rI   rJ   rK   rL   r   s   ``````` r#   %azure_managed_identity_token_providerra   g   s    2j j@  i88r"   )rK   rL   c               "     d fd}d|dS )a6  
    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 httpx2.Client instance to use for requests. If not provided, a new client will be created for each request.
    c                    	 d} di}j                  | |ddi      }n4t        j                         5 }|j                  | |ddi      }d d d        j                  rt	        d|j
                   |      |j                  j                         }|st	        d|      |S # 1 sw Y   ZxY w# t        $ r}t	        d	|       |d }~ww xY w)
Nz]http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identityaudiencezMetadata-FlavorGooglerR   z=Failed to fetch GCP subject token from metadata server: HTTP rU   z+GCP metadata server returned an empty tokenz8Failed to fetch GCP subject token from metadata server: )	rX   rY   rZ   r[   r   r\   textr<   r=   )	r^   rS   rV   r_   r?   r@   rd   rL   rK   s	         r#   r   z(gcp_id_token_provider.<locals>.get_token   s   	sqC (+F&&??3vHY[cGdnu?v]]_ v%zz#fGXZbFcmtzuHv   /ST\ThThSij%  MM'')E/0]hpqqLv v  	s+.fghfi,jkqrr	ss/   4B4 B(AB4 (B1-B4 4	C=CCr   rB   rC   r!   )rd   rK   rL   r   s   ``` r#   gcp_id_token_providerrg      s    $s. Y77r"   c                      e Zd Zedd	 	 	 	 	 	 	 ddZddZddZdddZddZdd	Z	dd
Z
ddZddZddZddZddZddZddZddZy) _WorkloadIdentityAuthTtoken_exchange_url_use_httpx2c                   || _         || _        || _        d | _        d | _        d | _        d | _        d| _        t        j                         | _
        t        j                  | j                        | _        y NF)workload_identityrk   rl   _follow_redirects_cached_token"_cached_token_expires_at_monotonic"_cached_token_refresh_at_monotonic_refreshing	threadingLock_lock	Condition
_condition)selfro   rk   rl   s       r#   __init__z_WorkloadIdentityAuth.__init__   si     6G"4&.2)-@D/@D/!&^^%
#--djj9r"   c                   | j                   5  | j                  rG| j                         r7| j                  j	                          | j                  r| j                         r7| j                         s3| j                         s#t        t        | j                        cd d d        S | j                  rs| j                  r'| j                  j	                          | j                  r'| j                  }| j                         rt        d      t        t        |      cd d d        S d| _        d d d        	 | j                          | j                   5  | j                         rt        d      t        t        | j                        cd d d        | j                   5  d| _        | j                  j                          d d d        S # 1 sw Y   xY w# 1 sw Y   S xY w# 1 sw Y   nxY w	 | j                   5  d| _        | j                  j                          d d d        y # 1 sw Y   y xY w# | j                   5  d| _        | j                  j                          d d d        w # 1 sw Y   w xY wxY w)Nz)Token is unusable after refresh completedTF)rw   rt   _token_unusablery   wait_needs_refreshr	   r&   rq   RuntimeError_perform_refresh
notify_allrz   r?   s     r#   r   z_WorkloadIdentityAuth.get_token   s   ZZ 	$""t';';'=$$& ""t';';'= '')$2E2E2GC!3!34	$ 	$ &&OO((* &&**'')&'RSSC'	$ 	$  $D	$"		-!!# 5'')&'RSSC!3!345 5
  -#( **,- -1	$ 	$0- -5 5 5
  -#( **,- - - -#( **,- - -sx   AG!9G$>G#6G#G3H, 5G	H, "GGG	G%!H, 5"H  H),I09"I$	I0$I-)I0c                H   K   t        | j                         d {   S 7 wN)r   r   rz   s    r#   get_token_asyncz%_WorkloadIdentityAuth.get_token_async   s     t~~....s   " "Nc                    | j                   5  || j                  |k7  r
	 d d d        y d | _        d | _        d | _        d d d        y # 1 sw Y   y xY wr   )rw   rq   rr   rs   r   s     r#   invalidate_tokenz&_WorkloadIdentityAuth.invalidate_token  sX    ZZ 	; T%7%75%@	; 	; "&D6:D36:D3	; 	; 	;s   AAAc                F    | j                         }| j                  |       y r   )_fetch_token_from_exchange_store_token)rz   
token_datas     r#   r   z&_WorkloadIdentityAuth._perform_refresh  s    446
*%r"   c                    t        j                         }|d   }| j                  5  |d   | _        ||z   | _        || j                  |      z   | _        d d d        y # 1 sw Y   y xY w)N
expires_inrW   )time	monotonicrw   rq   rr   _refresh_delay_secondsrs   )rz   r   nowr   s       r#   r   z"_WorkloadIdentityAuth._store_token  sk    nn-
ZZ 	d!+N!;D69J6FD369D<W<WXb<c6cD3	d 	d 	ds   .AA&c                    t        d      )Nz>Workload identity authentication must implement token exchange)NotImplementedErrorr   s    r#   r   z0_WorkloadIdentityAuth._fetch_token_from_exchange  s    !"bccr"   c                   	 |j                   r|j                         nd }|j                  dv rt	        ||      |j
                  rv|t        d      t        |      st        d      |j                  d      }|j                  d      }t        |t              r|st        d      || j                  |      dS t        d	|j                         # t        $ r d }Y w xY w)
N)i  i  i  )rV   bodyz4Token exchange succeeded but response body was emptyz@Token exchange succeeded but response body was not a JSON objectrW   r   z<Token exchange response did not include a valid access_token)rW   r   z"Token exchange failed with status )contentr]   
ValueErrorr\   r   
is_successr   r   rX   
isinstancer&   _validate_expires_in)rz   rV   r   rW   r   s        r#   _handle_token_responsez,_WorkloadIdentityAuth._handle_token_response  s    	&.&6&68==?DD ?2hT::|!"XYY4=!"dee88N3L,/JlC0!"`aa$0@Y@YZd@eff01E1E0FG
 	
#  	D	s   C C#"C#c                Z    t        |t        t        f      st        d      t        |      S )Nz:Token exchange response did not include a valid expires_in)r   intfloatr   )rz   r   s     r#   r   z*_WorkloadIdentityAuth._validate_expires_in3  s'    *sEl3Z[[Z  r"   c                B    | j                   d u xs | j                         S r   )rq   _token_expiredr   s    r#   r}   z%_WorkloadIdentityAuth._token_unusable8  s!    !!T)BT-@-@-BBr"   c                ^    | j                   yt        j                         | j                   k\  S )NT)rr   r   r   r   s    r#   r   z$_WorkloadIdentityAuth._token_expired;  s)    22:~~4#J#JJJr"   c                ^    | j                   yt        j                         | j                   k\  S rn   )rs   r   r   r   s    r#   r   z$_WorkloadIdentityAuth._needs_refresh@  s)    22:~~4#J#JJJr"   c                ~    | j                   j                  dt              }t        ||dz        }t	        ||z
  d      S )Nr+   r   g        )ro   rX   DEFAULT_REFRESH_BUFFER_SECONDSminmax)rz   r   configured_buffereffective_buffers       r#   r   z,_WorkloadIdentityAuth._refresh_delay_secondsE  sB     22667OQop0*q.A: 00#66r"   c                     ~y)>Preserve the established subject-token request retry behavior.Tr!   rz   requests     r#   _can_retry_requestz(_WorkloadIdentityAuth._can_retry_requestJ  s    r"   c                     ~y)r   Nr!   r   s     r#   _prepare_retry_requestz,_WorkloadIdentityAuth._prepare_retry_requestO  s    r"   )ro   r2   rk   r&   rl   boolrD   NonerC   r   )r?   
str | NonerD   r   )rD   r   )r   dict[str, Any]rD   r   rD   r   )rV   zhttpx2.ResponserD   r   )r   objectrD   r   )rD   r   )r   r   rD   r   )r   httpx2.RequestrD   r   )r   r   rD   r   )r   r   r   DEFAULT_TOKEN_EXCHANGE_URLr{   r   r   r   r   r   r   r   r   r}   r   r   r   r   r   r!   r"   r#   ri   ri      s    
 #= : .:  	:
 : 
:&-:/;&dd
0!
CK
K
7

r"   ri   c                  P     e Zd Zedd	 	 	 	 	 	 	 d fdZedd       ZddZ xZS )	WorkloadIdentityAuthTrj   c               *    t         |   |||       y )N)ro   rk   rl   )superr{   )rz   ro   rk   rl   	__class__s       r#   r{   zWorkloadIdentityAuth.__init__U  s      	/1# 	 	
r"   c           
        | j                         }| j                  d   d   }t        j                  |      }|2t	        d|ddj                  t        j                                      | j                  s
t               nd }||j                         nt        d      }|5 }|j                  | j                  t        ||| j                  d   | j                  d	   d
d      }| j                  |      cd d d        S # 1 sw Y   y xY w)Nr)   r   zUnsupported token type: z. Supported types: z, F)follow_redirectsr'   r(   )
grant_typesubject_tokensubject_token_typer'   r(   rF   )r]   rK   )_get_subject_tokenro   SUBJECT_TOKEN_TYPESrX   r   joinkeysrl   r   rZ   r   postrk   TOKEN_EXCHANGE_GRANT_TYPEr   )rz   r   r   r   legacy_httpxexchange_clientr_   rV   s           r#   r   z/WorkloadIdentityAuth._fetch_token_from_exchangeb  s   //1++J7E
044Z@%*:.8KDIIViVnVnVpLqKrs  6:5E5E+-4%1%=L!CVhmCn 	  	9{{''";%2*<,0,B,BCY,Z*.*@*@AU*V  # 
H ..x8	9 	9 	9s   $ADD
c                R    | j                   d   } |d          }|st        d      |S )Nr)   r   z>The workload identity provider returned an empty subject token)ro   r   )rz   r)   r   s      r#   r   z'WorkloadIdentityAuth._get_subject_token~  s6    ))*5--/^__r"   )ro   r%   rk   r&   rl   r   rD   r   r   rC   )	r   r   r   r   r{   r   r   r   __classcell__)r   s   @r#   r   r   T  sQ    
 #= 
 ,
  	

 
 

 9 96r"   r   )r'   r&   r(   r&   r+   zfloat | NonerD   r0   )z3/var/run/secrets/kubernetes.io/serviceaccount/token)rA   z
str | PathrD   r   )zhttps://management.azure.com/)rO   r&   rG   r   rH   r   rI   r   rJ   r&   rK   r   rL   httpx2.Client | NonerD   r   )zhttps://api.openai.com/v1)rd   r&   rK   r   rL   r   rD   r   ).
__future__r   r   ru   typingr   r   r   r   r   r	   pathlibr
   typing_extensionsr   r   r   r   rY   _utilsr   _httpx2r   r   _exceptionsr   r   r   _utils._syncr   r   r   r   r   r   r%   r.   r    r0   r2   r6   rE   ra   rg   ri   r   r!   r"   r#   <module>r      s   "   C C  G G   ? L L $M B !%  2
5 !9 !
/y / +; i :/9 / 13CEYZ  ,0	  )	
 $ #X9994 499 ! !#(,9999 99 	99
 99 99 99 &99 99z 0)8 (,	)8)8 )8 &	)8
 )8XBG$67 BJ/01AB /r"   