o
    i~0                     @  s   d Z ddlm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 )aT  GitHub OAuth provider for FastMCP.

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

Example:
    ```python
    from fastmcp import FastMCP
    from fastmcp.server.auth.providers.github import GitHubProvider

    # Simple GitHub OAuth protection
    auth = GitHubProvider(
        client_id="your-github-client-id",
        client_secret="your-github-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 )GitHubProviderSettingsz#Settings for GitHub OAuth provider.FASTMCP_SERVER_AUTH_GITHUB_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/github.py_parse_scopes;   s   z$GitHubProviderSettings._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 )GitHubTokenVerifierzToken verifier for GitHub OAuth tokens.

    GitHub OAuth tokens are opaque (not JWTs), so we verify them
    by calling GitHub's 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 GitHub token verifier.

        Args:
            required_scopes: Required OAuth scopes (e.g., ['user:email'])
            timeout_seconds: HTTP request timeout
        )r   N)super__init__r   )selfr   r   	__class__r&   r'   r5   H   s   
zGitHubTokenVerifier.__init__tokenstrreturnAccessToken | Nonec                   s  zt j| jd4 I dH }|jdd| ddddI dH }|jd	kr>td
|j|jdd	  	 W d  I dH  W dS | }|jdd| ddddI dH }|j	dd}dd |
dD }|sidg}| jrt|}t| j}	|	|stdt|t|	 	 W d  I dH  W dS t|t|dd|dt|d |d|d|d|d|ddW  d  I dH  W S 1 I dH sw   Y  W dS  t jy }
 ztd|
 W Y d}
~
dS d}
~
w ty }
 ztd|
 W Y d}
~
dS d}
~
ww )z0Verify GitHub OAuth token by calling GitHub API.)timeoutNzhttps://api.github.com/userzBearer zapplication/vnd.github.v3+jsonzFastMCP-GitHub-OAuth)AuthorizationAcceptz
User-Agent)headers   z)GitHub token verification failed: %d - %sz!https://api.github.com/user/reposzx-oauth-scopes c                 S  s   g | ]
}|  r|  qS r&   )strip).0scoper&   r&   r'   
<listcomp>|   s    z4GitHubTokenVerifier.verify_token.<locals>.<listcomp>,userz6GitHub token missing required scopes. Has %d, needs %didunknownloginnameemail
avatar_url)subrK   rL   rM   rN   github_user_data)r9   r   scopes
expires_atclaimsz!Failed to verify GitHub token: %sz#GitHub token verification error: %s)httpxAsyncClientr   getstatus_codeloggerdebugtextjsonr@   splitr   setissubsetlenr
   r:   RequestError	Exception)r6   r9   clientresponse	user_datascopes_responseoauth_scopes_headertoken_scopestoken_scopes_setrequired_scopes_seter&   r&   r'   verify_tokenW   s   
	


9
4Hz GitHubTokenVerifier.verify_token)r   r   r   r3   )r9   r:   r;   r<   )r)   r*   r+   r,   r5   rk   __classcell__r&   r&   r7   r'   r0   A   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 )GitHubProvidera  Complete GitHub OAuth provider for FastMCP.

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

    Features:
    - Transparent OAuth proxy to GitHub
    - Automatic token validation via GitHub API
    - User information extraction
    - Minimal configuration required

    Example:
        ```python
        from fastmcp import FastMCP
        from fastmcp.server.auth.providers.github import GitHubProvider

        auth = GitHubProvider(
            client_id="Ov23li...",
            client_secret="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    rn   AsyncKeyValue | Noner!   str | bytes | NotSetTro   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 GitHub OAuth provider.

        Args:
            client_id: GitHub OAuth app client ID (e.g., "Ov23li...")
            client_secret: GitHub OAuth app client secret
            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 GitHub OAuth app (defaults to "/auth/callback")
            required_scopes: Required GitHub scopes (defaults to ["user"])
            timeout_seconds: HTTP request timeout for GitHub 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 GitHub.
                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   )rD   kr%   r&   r&   r'   
<dictcomp>   s
    z+GitHubProvider.__init__.<locals>.<dictcomp>)	r   r   r   r   r   r   r   r    r!   zQclient_id is required - set via parameter or FASTMCP_SERVER_AUTH_GITHUB_CLIENT_IDzYclient_secret is required - set via parameter or FASTMCP_SERVER_AUTH_GITHUB_CLIENT_SECRETr1   rH   r2   rB   z(https://github.com/login/oauth/authorizez+https://github.com/login/oauth/access_token)upstream_authorization_endpointupstream_token_endpointupstream_client_idupstream_client_secrettoken_verifierr   r   r   r    rn   r!   ro   z?Initialized GitHub 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!   rX   rY   )r6   r   r   r   r   r   r   r   r    rn   r!   ro   settingstimeout_seconds_finalrequired_scopes_final"allowed_client_redirect_uris_finalr}   client_secret_strr7   r&   r'   r5      sh   (

zGitHubProvider.__init__)r   rp   r   rp   r   rq   r   rq   r   rp   r   rr   r   rs   r    rr   rn   rt   r!   ru   ro   rv   )r)   r*   r+   r,   r   r5   rl   r&   r&   r7   r'   rm      s    rm   )!r,   
__future__r   rT   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)   rX   r   r0   rm   r&   r&   r&   r'   <module>   s"    i