
    kKj,                        d 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 ddlmZ dd	lmZ dd
lmZ  ee      Z G d de      Z G d de      Zy)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)Literal)AsyncKeyValue)
AnyHttpUrl)AccessToken)&DEFAULT_OIDC_DISCOVERY_TIMEOUT_SECONDS	OIDCProxy)JWTVerifier)parse_scopes)
get_loggerc                  6     e Zd ZdZddd fdZd fdZ xZS )AWSCognitoTokenVerifiera  Token verifier for Cognito access tokens.

    Cognito access tokens use a ``client_id`` claim instead of the
    standard ``aud`` claim.  This subclass passes ``audience=None``
    to the parent (skipping the ``aud`` check) and validates the
    ``client_id`` claim directly.
    N)audiencec               6    || _         t        |   ddd i| y )Nr    )_expected_client_idsuper__init__)selfr   kwargs	__class__s      r/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/auth/providers/aws.pyr   z AWSCognitoTokenVerifier.__init__4   s     #+ 1$1&1    c                l  K   t         |   |       d{   }|sy| j                  r}|j                  j	                  d      }t        | j                  t              r|| j                  v }n|| j                  k(  }|s(| j                  j                  d| j                  |       y|j                  j	                  d      |j                  j	                  d      |j                  j	                  dg       d}t        |j                  |j                  |j                  |j                  |      S 7 w)	z:Verify token and filter claims to Cognito-specific subset.N	client_idzAToken validation failed: client_id mismatch (expected %s, got %s)subusernamecognito:groups)r   r   r   )tokenr   scopes
expires_atclaims)r   verify_tokenr   r"   get
isinstancelistloggerdebugr   r   r   r    r!   )r   r   access_tokentoken_client_idvalidcognito_claimsr   s         r   r#   z$AWSCognitoTokenVerifier.verify_token8   s    "W1%88 ##*1155kBO$22D9'4+C+CC'4+C+CC!!W,,#
   &&**51$++//
;*11556FK
 $$",,&&#..!
 	
5 9s   D4D1DD4)r   zstr | list[str] | None)r   strreturnzAccessToken | None)__name__
__module____qualname____doc__r   r#   __classcell__r   s   @r   r   r   +   s     >B 2"
 "
r   r   c                       e Zd ZdZeddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddddd		 	 	 	 	 	 	 	 	 dd
Z x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)
        ```
    Nzeu-central-1z/auth/callbackTr   )timeout_secondsresource_base_url
aws_region
issuer_urlredirect_pathrequired_scopes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_secondsc                   |
t        |
      ndg}d| d| d}|| _        || _        || _        t        |   ||||d|||||	|||||||||       t        j                  d||       y)	a  Initialize AWS Cognito OAuth provider.

        Args:
            user_pool_id: Your Cognito User Pool ID (e.g., "eu-central-1_XXXXXXXXX")
            client_id: Cognito app client ID
            client_secret: Cognito app client secret
            timeout_seconds: Timeout, in seconds, for the OIDC discovery request
                made during construction. Defaults to 10 seconds so a slow or
                unreachable issuer cannot block server startup indefinitely. Pass
                None to fall back to the HTTP client's own default timeout.
            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``.
            aws_region: AWS region where your User Pool is located (defaults to "eu-central-1")
            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, 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 AWS Cognito.
                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 the upstream IdP).
                SECURITY WARNING: Only set to False for local development or testing environments.
            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openidzhttps://cognito-idp.z.amazonaws.com/z!/.well-known/openid-configurationRS256)
config_urlr   client_secretr7   	algorithmr<   base_urlr8   r:   r;   r=   r>   r?   r@   rA   rB   rC   rD   rE   zDInitialized AWS Cognito OAuth provider for client %s with scopes: %s)r   user_pool_idr9   r   r   r   r'   r(   )r   rM   r   rJ   r7   rL   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   rD   rE   required_scopes_finalrI   r   s                         r   r   zAWSCognitoProvider.__init__|   s    J .=-HL)xj 	
 ,J<|nTuv
 )$" 	!'+1/!')E)+*G1-2W0S+I' 	 	
, 	R!	
r   )rK   r   r<   r7   c                   t        t        | j                  j                        |xs | j                  |t        | j                  j
                        |      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
        )issuerr   rK   jwks_urir<   )r   r-   oidc_configrP   r   rQ   )r   rK   r   r<   r7   s        r   get_token_verifierz%AWSCognitoProvider.get_token_verifier   sK      't''..//))223+
 	
r   )&rM   r-   r   r-   rJ   r-   r7   
int | NonerL   zAnyHttpUrl | strr8   AnyHttpUrl | str | Noner9   r-   r:   rU   r;   r-   r<   list[str] | Noner=   rV   r>   zAsyncKeyValue | Noner?   zstr | bytes | Noner@   z&bool | Literal['remember', 'external']rA   
str | NonerB   boolrC   rT   rD   rT   rE   int)
rK   rW   r   rW   r<   rV   r7   rT   r.   r   )r/   r0   r1   r2   r   r   rS   r3   r4   s   @r   r6   r6   ]   sW   H 'M59(.2-,09=/3.2PT)-!%<@:>./+k
 k
 	k

 k
 $k
 #k
 3k
 k
 ,k
 k
 *k
 '7k
 -k
 ,k
  (N!k
" '#k
$ %k
& 0:'k
( .8)k
* ),+k
` !%#,0&*
 
 	

 *
 $
 
!
r   r6   N)r2   
__future__r   typingr   key_value.aio.protocolsr   pydanticr   fastmcp.server.auth.authr   fastmcp.server.auth.oidc_proxyr   r	   !fastmcp.server.auth.providers.jwtr
   fastmcp.utilities.authr   fastmcp.utilities.loggingr   r/   r'   r   r6   r   r   r   <module>rc      sP   . #  1  0 : / 0	H	/
k /
db
 b
r   