
    i                       d Z ddlmZ ddlZddlZddlmZmZ ddlm	Z	 ddl
mZmZ ddlmZ  ej                  e      ZerddlmZ dd	lmZ dd
lmZ e	 G d d             Zeegef   eegee   f   z  ZddZddZ	 	 	 	 	 	 ddZy)a$  Authorization checks for FastMCP components.

This module provides callable-based authorization for tools, resources, and prompts.
Auth checks are functions that receive an AuthContext and return True to allow access
or False to deny.

Auth checks can also raise exceptions:
- AuthorizationError: Propagates with the custom message for explicit denial
- Other exceptions: Masked for security (logged, treated as auth failure)

Example:
    ```python
    from fastmcp import FastMCP
    from fastmcp.server.auth import require_scopes

    mcp = FastMCP()

    @mcp.tool(auth=require_scopes("write"))
    def protected_tool(): ...

    @mcp.resource("data://secret", auth=require_scopes("read"))
    def secret_data(): ...

    @mcp.prompt(auth=require_scopes("admin"))
    def admin_prompt(): ...
    ```
    )annotationsN)	AwaitableCallable)	dataclass)TYPE_CHECKINGcast)AuthorizationError)AccessTokenTool)FastMCPComponentc                  8    e Zd ZU dZded<   ded<   edd       Zy)	AuthContexta  Context passed to auth check callables.

    This object is passed to each auth check function and provides
    access to the current authentication token and the component being accessed.

    Attributes:
        token: The current access token, or None if unauthenticated.
        component: The component (tool, resource, or prompt) being accessed.
        tool: Backwards-compatible alias for component when it's a Tool.
    zAccessToken | Nonetokenr   	componentc                V    ddl m} t        | j                  |      r| j                  S dS )zBackwards-compatible access to the component as a Tool.

        Returns the component if it's a Tool, None otherwise.
        r   r   N)fastmcp.tools.toolr   
isinstancer   )selfr   s     q/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/server/auth/authorization.pytoolzAuthContext.tool?   s#     	,!+DNND!At~~KtK    N)returnzTool | None)__name__
__module____qualname____doc____annotations__propertyr    r   r   r   r   /   s)    	 L Lr   r   c                 *    t        |       dfd}|S )a  Require specific OAuth scopes.

    Returns an auth check that requires ALL specified scopes to be present
    in the token (AND logic).

    Args:
        *scopes: One or more scope strings that must all be present.

    Example:
        ```python
        @mcp.tool(auth=require_scopes("admin"))
        def admin_tool(): ...

        @mcp.tool(auth=require_scopes("read", "write"))
        def read_write_tool(): ...
        ```
    c                z    | j                   yj                  t        | j                   j                              S )NF)r   issubsetsetscopes)ctxrequireds    r   checkzrequire_scopes.<locals>.checkb   s0    99  SYY%5%5!677r   r&   r   r   boolr$   )r%   r(   r'   s     @r   require_scopesr,   N   s    $ 6{H8
 Lr   c               .     t        |      d fd}|S )a  Restrict components with a specific tag to require certain scopes.

    If the component has the specified tag, the token must have ALL the
    required scopes. If the component doesn't have the tag, access is allowed.

    Args:
        tag: The tag that triggers the scope requirement.
        scopes: List of scopes required when the tag is present.

    Example:
        ```python
        # Components tagged "admin" require the "admin" scope
        AuthMiddleware(auth=restrict_tag("admin", scopes=["admin"]))
        ```
    c                    | j                   j                  vry| j                  yj                  t	        | j                  j
                              S )NTF)r   tagsr   r#   r$   r%   )r&   r'   tags    r   r(   zrestrict_tag.<locals>.check|   sE    cmm(((99  SYY%5%5!677r   r)   r+   )r0   r%   r(   r'   s   `  @r   restrict_tagr1   j   s      6{H8 Lr   c                ^  K   t        | t              s| gn| }t        t        t           |      }|D ].  }	  ||      }t	        j
                  |      r
| d{   }|s y0 y7 # t        $ r  t        $ r3 t        j                  dt        |dt        |             dd       Y  yw xY ww)a  Run auth checks with AND logic.

    All checks must pass for authorization to succeed. Checks can be
    synchronous or asynchronous functions.

    Auth checks can:
    - Return True to allow access
    - Return False to deny access
    - Raise AuthorizationError to deny with a custom message (propagates)
    - Raise other exceptions (masked for security, treated as denial)

    Args:
        checks: A single check function or list of check functions.
            Each check can be sync (returns bool) or async (returns Awaitable[bool]).
        ctx: The auth context to pass to each check.

    Returns:
        True if all checks pass, False if any check fails.

    Raises:
        AuthorizationError: If an auth check explicitly raises it.
    NFzAuth check r   z raised an unexpected exceptionT)exc_info)r   listr   	AuthCheckinspectisawaitabler	   	Exceptionloggerwarninggetattrrepr)checksr&   
check_listr(   results        r   run_auth_checksr@      s     4 ",FD!9&vJd9oz2J	3ZF""6*%  &  & " 	 	NNgeZeEF G1 1  
 	s;   2B-"A%A#A%B-#A%%AB*&B-)B**B-)r%   strr   r5   )r0   rA   r%   z	list[str]r   r5   )r=   zAuthCheck | list[AuthCheck]r&   r   r   r*   )r   
__future__r   r6   loggingcollections.abcr   r   dataclassesr   typingr   r   fastmcp.exceptionsr	   	getLoggerr   r9   fastmcp.server.authr
   r   r   fastmcp.utilities.componentsr   r   r*   r5   r,   r1   r@   r    r   r   <module>rK      s   8 #   / ! & 1			8	$/'= L L L6 k]D()Hk]IdO5S,TT	880'0	0 
0r   