o
    ưi                      @   sr   d dl Z d dl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 G dd dZdS )    N)DictOptionalTuplecast)verbose_proxy_logger)get_async_httpx_clienthttpxSpecialProvider)CommonProxyErrorsLitellmUserRolesUserAPIKeyAuthc                   @   s   e Zd ZdZededee dee defddZededee dee de	e
eef e
eef f fd	d
Zedede
eef fddZede
dededede	ee ee ee f f
ddZededefddZdS )Oauth2Handlerz*
    Handles OAuth2 token validation.
    token_info_endpointoauth_client_idoauth_client_secretreturnc                 C   s   d|   v o|duo|duS )am  
        Determine if this is an introspection endpoint (requires POST) or token info endpoint (uses GET).

        Args:
            token_info_endpoint: The OAuth2 endpoint URL
            oauth_client_id: OAuth2 client ID
            oauth_client_secret: OAuth2 client secret

        Returns:
            bool: True if this is an introspection endpoint
        Z
introspectN)lowerr   r   r    r   V/home/app/Keep/.python/lib/python3.10/site-packages/litellm/proxy/auth/oauth2_check.py_is_introspection_endpoint   s
   z(Oauth2Handler._is_introspection_endpointtokenc                 C   s^   ddi}d| i}|r%|r%t | d|   }d| |d< ||fS |r+||d< ||fS )aP  
        Prepare headers and data for OAuth2 introspection endpoint (RFC 7662).

        Args:
            token: The OAuth2 token to validate
            oauth_client_id: OAuth2 client ID
            oauth_client_secret: OAuth2 client secret

        Returns:
            Tuple of (headers, data) for the introspection request
        Content-Typez!application/x-www-form-urlencodedr   :zBasic AuthorizationZ	client_id)base64	b64encodeencodedecode)r   r   r   headersdatacredentialsr   r   r   _prepare_introspection_request+   s   z,Oauth2Handler._prepare_introspection_requestc                 C   s   d|  ddS )z
        Prepare headers for generic token info endpoint.

        Args:
            token: The OAuth2 token to validate

        Returns:
            Dict of headers for the token info request
        zBearer zapplication/json)r   r   r   r   r   r   r   _prepare_token_info_requestL   s   z)Oauth2Handler._prepare_token_info_requestresponse_datauser_id_field_nameuser_role_field_nameuser_team_id_field_namec                 C   s(   |  |}|  |}|  |}|||fS )a  
        Extract user information from OAuth2 response.

        Args:
            response_data: The response data from OAuth2 endpoint
            user_id_field_name: Field name for user ID
            user_role_field_name: Field name for user role
            user_team_id_field_name: Field name for team ID

        Returns:
            Tuple of (user_id, user_role, user_team_id)
        )get)r$   r%   r&   r'   user_iduser_team_id	user_roler   r   r   _extract_user_infoY   s   



z Oauth2Handler._extract_user_infoc              
      s  ddl m} |durtdtjj td|  t	d}tj
dd}tj
d	d
}tj
dd}tj
d}tj
d}|sEtdttjd}tj|||d}	ze|	rqtd tj| ||d\}
}|j||
|dI dH }ntd tj| d}
|j||
dI dH }|  | }td| | |	r|ddstdtj||||d\}}}t| ||tt|dW S  tjy } ztd| d}~w ty } ztd| d}~ww ) aB  
        Makes a request to the token introspection endpoint to validate the OAuth2 token.

        This function implements OAuth2 token introspection according to RFC 7662.
        It supports both generic token info endpoints (GET) and OAuth2 introspection endpoints (POST).

        Args:
            token (str): The OAuth2 token to validate.

        Returns:
            UserAPIKeyAuth: If the token is valid, containing user information.

        Raises:
            ValueError: If the token is invalid, the request fails, or the token info endpoint is not set.
        r   )premium_userTz;Oauth2 token validation is only available for premium usersz$Oauth2 token validation for token=%sZOAUTH_TOKEN_INFO_ENDPOINTZOAUTH_USER_ID_FIELD_NAMEsubZOAUTH_USER_ROLE_FIELD_NAMEZroleZOAUTH_USER_TEAM_ID_FIELD_NAMEteam_idZOAUTH_CLIENT_IDZOAUTH_CLIENT_SECRETz9OAUTH_TOKEN_INFO_ENDPOINT environment variable is not set)Zllm_providerr   z*Using OAuth2 introspection endpoint (POST))r   r   r   )r   r   Nz'Using generic token info endpoint (GET)r"   )r   z?Oauth2 token validation for token=%s, response from endpoint=%sactivezToken is not active)r$   r%   r&   r'   )Zapi_keyr/   r)   r+   z#Oauth 2.0 Token validation failed: z+An error occurred during token validation: )Zlitellm.proxy.proxy_serverr-   
ValueErrorr	   Znot_premium_uservaluer   debugosgetenvenvironr(   r   r   ZOauth2Checkr   r   r!   postr#   raise_for_statusjsonr,   r   r   r
   httpxZHTTPStatusError	Exception)r   r-   r   r%   r&   r'   r   r   clientZis_introspection_endpointr   r   responser)   r+   r*   er   r   r   check_oauth2_tokenr   s   



z Oauth2Handler.check_oauth2_tokenN)__name__
__module____qualname____doc__staticmethodstrr   boolr   r   r   r!   r#   r,   r   r?   r   r   r   r   r      sL     r   )r   r4   typingr   r   r   r   r:   Zlitellm._loggingr   Z&litellm.llms.custom_httpx.http_handlerr   r   Zlitellm.proxy._typesr	   r
   r   r   r   r   r   r   <module>   s    