
    i2                    "   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	 d0dddddddd1d'Z	 d2ddd)d3d+Z G d, d-          ZdS )4    )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<   dS )SubjectTokenProviderzLiteral['jwt', 'id']
token_typezCallable[[], str]	get_tokenN)__name__
__module____qualname____annotations__     \/home/ubuntu/.hermes/hermes-agent/venv/lib/python3.11/site-packages/openai/auth/_workload.pyr   r      s*         $$$$      r   r   c                  N    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]         55NNN2GE""""......r   r   3/var/run/secrets/kubernetes.io/serviceaccount/tokentoken_file_path
str | Pathreturnc                     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`.
    r)   r   c                 $   	 t          d          5 } |                                                                 }|st          d d          |cd d d            S # 1 swxY w Y   d S # 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er'   s      r   r   z5k8s_service_account_token_provider.<locals>.get_token;   s    	oos++ q(( f34d4d4d4deee	                 
  	o 	o 	o+,fP_,f,fcd,f,fggmnn	os:   A* =AA* A!!A* $A!%A* *
B4B

Br   r   r   r)   r   r   )r'   r   s   ` r   "k8s_service_account_token_providerr6   /   s7    o o o o o o  i888r   https://management.azure.com/z
2018-02-01      $@)	object_idr    
msi_res_idapi_versiontimeouthttp_clientresourcer   r9   
str | Noner    r:   r;   r<   floatr=   httpx.Client | Nonec               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.
    r)   r   c                 2   	 d} d}|d<   |d<   

|d<   		                     | |ddi          }nFt          j                    5 }|                     | |ddi          }d d d            n# 1 swxY w Y   |j        rt	          d	|j         |
          |                                }|                     d          }|st	          d|
          t          t          |          S # t          $ r}t	          d|           |d }~ww xY w)Nz5http://169.254.169.254/metadata/identity/oauth2/token)zapi-versionr>   r9   r    r:   Metadatatrueparamsheadersr<   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   r0   )urlrG   rJ   clientdatar2   r3   r;   r    r=   r:   r9   r>   r<   s          r   r   z8azure_managed_identity_token_provider.<locals>.get_tokena   s   	jIC5@h%W%WF$&/{#$&/{#%'1|$&&??3v
TZG[el?mm\^^ mv%zz#fzSYFZdkzllHm m m m m m m m m m m m m m m   /a8K_aa%    ==??DHH^,,E /IT\    U### 	j 	j 	j+,a^_,a,abbhii	js=   AC4 A8,C4 8A<<C4 ?A< A3C4 4
D>DDr   r4   r5   r   )r>   r9   r    r:   r;   r<   r=   r   s   ``````` r   %azure_managed_identity_token_providerrU   H   sb    2j j j j j j j j j j j j@  i888r   https://api.openai.com/v1)r<   r=   audiencec               "     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.
    r)   r   c                    	 d} di}                     | |ddi          }nFt          j                    5 }|                     | |ddi          }d d d            n# 1 swxY w Y   |j        rt	          d|j         |          |j                                        }|st	          d|          |S # t          $ r}t	          d	|           |d }~ww xY w)
Nz]http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identityrW   zMetadata-FlavorGooglerF   z=Failed to fetch GCP subject token from metadata server: HTTP rI   z+GCP metadata server returned an empty tokenz8Failed to fetch GCP subject token from metadata server: )	rL   rM   rN   rO   r   rP   textr/   r0   )	rR   rG   rJ   rS   r2   r3   rW   r=   r<   s	         r   r   z(gcp_id_token_provider.<locals>.get_token   s|   	sqC (+F&&??3vHY[cGdnu?vv\^^ vv%zz#fGXZbFcmtzuuHv v v v v v v v v v v v v v v   /jT\Thjj%    M''))E r/0]hpqqqqL 	s 	s 	s+,jgh,j,jkkqrr	ss;   7B; A"B; "A&&B; )A&*AB; ;
CCCr   r4   r5   r   )rW   r<   r=   r   s   ``` r   gcp_id_token_providerr\      sE    $s s s s s s s s. Y777r   c                  t    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dS )"WorkloadIdentityAuth)token_exchange_urlworkload_identityr   r_   r   c                   || _         || _        d | _        d | _        d | _        d| _        t          j                    | _        t          j	        | j                  | _
        d S NF)r`   r_   _cached_token"_cached_token_expires_at_monotonic"_cached_token_refresh_at_monotonic_refreshing	threadingLock_lock	Condition
_condition)selfr`   r_   s      r   __init__zWorkloadIdentityAuth.__init__   s[     "3"4)-@D/@D/!&^%%
#-dj99r   r)   c                   | j         5  | j        rH|                                 r4| j                                         | j        r|                                 4|                                 s:|                                 s&t          t          | j                  cd d d            S | j        rr| j        r | j                                         | j         | j        }|                                 rt          d          t          t          |          cd d d            S d| _        d d d            n# 1 swxY w Y   	 | 
                                 | j         5  |                                 rt          d          t          t          | j                  cd d d            | j         5  d| _        | j                                         d d d            S # 1 swxY w Y   S # 1 swxY w Y   	 | j         5  d| _        | j                                         d d d            d S # 1 swxY w Y   d S # | j         5  d| _        | j                                         d d d            w # 1 swxY w Y   w xY w)Nz)Token is unusable after refresh completedTF)ri   rf   _token_unusablerk   wait_needs_refreshr   r   rc   RuntimeError_perform_refresh
notify_all)rl   r2   s     r   r   zWorkloadIdentityAuth.get_token   s   Z 	$ 	$" 't';';'='= '$$&&& " 't';';'='= ' '')) 5$2E2E2G2G 5C!344	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$  (& +O((*** & +*'')) T&'RSSSC''	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$  $D	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$"		-!!### 5 5'')) T&'RSSSC!3445 5 5 5 5 5 5
  - -#( **,,,- - - - - - - - - - - - - - - -5 5 5 5 5 5 5 5 5
  - -#( **,,,- - - - - - - - - - - - - - - - - - - -#( **,,,- - - - - - - - - - - - - - - -s   BD2&A,D2D22D69D6>H0 =G"H0 )!GG	G	"G&&H0 )G&*H0 5!H##H'*H'0I18!I%I1%I))I1,I)-I1c                :   K   t          | j                   d {V S N)r   r   rl   s    r   get_token_asyncz$WorkloadIdentityAuth.get_token_async   s(      t~.........r   Nonec                p    | j         5  d | _        d | _        d | _        d d d            d S # 1 swxY w Y   d S rv   )ri   rc   rd   re   rw   s    r   invalidate_tokenz%WorkloadIdentityAuth.invalidate_token   s    Z 	; 	;!%D6:D36:D3	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	; 	;s   +//c                   |                                  }t          j                    }|d         }| j        5  |d         | _        ||z   | _        ||                     |          z   | _        d d d            d S # 1 swxY w Y   d S )N
expires_inrK   )_fetch_token_from_exchangetime	monotonicri   rc   rd   _refresh_delay_secondsre   )rl   
token_datanowr}   s       r   rs   z%WorkloadIdentityAuth._perform_refresh   s    4466
n-
Z 	d 	d!+N!;D69J6FD369D<W<WXb<c<c6cD3	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	d 	ds   5A99A= A=dict[str, Any]c                   |                                  }| j        d         d         }t                              |          }|?t	          d|dd                    t                                                               t          j                    5 }|	                    | j
        t          | j        d         ||| j        d         | j        d         d	d
          }|                     |          cd d d            S # 1 swxY w Y   d S )Nr#   r   zUnsupported token type: z. Supported types: z, r    r!   r"   )
grant_typer    subject_tokensubject_token_typer!   r"   r8   )rQ   r<   )_get_subject_tokenr`   SUBJECT_TOKEN_TYPESrL   r   joinkeysrM   rN   postr_   TOKEN_EXCHANGE_GRANT_TYPE_handle_token_response)rl   r   r   r   rS   rJ   s         r   r~   z/WorkloadIdentityAuth._fetch_token_from_exchange   sX   //11+J7E
044Z@@%s:ssDIIViVnVnVpVpLqLqss   \^^ 	9v{{'";!%!7!D%2*<,0,BCY,Z*.*@AU*V   #  H ..x88	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9s   ADD	DrJ   httpx.Responsec                   	 |j         r|                                nd }n# t          $ r d }Y nw xY w|j        dv rt	          ||          |j        r|t          d          |                    d          }|                    d          }t          |t                    r|st          d          t          |t          t          f          st          d          |t          |          dS t          d	|j                   )
N)i  i  i  )rJ   bodyz4Token exchange succeeded but response body was emptyrK   r}   z<Token exchange response did not include a valid access_tokenz:Token exchange response did not include a valid expires_in)rK   r}   z"Token exchange failed with status )contentrQ   
ValueErrorrP   r   
is_successr   rL   
isinstancer   intr@   )rl   rJ   r   rK   r}   s        r   r   z+WorkloadIdentityAuth._handle_token_response
  s1   	&.&6@8==???DDD 	 	 	DDD	 ?22hT:::: 		S|!"XYYY88N33L,//JlC00 b b!"`aaaj3,77 `!"^___$0j@Q@QRRRG1EGG
 
 	
s     //c                b    | j         d         } |d                     }|st          d          |S )Nr#   r   z>The workload identity provider returned an empty subject token)r`   r   )rl   r#   r   s      r   r   z'WorkloadIdentityAuth._get_subject_token"  s?    )*5--// 	`^___r   boolc                <    | j         d u p|                                 S rv   )rc   _token_expiredrw   s    r   ro   z$WorkloadIdentityAuth._token_unusable)  s!    !T)BT-@-@-B-BBr   c                L    | j         dS t          j                    | j         k    S )NT)rd   r   r   rw   s    r   r   z#WorkloadIdentityAuth._token_expired,  s&    2:4~4#JJJr   c                L    | j         dS t          j                    | j         k    S rb   )re   r   r   rw   s    r   rq   z#WorkloadIdentityAuth._needs_refresh1  s&    2:5~4#JJJr   r}   r@   c                    | j                             dt                    }t          ||dz            }t	          ||z
  d          S )Nr$   r   g        )r`   rL   DEFAULT_REFRESH_BUFFER_SECONDSminmax)rl   r}   configured_buffereffective_buffers       r   r   z+WorkloadIdentityAuth._refresh_delay_seconds6  sH     2667OQopp0*q.AA: 00#666r   N)r`   r   r_   r   r5   )r)   ry   )r)   r   )rJ   r   r)   r   )r)   r   )r}   r@   r)   r@   )r   r   r   DEFAULT_TOKEN_EXCHANGE_URLrm   r   rx   r{   rs   r~   r   r   ro   r   rq   r   r   r   r   r^   r^      s#       
 #=	: : : : : : - - - -:/ / / /; ; ; ;d d d d9 9 9 92
 
 
 
0   C C C CK K K K
K K K K
7 7 7 7 7 7r   r^   )r&   )r'   r(   r)   r   )r7   )r>   r   r9   r?   r    r?   r:   r?   r;   r   r<   r@   r=   rA   r)   r   )rV   )rW   r   r<   r@   r=   rA   r)   r   )
__future__r   r   rg   typingr   r   r   r   pathlibr   typing_extensionsr	   r
   rM   _exceptionsr   r   r   _utils._syncr   r   r   r   r   r   r   r6   rU   r\   r^   r   r   r   <module>r      s   " " " " " "      1 1 1 1 1 1 1 1 1 1 1 1       2 2 2 2 2 2 2 2  L L L L L L L L L L $ $ $ $ $ $M B !%  2
5  ! ! ! ! !9 ! ! !
/ / / / /y / / /& #X9 9 9 9 94 499 ! !#'+99 99 99 99 99 99z 0)8 '+	)8 )8 )8 )8 )8 )8XI7 I7 I7 I7 I7 I7 I7 I7 I7 I7r   