
    4Rj6                    h   U d dl mZ d dlZd dlZd dlmZ d dlmZmZm	Z	m
Z
 d dlmZ d dlZddlmZmZ ddlmZmZmZmZmZmZmZmZ d	d
lmZ e de ZdZdZdZddZ ddZ!ddddZ"g dZ# ejH                  e%      Z&de'd<    G d de      Z( G d d      Z)ddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ*y)     )annotationsN)TracebackType)AnyDictTypeOptional)override   )AccessTokenIdentityTokenProvider)TOKEN_ENDPOINTDEFAULT_BASE_URLGRANT_TYPE_JWT_BEAREROAUTH_API_BETA_HEADERFEDERATION_BETA_HEADERTOKEN_EXCHANGE_TIMEOUT_user_agent_require_https   )AnthropicError,   i @  i   c                v    | j                   j                  d      xs | j                   j                  d      }|S )Nz
Request-Idz
request-id)headersget)resprids     k/var/www/html/meridian/meridian-ai/venv/lib/python3.12/site-packages/anthropic/lib/credentials/_workload.py_request_idr   ,   s/    )),7Y4<<;K;KL;YCJ    c                    | yt        | t              r4t        |       t        k  r| S | dt         dt        |       t        z
   dz   S t        | t              ri }dD ]  }|| v s| |   ||<    |S y)zHTruncate a token-endpoint error body for safe inclusion in an exception.Nz... <z more chars>)errorerror_description	error_uri)
isinstancestrlen_MAX_ERROR_BODY_CHARSdict)bodykeptkeys      r   _redact_bodyr-   1   s    |$t9--K**+c$iBW6W5XXd.eee$!> 	&Cd{ IS		& r    )hintc                   	 | j                         }t        |      }| d| j                   d| }|r| d| }t        || j                  |t        |             # t        $ r | j                  }Y aw xY w)u  Raise a redacted :class:`WorkloadIdentityError` from a non-200 token-endpoint response.

    Shared between the jwt-bearer exchange path in this module and the
    refresh_token grant path in :mod:`_providers`.

    ``hint`` is an optional caller-supplied diagnostic appended verbatim to the
    error message (after the redacted body). Callers gate it on the response
    status and their own state — this helper does not inspect ``resp`` for it.
    z (HTTP ):  status_coder*   
request_id)json
ValueErrortextr-   r3   WorkloadIdentityErrorr   )r   message_prefixr.   payloadredactedmessages         r   _raise_token_endpoint_errorr=   C   s    yy{ G$H (8(8'9XJGGIQtf%
$$t$	   ))s   A A43A4)WorkloadIdentityCredentialsr8   exchange_federation_assertionzlogging.Loggerlogc                  v     e Zd ZU dZded<   ded<   ded<   dddd		 	 	 	 	 	 	 	 	 d fd
Zed fd       Z xZS )r8   zERaised when the OIDC token exchange (``POST /v1/oauth/token``) fails.Optional[int]r3   r   r*   Optional[str]r4   Nr2   c               N    t         |   |       || _        || _        || _        y N)super__init__r3   r*   r4   )selfr<   r3   r*   r4   	__class__s        r   rG   zWorkloadIdentityError.__init__i   s(     	!&	$r    c                `    t         |          }| j                  r| d| j                   dS |S )Nz [request_id=])rF   __str__r4   )rH   baserI   s     r   rL   zWorkloadIdentityError.__str__v   s3    w ??V=(9;;r    )
r<   r&   r3   rB   r*   r   r4   rC   returnNonerN   r&   )	__name__
__module____qualname____doc____annotations__rG   r	   rL   __classcell__)rI   s   @r   r8   r8   b   sk    O
I &*$(%% #	%
 % "% 
%  r    r8   c                      e Zd ZdZddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       Zedd       ZddZddZ	dd	Z
	 	 	 	 	 	 	 	 dd
ZddddZy)r>   u  Exchanges an external OIDC JWT for an Anthropic access token via the
    RFC 7523 ``jwt-bearer`` grant.

    This is an :class:`AccessTokenProvider`: calling it performs a *fresh* token
    exchange. Wrap in a :class:`TokenCache` (done automatically when passed as
    ``credentials=`` to :class:`anthropic.Anthropic`) to avoid exchanging on every
    request.

    Args:
        organization_id: The organization's raw UUID string (organizations do
            not use tagged IDs).
        workspace_id: Optional ``wrkspc_*`` tagged ID, or the literal
            ``"default"`` to scope the token to the organization's default
            workspace. When omitted the server picks the rule's sole enabled
            workspace, else the org default if the rule covers it. Required
            when the rule enables more than one non-default workspace, or to
            target a specific workspace other than the one the server would
            pick. The minted token is workspace-scoped: per-request workspace
            selection (the ``anthropic-workspace-id`` header) is not supported
            for federation tokens — switching workspaces requires a new token
            exchange with a different ``workspace_id``.
    N)service_account_idworkspace_idscopehttp_clientc                   || _         || _        || _        || _        || _        || _        d | _        |'t        j                  t              | _
        d| _        y || _
        d| _        y )N)timeoutTF)_identity_token_provider_federation_rule_id_organization_id_service_account_id_workspace_id_scope_bound_base_urlhttpxClientr   _http_client_owns_http_client)rH   identity_token_providerfederation_rule_idorganization_idrX   rY   rZ   r[   s           r   rG   z$WorkloadIdentityCredentials.__init__   sp     )@%#5  /#5 )
  /3 %5K LD%)D" +D%*D"r    c                    | j                   S rE   )rc   rH   s    r   rZ   z!WorkloadIdentityCredentials.scope   s    {{r    c                *    | j                   xs t        S rE   )rd   r   rm   s    r   	_base_urlz%WorkloadIdentityCredentials._base_url   s    ##7'77r    c                N    |j                  d      }t        |d       || _        y)a  Set the API ``base_url`` the token exchange POSTs to.

        Called by :class:`anthropic.Anthropic` when this object is passed as
        ``credentials=``, so callers don't pass the same URL twice. For
        standalone use (no client) or tests, call this directly.
        /base_url)fieldN)rstripr   rd   )rH   rr   bounds      r   bind_base_urlz)WorkloadIdentityCredentials.bind_base_url   s$     $uJ/$r    c                R    | j                   r| j                  j                          yy)z7Close the underlying ``httpx.Client`` if we created it.N)rh   rg   closerm   s    r   rx   z!WorkloadIdentityCredentials.close   s"    !!##% "r    c                    | S rE    rm   s    r   	__enter__z%WorkloadIdentityCredentials.__enter__   s    r    c                $    | j                          y rE   )rx   )rH   exc_typeexctbs       r   __exit__z$WorkloadIdentityCredentials.__exit__   s     	

r    F)force_refreshc                  ~| j                         }t        |j                  d            t        kD  r.t	        dt        |j                  d             dt         d      t
        || j                  | j                  d}| j                  | j                  |d<   | j                  | j                  |d<   | j                   t         }	 | j                  j                  ||t        dt               d	
      }t%        |      }t        |j&                        t(        kD  r6t	        dt(         dt        |j&                         d|j*                  |      |j*                  dk\  r7d }|j*                  dk(  rd}| j                  |dz  }|dz  }t-        |d|       	 |j/                         }	|	j7                  d      }|Bt9        |      j;                         dk7  r&t	        d|d|j*                  t3        |	      |      	 |	d   }t=        |	d          }tC        |t=        tE        jD                               |z   "      S # t         j"                  $ r}t	        d| d|       |d }~ww xY w# t0        $ rD}t3        |j4                        }
t	        d|j*                   d|
 |j*                  |
|      |d }~ww xY w# t>        t@        t0        f$ r(}t	        d!|j*                  t3        |	      |      |d }~ww xY w)#Nzutf-8zIdentity token assertion is z bytes, which exceeds the u   -byte limit. This is almost certainly not a JWT — check that the identity-token path points at the projected token, not a key or cert.)
grant_type	assertionrj   rk   rX   rY   zapplication/json)zanthropic-betazContent-Typez
User-Agent)r5   r   zFailed to reach token endpoint z: z%Token endpoint response body exceeds z bytes (got z); refusing to parse.)r3   r4   i  i  z9Ensure your federation rule matches your identity token. zIf your federation rule is scoped to multiple workspaces, set the ANTHROPIC_WORKSPACE_ID environment variable, the 'workspace_id' config key, or the workspace_id= argument. zaView your authentication events in the Workload identity page of Claude Console for more details.zToken exchange failed)r9   r.   z2Token endpoint returned non-JSON response (status r0   r2   
token_typebearerz/Token endpoint returned unsupported token_type z (expected 'Bearer').access_token
expires_inzLToken endpoint response missing required fields (access_token / expires_in).)token
expires_at)#r^   r'   encode_MAX_ASSERTION_BYTESr8   r   r_   r`   ra   rb   ro   r   rg   post_JWT_BEARER_BETA_HEADERr   re   	HTTPErrorr   content_MAX_TOKEN_RESPONSE_BYTESr3   r=   r5   r6   r-   r7   r   r&   lowerintKeyError	TypeErrorr   time)rH   r   jwtr*   urlr   errr4   r.   datar;   r   r   r   s                 r   __call__z$WorkloadIdentityCredentials.__call__   sF    ++-szz'"#&::'.s3::g3F/G.HHb'( )ab  0"&":":#44	 
 ##/)-)A)AD%&)#'#5#5D   01	a$$))&=$6"-- * D !&
t||88'78Q7R SDLL)**?A ,,%	  s"
 #'D3&R%%-FD
 w (=T[_`		99;D XXl+
!c*o&;&;&=&I'A*Ode ,,!$'%	 
	(ET,/0J 3tyy{3Cj3PQQA  	a'*I#bQTPU(VW]``	aD  	#DII.H'DTEUEUDVVYZbYcd ,,%	
 	, )Z0 	'^ ,,!$'%	
 	sH   .I I. J> I+I&&I+.	J;7?J66J;>K:#K55K:)ri   r   rj   r&   rk   r&   rX   rC   rY   rC   rZ   rC   r[   Optional[httpx.Client]rN   rO   )rN   rC   rP   )rr   r&   rN   rO   )rN   rO   )rN   z'WorkloadIdentityCredentials')r}   zOptional[Type[BaseException]]r~   zOptional[BaseException]r   zOptional[TracebackType]rN   rO   )r   boolrN   r   )rQ   rR   rS   rT   rG   propertyrZ   ro   rv   rx   r{   r   r   rz   r    r   r>   r>   ~   s    : -1&*#.2!+ "7!+  	!+
 !+ *!+ $!+ !+ ,!+ 
!+F   8 8	%&
/ % $	
 
 16 dRr    r>   )rX   rY   rr   r[   c                     t         fd|||||      }||j                  |       	  |       |j                          S # |j                          w xY w)aS  Perform a single RFC 7523 ``jwt-bearer`` exchange and return the resulting
    :class:`AccessToken`.

    This is a one-shot convenience wrapper around :class:`WorkloadIdentityCredentials`
    for callers that already have the assertion JWT in hand and just want the
    Anthropic access token back (no caching, no provider plumbing).
    c                      S rE   rz   )r   s   r   <lambda>z/exchange_federation_assertion.<locals>.<lambda>U  s    	 r    )ri   rj   rk   rX   rY   r[   )r>   rv   rx   )r   rj   rk   rX   rY   rr   r[   credss   `       r   r?   r?   C  sT    " ( 1-'-!E H%ws   A A)r   httpx.ResponserN   rC   )r*   r   rN   r   )r   r   r9   r&   r.   rC   rN   rO   )r   r&   rj   r&   rk   r&   rX   rC   rY   rC   rr   rC   r[   r   rN   r   )+
__future__r   r   loggingtypesr   typingr   r   r   r   typing_extensionsr	   re   _typesr   r   
_constantsr   r   r   r   r   r   r   r   _exceptionsr   r   r(   r   r   r   r-   r=   __all__	getLoggerrQ   r@   rU   r8   r>   r?   rz   r    r   <module>r      s   "    , , &  6	 	 	 *
 3315K4LM    ! # 
$ ei 4 d'g''1^ 1N 8BR BRT )-"&"*.  	
 &    ( r    