o
    i=5                     @  s   d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	m
Z
 ddlmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZmZ eeZG dd deZG dd deZ G dd deZ!dS )ao  Google OAuth provider for FastMCP.

This module provides a complete Google OAuth integration that's ready to use
with just a client ID and client secret. It handles all the complexity of
Google's OAuth flow, token validation, and user management.

Example:
    ```python
    from fastmcp import FastMCP
    from fastmcp.server.auth.providers.google import GoogleProvider

    # Simple Google OAuth protection
    auth = GoogleProvider(
        client_id="your-google-client-id.apps.googleusercontent.com",
        client_secret="your-google-client-secret"
    )

    mcp = FastMCP("My Protected Server", auth=auth)
    ```
    )annotationsN)AsyncKeyValue)
AnyHttpUrl	SecretStrfield_validator)BaseSettingsSettingsConfigDict)TokenVerifier)AccessToken)
OAuthProxy)ENV_FILEparse_scopes)
get_logger)NotSetNotSetTc                   @  s   e Zd ZU dZededdZdZded< dZ	ded	< dZ
d
ed< dZd
ed< dZded< dZded< dZded< dZded< dZded< edddedd ZdS )GoogleProviderSettingsz#Settings for Google OAuth provider.FASTMCP_SERVER_AUTH_GOOGLE_ignore)
env_prefixenv_fileextraNz
str | None	client_idzSecretStr | Noneclient_secretzAnyHttpUrl | str | Nonebase_url
issuer_urlredirect_pathlist[str] | Nonerequired_scopesz
int | Nonetimeout_secondsallowed_client_redirect_urisjwt_signing_keybefore)modec                 C  s   t |S )Nr   )clsv r&   j/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/auth/providers/google.py_parse_scopes=   s   z$GoogleProviderSettings._parse_scopes)__name__
__module____qualname____doc__r   r   model_configr   __annotations__r   r   r   r   r   r   r    r!   r   classmethodr(   r&   r&   r&   r'   r   *   s&   
 
r   c                      s4   e Zd ZdZdddd fd	d
ZdddZ  ZS )GoogleTokenVerifierzToken verifier for Google OAuth tokens.

    Google OAuth tokens are opaque (not JWTs), so we verify them
    by calling Google's tokeninfo API to check if they're valid and get user info.
    N
   r   r   r   r   r   intc                  s   t  j|d || _dS )zInitialize the Google token verifier.

        Args:
            required_scopes: Required OAuth scopes (e.g., ['openid', 'https://www.googleapis.com/auth/userinfo.email'])
            timeout_seconds: HTTP request timeout
        )r   N)super__init__r   )selfr   r   	__class__r&   r'   r5   J   s   
zGoogleTokenVerifier.__init__tokenstrreturnAccessToken | Nonec                   s  z0t j| jd4 I dH }|jdd|iddidI dH }|jdkr8td	|j 	 W d  I dH  W dS | }|d
}|r[t|dkr[td 	 W d  I dH  W dS |dd}dd |	dD }| j
rt|}t| j
}	|	|stdt|t|	 	 W d  I dH  W dS i }
d|v sd|v rz|jdd| dddI dH }|jdkr| }
W n ty } ztd| W Y d}~nd}~ww d}|rtt t| }t||dd|||
dp|dd|
d|
d|
d |
d!|
d"|
d#|
|d$	d%}td& |W  d  I dH  W S 1 I dH s+w   Y  W dS  t jyM } ztd'| W Y d}~dS d}~w tyf } ztd(| W Y d}~dS d}~ww ))z<Verify Google OAuth token by calling Google's tokeninfo API.)timeoutNz.https://www.googleapis.com/oauth2/v1/tokeninfoaccess_token
User-AgentzFastMCP-Google-OAuth)paramsheaders   z$Google token verification failed: %d
expires_inr   zGoogle token has expiredscope c                 S  s   g | ]
}|  r|  qS r&   )strip).0rD   r&   r&   r'   
<listcomp>u   s
    z4GoogleTokenVerifier.verify_token.<locals>.<listcomp> z6Google token missing required scopes. Has %d, needs %dopenidprofilez-https://www.googleapis.com/oauth2/v2/userinfozBearer )Authorizationr?   )rA   z$Failed to fetch Google user info: %saudienceunknowniduser_idemailnamepicture
given_namefamily_namelocale)	subrQ   rR   rS   rT   rU   rV   google_user_datagoogle_token_info)r9   r   scopes
expires_atclaimsz"Google token verified successfullyz!Failed to verify Google token: %sz#Google token verification error: %s)httpxAsyncClientr   getstatus_codeloggerdebugjsonr3   splitr   setissubsetlen	Exceptiontimer
   RequestError)r6   r9   clientresponse
token_inforC   scope_stringtoken_scopestoken_scopes_setrequired_scopes_set	user_datauserinfo_responseer[   r>   r&   r&   r'   verify_tokenY   s   




*



6Vz GoogleTokenVerifier.verify_token)r   r   r   r3   )r9   r:   r;   r<   )r)   r*   r+   r,   r5   ru   __classcell__r&   r&   r7   r'   r0   C   s    	r0   c                      s<   e Zd ZdZeeeeeeeededdd fddZ  ZS )GoogleProvidera;  Complete Google OAuth provider for FastMCP.

    This provider makes it trivial to add Google OAuth protection to any
    FastMCP server. Just provide your Google OAuth app credentials and
    a base URL, and you're ready to go.

    Features:
    - Transparent OAuth proxy to Google
    - Automatic token validation via Google's tokeninfo API
    - User information extraction from Google APIs
    - Minimal configuration required

    Example:
        ```python
        from fastmcp import FastMCP
        from fastmcp.server.auth.providers.google import GoogleProvider

        auth = GoogleProvider(
            client_id="123456789.apps.googleusercontent.com",
            client_secret="GOCSPX-abc123...",
            base_url="https://my-server.com"
        )

        mcp = FastMCP("My App", auth=auth)
        ```
    NT)r   r   r   r   r   r   r   r    client_storager!   require_authorization_consentr   str | NotSetTr   r   AnyHttpUrl | str | NotSetTr   r   r   list[str] | NotSetTr   int | NotSetTr    rx   AsyncKeyValue | Noner!   str | bytes | NotSetTry   boolc                  s   t dd |||||||||
d	 D }|jstd|js$td|jp(d}|jp.dg}|j}t	||d}|jr@|j
 nd	}t jd
d|j|||j|j|jpT|j||	|j|d td|j| dS )a  Initialize Google OAuth provider.

        Args:
            client_id: Google OAuth client ID (e.g., "123456789.apps.googleusercontent.com")
            client_secret: Google OAuth client secret (e.g., "GOCSPX-abc123...")
            base_url: Public URL where OAuth endpoints will be accessible (includes any mount path)
            issuer_url: Issuer URL for OAuth metadata (defaults to base_url). Use root-level URL
                to avoid 404s during discovery when mounting under a path.
            redirect_path: Redirect path configured in Google OAuth app (defaults to "/auth/callback")
            required_scopes: Required Google scopes (defaults to ["openid"]). Common scopes include:
                - "openid" for OpenID Connect (default)
                - "https://www.googleapis.com/auth/userinfo.email" for email access
                - "https://www.googleapis.com/auth/userinfo.profile" for profile info
            timeout_seconds: HTTP request timeout for Google API calls
            allowed_client_redirect_uris: List of allowed redirect URI patterns for MCP clients.
                If None (default), all URIs are allowed. If empty list, no URIs are allowed.
            client_storage: Storage backend for OAuth state (client registrations, encrypted tokens).
                If None, a DiskStore will be created in the data directory (derived from `platformdirs`). The
                disk store will be encrypted using a key derived from the JWT Signing Key.
            jwt_signing_key: Secret for signing FastMCP JWT tokens (any string or bytes). If bytes are provided,
                they will be used as is. If a string is provided, it will be derived into a 32-byte key. If not
                provided, the upstream client secret will be used to derive a 32-byte key using PBKDF2.
            require_authorization_consent: Whether to require user consent before authorizing clients (default True).
                When True, users see a consent screen before being redirected to Google.
                When False, authorization proceeds directly without user confirmation.
                SECURITY WARNING: Only disable for local development or testing environments.
        c                 S  s   i | ]\}}|t ur||qS r&   )r   )rG   kr%   r&   r&   r'   
<dictcomp>  s
    z+GoogleProvider.__init__.<locals>.<dictcomp>)	r   r   r   r   r   r   r   r    r!   zQclient_id is required - set via parameter or FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_IDzYclient_secret is required - set via parameter or FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRETr1   rJ   r2   rE   z,https://accounts.google.com/o/oauth2/v2/authz#https://oauth2.googleapis.com/token)upstream_authorization_endpointupstream_token_endpointupstream_client_idupstream_client_secrettoken_verifierr   r   r   r    rx   r!   ry   z?Initialized Google OAuth provider for client %s with scopes: %sN)r   model_validateitemsr   
ValueErrorr   r   r   r    r0   get_secret_valuer4   r5   r   r   r   r!   ra   rb   )r6   r   r   r   r   r   r   r   r    rx   r!   ry   settingstimeout_seconds_finalrequired_scopes_final"allowed_client_redirect_uris_finalr   client_secret_strr7   r&   r'   r5      sh   +

zGoogleProvider.__init__)r   rz   r   rz   r   r{   r   r{   r   rz   r   r|   r   r}   r    r|   rx   r~   r!   r   ry   r   )r)   r*   r+   r,   r   r5   rv   r&   r&   r7   r'   rw      s    rw   )"r,   
__future__r   ri   r]   key_value.aio.protocolsr   pydanticr   r   r   pydantic_settingsr   r   fastmcp.server.authr	   fastmcp.server.auth.authr
   fastmcp.server.auth.oauth_proxyr   fastmcp.settingsr   fastmcp.utilities.authr   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r   r)   ra   r   r0   rw   r&   r&   r&   r'   <module>   s$    w