
    kKjhG                        U d Z ddlmZ ddlZddlZddlmZ ddl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  ee      ZdddZded<   ddZ G d de      Z G d de      Zy)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)Literal)AsyncKeyValue)
AnyHttpUrl)TokenVerifier)AccessToken)
OAuthProxy)parse_scopes)
get_loggerz.https://www.googleapis.com/auth/userinfo.emailz0https://www.googleapis.com/auth/userinfo.profile)emailprofilezdict[str, str]GOOGLE_SCOPE_ALIASESc                .    t         j                  | |       S )a.  Normalize a Google scope shorthand to its canonical full URI.

    Google accepts shorthand scopes like "email" and "profile" in authorization
    requests, but returns the full URI form in token responses. This normalizes
    to the full URI so comparisons work regardless of which form was used.
    )r   get)scopes    u/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/auth/providers/google.py_normalize_google_scoper   /   s      ##E511    c                  @     e Zd ZdZdddd	 	 	 	 	 d fdZddZ xZS )	GoogleTokenVerifiera  Token verifier for Google OAuth tokens.

    Google OAuth tokens are opaque (not JWTs), so we verify them by calling
    Google's tokeninfo endpoint with the access token as a query parameter.
    This returns the OAuth app ID (``aud``), granted scopes, and expiry time.
    User profile data (name, picture, etc.) is fetched separately from the
    v2 userinfo endpoint when the token is valid.
    N
   required_scopestimeout_secondshttp_clientc                   |r|D cg c]  }t        |       c}n|}t        | 	  |       || _        || _        yc c}w )a  Initialize 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
            http_client: Optional httpx.AsyncClient for connection pooling. When provided,
                the client is reused across calls and the caller is responsible for its
                lifecycle. When None (default), a fresh client is created per call.
        )r   N)r   super__init__r   _http_client)selfr   r   r   s
normalized	__class__s         r   r   zGoogleTokenVerifier.__init__C   sS    $  2AAA$Q'A  	
 	4.' Bs   >c                <  K   	 | j                   t        j                  | j                         nt        j                  | j
                        4 d{   }|j                  dd|iddi       d{   }|j                  dk7  r2t        j                  d	|j                         	 ddd      d{    y|j                         }|j                  d
      }|s't        j                  d       	 ddd      d{    y|j                  d      }|s't        j                  d       	 ddd      d{    y|j                  dd      }|r|j                         ng }| j                  rlt        |      }	t        | j                        }
|
j                  |	      s;t        j                  dt        |	      t        |
             	 ddd      d{    yd}|j                  d      }|Pt        j                   t"        t$              5  t'        t)        j(                               t'        |      z   }ddd       i }	 |j                  dd| dd       d{   }|j                  dk(  r|j                         }t-        |||||||j                  d      xs |j                  d      |j                  d      xs |j                  d      |j                  d      |j                  d      |j                  d      |j                  d      |j                  d      |xs dd
       }t        j                  d!       |cddd      d{    S 7 7 7 7 e7 .7 # 1 sw Y   5xY w7 # t*        $ r!}t        j                  d|       Y d}~d}~ww xY w7 T# 1 d{  7  sw Y   yxY w# t        j.                  $ r }t        j                  d"|       Y d}~yd}~wt*        $ r }t        j                  d#|       Y d}~yd}~ww xY ww)$a{  Verify a Google OAuth token using the tokeninfo endpoint.

        Calls ``https://oauth2.googleapis.com/tokeninfo?access_token=TOKEN``
        to validate the token and retrieve the OAuth app ID (``aud``), granted
        scopes, and expiry time.  On success, fetches user profile data from
        the v2 userinfo endpoint to populate name, picture, and locale claims.
        N)timeoutz'https://oauth2.googleapis.com/tokeninfoaccess_token
User-AgentzFastMCP-Google-OAuth)paramsheaders   z$Google token verification failed: %daudz$Google tokeninfo missing 'aud' claimsubz$Google tokeninfo missing 'sub' claimr    z6Google token missing required scopes. Has %d, needs %d
expires_inz-https://www.googleapis.com/oauth2/v2/userinfozBearer )Authorizationr'   )r)   z'Failed to fetch Google user profile: %sr   email_verifiedverified_emailnamepicture
given_namefamily_namelocale)
r,   r+   r   r0   r2   r3   r4   r5   r6   google_user_data)token	client_idscopes
expires_atclaimsz"Google token verified successfullyz!Failed to verify Google token: %sz#Google token verification error: %s)r   
contextlibnullcontexthttpxAsyncClientr   r   status_codeloggerdebugjsonsplitr   setissubsetlensuppress
ValueError	TypeErrorinttime	Exceptionr   RequestError)r    r8   clientresponse
token_datar+   r,   	scope_strtoken_scopestoken_scopes_setrequired_scopes_setr;   r.   	user_datauserinfo_responseer&   s                    r   verify_tokenz GoogleTokenVerifier.verify_token\   s    e	 $$0 &&t'8'89&&t/C/CDE E  "(=*E2)+AB ", "  ''3.LL> ,,  #E E E& &]]_
 !nnU+LL!GH3E E E8 !nnU+LL!GH?E E ED 'NN7B7	4=y02 '''*<'8$*-d.B.B*C'.778HIT 01 34
  $_E E Ed *.
'^^L9
)#,,ZC%(%5J%G
 D
 #%	O.4jjG/6ug->*@! /9 / )% )44;$5$:$:$<	  +!')""!+!8!RIMM'<R*4..9I*J +;$==)9: )f 5#,==#;&/mmL&A'0}}]'C"+--"9,5,= & AB#yE E EE E E Ej DC) ! OLL!JANNOKE E E E| !! 	LL<a@ 	LL>B	s  PAN? MN? N*3M44N*(N? 3M4N? 8P99N*2N? =M">N? P)N*,N? 7M%8N? <P=BN*
N? M(N? P3N**M+8
N*M;M8 #M;CN*N? N(N? PN? N*N? "N? %N? (N? +M5	0N*8M;;	N%N N* N%%N*(N? *N<0N31N<8N? ;P<N? ?PO-(P-P9PPPP)r   list[str] | Noner   rL   r   httpx.AsyncClient | None)r8   strreturnzAccessToken | None)__name__
__module____qualname____doc__r   rZ   __classcell__r#   s   @r   r   r   9   s<     -1!04( *( 	(
 .(2mr   r   c                       e Zd ZdZdddddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ x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)
        ```
    Nr   Tr   )client_secretresource_base_url
issuer_urlredirect_pathr   valid_scopesr   allowed_client_redirect_urisclient_storagejwt_signing_keyrequire_authorization_consentconsent_csp_policyforward_resource%fallback_refresh_token_expiry_seconds#fastmcp_access_token_expiry_secondstoken_expiry_threshold_secondsextra_authorize_paramsr   enable_cimdc               V   |t        |      ndg}|t        |      nd}||D cg c]  }t        |       c}nd}t        ||	|      }ddd}|r|j                  |       |}t        |   dd|||||||xs ||
|||||||||||	       t        j                  d
||       yc c}w )as  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...").
                Optional for PKCE public clients (e.g., native apps). When omitted,
                jwt_signing_key must be provided.
            base_url: Public URL where OAuth endpoints will be accessible (includes any mount path)
            resource_base_url: Optional public base URL for the protected resource metadata
                and token audience. Defaults to ``base_url``.
            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
                Google scope shorthands like "email" and "profile" are automatically
                normalized to their full URI forms for token verification.
            valid_scopes: All scopes that clients are allowed to request, advertised through
                well-known endpoints. Defaults to required_scopes if not provided. Use this
                when you want clients to be able to request additional scopes beyond the
                required minimum. Shorthands are normalized to full URI forms.
            timeout_seconds: HTTP request timeout for Google API calls (defaults to 10)
            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, an encrypted file store will be created in the data directory
                (derived from `platformdirs`).
            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.
                When "external", the built-in consent screen is skipped but no warning is
                logged, indicating that consent is handled externally (e.g. by Google's own consent).
                SECURITY WARNING: Only set to False for local development or testing environments.
            extra_authorize_params: Additional parameters to forward to Google's authorization endpoint.
                By default, GoogleProvider sets {"access_type": "offline", "prompt": "consent"} to ensure
                refresh tokens are returned. You can override these defaults or add additional parameters.
                Example: {"prompt": "select_account"} to let users choose their Google account.
            http_client: Optional httpx.AsyncClient for connection pooling in token verification.
                When provided, the client is reused across verify_token calls and the caller
                is responsible for its lifecycle. When None (default), a fresh client is created per call.
            enable_cimd: Enable CIMD (Client ID Metadata Document) support for URL-based
                client IDs (default True). Set to False to disable.
            fallback_refresh_token_expiry_seconds: Lifetime for the FastMCP-issued
                refresh token when the upstream provider omits `refresh_expires_in`
                (e.g. Cognito, GitHub, many OIDC IdPs). Defaults to 1 year. The upstream
                refresh remains the source of truth. See `OAuthProxy` for details.
            fastmcp_access_token_expiry_seconds: Lifetime for the FastMCP-issued access
                token, decoupling it from the upstream provider's `expires_in`. Defaults
                to None (mirror the upstream lifetime). Set this for bridges whose
                upstream issues short-lived access tokens that some MCP clients can't
                refresh gracefully (e.g. `mcp-remote`). See `OAuthProxy` for details.
            token_expiry_threshold_seconds: Number of seconds before actual expiry to
                treat a token as expired, refreshing early to avoid races. Defaults to 0.
        Nopenidr   offlineconsent)access_typepromptz,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_verifierbase_urlrh   rj   ri   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rk   rv   z?Initialized Google OAuth provider for client %s with scopes: %s)r
   r   r   updater   r   rB   rC   )r    r9   rg   r   rh   ri   rj   r   rk   r   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   r   rv   required_scopes_finalparsed_valid_scopesr!   valid_scopes_finalr   google_defaultsextra_authorize_params_finalr#   s                                r   r   zGoogleProvider.__init__   s   n .=-HL)xj 	 +7*BL& 	
 #. 2EE1DA$Q'1DE 	 -1+#
 %

 """#9:'6$ 	,Z$I(#0)/'!-X)E)+*G1-2W0S+I#?+#+ 	 	
0 	M!	
g Fs   B&)*r9   r]   rg   
str | Noner   zAnyHttpUrl | strrh   AnyHttpUrl | str | Noneri   r   rj   r   r   r[   rk   r[   r   rL   rl   r[   rm   zAsyncKeyValue | Nonern   zstr | bytes | Nonero   z&bool | Literal['remember', 'external']rp   r   rq   boolrr   
int | Noners   r   rt   rL   ru   zdict[str, str] | Noner   r\   rv   r   )r_   r`   ra   rb   r   rc   rd   s   @r   rf   rf      s7   > %)59.2$(,0)-!9=/3.2PT)-!%<@:>./8<04 /V
 V
 "	V

 #V
 3V
 ,V
 "V
 *V
 'V
 V
 '7V
 -V
 ,V
 (NV
  '!V
" #V
$ 0:%V
& .8'V
( ),)V
* !6+V
, .-V
. /V
 V
r   rf   )r   r]   r^   r]   )rb   
__future__r   r=   rM   typingr   r?   key_value.aio.protocolsr   pydanticr   fastmcp.server.authr   fastmcp.server.auth.authr   fastmcp.server.auth.oauth_proxyr	   fastmcp.utilities.authr
   fastmcp.utilities.loggingr   r_   rB   r   __annotations__r   r   rf    r   r   <module>r      ss   * #     1  - 0 6 / 0	H	 >A( n 2P- Pfr
Z r
r   