o
    id*                     @  s   d Z ddlm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 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 )a  AWS Cognito OAuth provider for FastMCP.

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

Example:
    ```python
    from fastmcp import FastMCP
    from fastmcp.server.auth.providers.aws_cognito import AWSCognitoProvider

    # Simple AWS Cognito OAuth protection
    auth = AWSCognitoProvider(
        user_pool_id="your-user-pool-id",
        aws_region="eu-central-1",
        client_id="your-cognito-client-id",
        client_secret="your-cognito-client-secret"
    )

    mcp = FastMCP("My Protected Server", auth=auth)
    ```
    )annotations)AsyncKeyValue)
AnyHttpUrl	SecretStrfield_validator)BaseSettingsSettingsConfigDict)TokenVerifier)AccessToken)	OIDCProxy)JWTVerifier)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< dZded< edddedd ZdS )AWSCognitoProviderSettingsz(Settings for AWS Cognito OAuth provider. FASTMCP_SERVER_AUTH_AWS_COGNITO_ignore)
env_prefixenv_fileextraN
str | Noneuser_pool_id
aws_region	client_idzSecretStr | Noneclient_secretzAnyHttpUrl | str | Nonebase_url
issuer_urlredirect_pathlist[str] | Nonerequired_scopesallowed_client_redirect_urisjwt_signing_keybefore)modec                 C  s   t |S )Nr   )clsv r)   g/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/auth/providers/aws.py_parse_scopes>   s   z(AWSCognitoProviderSettings._parse_scopes)__name__
__module____qualname____doc__r   r   model_configr   __annotations__r   r   r   r   r   r    r"   r#   r$   r   classmethodr+   r)   r)   r)   r*   r   *   s(   
 
r   c                      s"   e Zd ZdZd fddZ  ZS )	AWSCognitoTokenVerifierz>Token verifier that filters claims to Cognito-specific subset.tokenstrreturnAccessToken | Nonec                   s\   t  |I dH }|sdS |jd|jd|jdg d}t|j|j|j|j|dS )z:Verify token and filter claims to Cognito-specific subset.Nsubusernamecognito:groups)r8   r9   r:   )r4   r   scopes
expires_atclaims)	superverify_tokenr=   getr
   r4   r   r;   r<   )selfr4   access_tokencognito_claims	__class__r)   r*   r?   G   s   

z$AWSCognitoTokenVerifier.verify_token)r4   r5   r6   r7   )r,   r-   r.   r/   r?   __classcell__r)   r)   rD   r*   r3   D   s    r3   c                      sT   e Zd ZdZeeeeeeeeededdd$ fddZdddddd%d"d#Z  ZS )&AWSCognitoProvidera'  Complete AWS Cognito OAuth provider for FastMCP.

    This provider makes it trivial to add AWS Cognito OAuth protection to any
    FastMCP server using OIDC Discovery. Just provide your Cognito User Pool details,
    client credentials, and a base URL, and you're ready to go.

    Features:
    - Automatic OIDC Discovery from AWS Cognito User Pool
    - Automatic JWT token validation via Cognito's public keys
    - Cognito-specific claim filtering (sub, username, cognito:groups)
    - Support for Cognito User Pools

    Example:
        ```python
        from fastmcp import FastMCP
        from fastmcp.server.auth.providers.aws_cognito import AWSCognitoProvider

        auth = AWSCognitoProvider(
            user_pool_id="eu-central-1_XXXXXXXXX",
            aws_region="eu-central-1",
            client_id="your-cognito-client-id",
            client_secret="your-cognito-client-secret",
            base_url="https://my-server.com",
            redirect_path="/custom/callback",
        )

        mcp = FastMCP("My App", auth=auth)
        ```
    NT)r   r   r   r   r   r   r    r"   r#   client_storager$   require_authorization_consentr   str | NotSetTr   r   r   r   AnyHttpUrl | str | NotSetTr   r    r"   list[str] | NotSetTr#   rH   AsyncKeyValue | Noner$   str | bytes | NotSetTrI   boolc                  s   t dd |||||||||	|d
 D }|jstd|js%td|js,td|jp1dg}|j}|j	p9d}|j
p>d	}d
| d|j d}|jrQ|j nd}|j| _|| _	t j||j|d||j|j|||
|j|d td|j| dS )a  Initialize AWS Cognito OAuth provider.

        Args:
            user_pool_id: Your Cognito User Pool ID (e.g., "eu-central-1_XXXXXXXXX")
            aws_region: AWS region where your User Pool is located (defaults to "eu-central-1")
            client_id: Cognito app client ID
            client_secret: Cognito 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 Cognito app (defaults to "/auth/callback")
            required_scopes: Required Cognito scopes (defaults to ["openid"])
            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 AWS Cognito.
                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   ).0kr(   r)   r)   r*   
<dictcomp>   s
    z/AWSCognitoProvider.__init__.<locals>.<dictcomp>)
r   r   r   r   r   r   r    r"   r#   r$   z\user_pool_id is required - set via parameter or FASTMCP_SERVER_AUTH_AWS_COGNITO_USER_POOL_IDzVclient_id is required - set via parameter or FASTMCP_SERVER_AUTH_AWS_COGNITO_CLIENT_IDz^client_secret is required - set via parameter or FASTMCP_SERVER_AUTH_AWS_COGNITO_CLIENT_SECRETopenidzeu-central-1z/auth/callbackzhttps://cognito-idp.z.amazonaws.com/z!/.well-known/openid-configuration RS256)
config_urlr   r   	algorithmr"   r   r   r    r#   rH   r$   rI   zDInitialized AWS Cognito OAuth provider for client %s with scopes: %sN)r   model_validateitemsr   
ValueErrorr   r   r"   r#   r   r    get_secret_valuer>   __init__r   r   r$   loggerdebug)rA   r   r   r   r   r   r   r    r"   r#   rH   r$   rI   settingsrequired_scopes_final"allowed_client_redirect_uris_finalaws_region_finalredirect_path_finalrV   client_secret_strrD   r)   r*   r\   ~   sp   *

zAWSCognitoProvider.__init__)rW   audiencer"   timeout_secondsrW   r   re   r!   rf   
int | Noner6   r	   c                C  s"   t t| jj||t| jj|dS )aI  Creates a Cognito-specific token verifier with claim filtering.

        Args:
            algorithm: Optional token verifier algorithm
            audience: Optional token verifier audience
            required_scopes: Optional token verifier required_scopes
            timeout_seconds: HTTP request timeout in seconds
        )issuerre   rW   jwks_urir"   )r3   r5   oidc_configrh   ri   )rA   rW   re   r"   rf   r)   r)   r*   get_token_verifier   s   

z%AWSCognitoProvider.get_token_verifier)r   rJ   r   rJ   r   rJ   r   rJ   r   rK   r   rK   r    rJ   r"   rL   r#   rL   rH   rM   r$   rN   rI   rO   )
rW   r   re   r   r"   r!   rf   rg   r6   r	   )r,   r-   r.   r/   r   r\   rk   rF   r)   r)   rD   r*   rG   _   s(    !vrG   N)"r/   
__future__r   key_value.aio.protocolsr   pydanticr   r   r   pydantic_settingsr   r   fastmcp.server.authr	   fastmcp.server.auth.authr
   fastmcp.server.auth.oidc_proxyr   !fastmcp.server.auth.providers.jwtr   fastmcp.settingsr   fastmcp.utilities.authr   fastmcp.utilities.loggingr   fastmcp.utilities.typesr   r   r,   r]   r   r3   rG   r)   r)   r)   r*   <module>   s"    