
    2Rj1                    @   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e      Z G d de      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      Zy)"    )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                  "    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__     ]/var/www/html/meridian/meridian-ai/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   providerzNotRequired[float]refresh_buffer_secondsN)r   r   r   __doc__r   r   r   r   r   r      s&    2GE""..r   r   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_token8   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   )r/   r   s   ` r   "k8s_service_account_token_providerr3   ,   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 httpx.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resourcer5   r6   r7   Metadatatrueparamsheadersr9   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.   r8   r6   r:   r7   r5   r=   r9   s          r   r   z8azure_managed_identity_token_provider.<locals>.get_token^   sC   	jIC5@h%WF$&/{#$&/{#%'1|$&&??3v
TZG[el?m\\^ mv%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   r0   r1   r   )r=   r5   r6   r7   r8   r9   r:   r   s   ``````` r   %azure_managed_identity_token_providerrO   E   s    2j j@  i88r   )r9   r:   c               "     d f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.
    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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   r:   r9   s	         r   r   z(gcp_id_token_provider.<locals>.get_token   s   	sqC (+F&&??3vHY[cGdnu?v\\^ 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   r0   r1   r   )rR   r9   r:   r   s   ``` r   gcp_id_token_providerrU      s    $s. Y77r   c                  x    e Zd Ze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)WorkloadIdentityAuth)token_exchange_urlc                   || _         || _        d | _        d | _        d | _        d| _        t        j                         | _        t        j                  | j                        | _
        y NF)workload_identityrX   _cached_token"_cached_token_expires_at_monotonic"_cached_token_refresh_at_monotonic_refreshing	threadingLock_lock	Condition
_condition)selfr[   rX   s      r   __init__zWorkloadIdentityAuth.__init__   sX     "3"4)-@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)rb   r_   _token_unusablerd   wait_needs_refreshr   r   r\   RuntimeError_perform_refresh
notify_all)re   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   re   s    r   get_token_asyncz$WorkloadIdentityAuth.get_token_async   s     t~~....s   " "c                p    | j                   5  d | _        d | _        d | _        d d d        y # 1 sw Y   y xY wro   )rb   r\   r]   r^   rp   s    r   invalidate_tokenz%WorkloadIdentityAuth.invalidate_token   s6    ZZ 	;!%D6:D36:D3	; 	; 	;s   ,5c                    | j                         }t        j                         }|d   }| j                  5  |d   | _        ||z   | _        || j                  |      z   | _        d d d        y # 1 sw Y   y xY w)N
expires_inrE   )_fetch_token_from_exchangetime	monotonicrb   r\   r]   _refresh_delay_secondsr^   )re   
token_datanowru   s       r   rl   z%WorkloadIdentityAuth._perform_refresh   sy    446
nn-
ZZ 	d!+N!;D69J6FD369D<W<WXb<c6cD3	d 	d 	ds   .A--A6c           
        | j                         }| j                  d   d   }t        j                  |      }|2t	        d|ddj                  t        j                                      t        j                         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, r    r!   )
grant_typesubject_tokensubject_token_typer    r!   r4   )rK   r9   )_get_subject_tokenr[   SUBJECT_TOKEN_TYPESrF   r   joinkeysrG   rH   postrX   TOKEN_EXCHANGE_GRANT_TYPE_handle_token_response)re   r~   r   r   rM   rD   s         r   rv   z/WorkloadIdentityAuth._fetch_token_from_exchange   s    //1++J7E
044Z@%*:.8KDIIViVnVnVpLqKrs  \\^ 	9v{{''";%2*<,0,B,BCY,Z*.*@*@AU*V  # 
H ..x8	9 	9 	9s    ACC&c                   	 |j                   r|j                         nd }|j                  dv rt	        ||      |j
                  r{|t        d      |j                  d      }|j                  d      }t        |t              r|st        d      t        |t        t        f      st        d      |t        |      dS t        d	|j                         # t        $ r d }Y w xY w)
N)i  i  i  )rD   bodyz4Token exchange succeeded but response body was emptyrE   ru   z<Token exchange response did not include a valid access_tokenz:Token exchange response did not include a valid expires_in)rE   ru   z"Token exchange failed with status )contentrK   
ValueErrorrJ   r   
is_successr   rF   
isinstancer   intfloat)re   rD   r   rE   ru   s        r   r   z+WorkloadIdentityAuth._handle_token_response  s    	&.&6&68==?DD ?2hT::|!"XYY88N3L,/JlC0!"`aaj3,7!"^__$0j@QRR01E1E0FG
 	
#  	D	s   C C('C(c                R    | j                   d   } |d          }|st        d      |S )Nr"   r   z>The workload identity provider returned an empty subject token)r[   r   )re   r"   r~   s      r   r   z'WorkloadIdentityAuth._get_subject_token  s6    ))*5--/^__r   c                B    | j                   d u xs | j                         S ro   )r\   _token_expiredrp   s    r   rh   z$WorkloadIdentityAuth._token_unusable%  s!    !!T)BT-@-@-BBr   c                ^    | j                   yt        j                         | j                   k\  S )NT)r]   rw   rx   rp   s    r   r   z#WorkloadIdentityAuth._token_expired(  s)    22:~~4#J#JJJr   c                ^    | j                   yt        j                         | j                   k\  S rZ   )r^   rw   rx   rp   s    r   rj   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        )r[   rF   DEFAULT_REFRESH_BUFFER_SECONDSminmax)re   ru   configured_buffereffective_buffers       r   ry   z+WorkloadIdentityAuth._refresh_delay_seconds2  sB     22667OQop0*q.A: 00#66r   N)r[   r   rX   r   r1   )r2   None)r2   dict[str, Any])rD   zhttpx.Responser2   r   )r2   bool)ru   r   r2   r   )r   r   r   DEFAULT_TOKEN_EXCHANGE_URLrf   r   rq   rs   rl   rv   r   r   rh   r   rj   ry   r   r   r   rW   rW      s[    
 #=	: ,:  	: -:/;d90
0CK
K
7r   rW   )z3/var/run/secrets/kubernetes.io/serviceaccount/token)r/   z
str | Pathr2   r   )zhttps://management.azure.com/)r=   r   r5   
str | Noner6   r   r7   r   r8   r   r9   r   r:   httpx.Client | Noner2   r   )zhttps://api.openai.com/v1)rR   r   r9   r   r:   r   r2   r   )
__future__r   rw   r`   typingr   r   r   r   pathlibr   typing_extensionsr	   r
   rG   _exceptionsr   r   r   _utils._syncr   r   r   r   r   r   r   r3   rO   rU   rW   r   r   r   <module>r      s7   "   1 1  2  L L $M B !%  2
5 !9 !
/y /  #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H7 H7r   