
    4Rj(                       d dl mZ d dlZd dlZd dlZd dlmZ ddlmZ dZ	dZ
dZd	Zd
ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd+dZd,dZ d-dZ!d+dZ"d.d Z#d!d"d/d#Z$d0d$Z%d1d%Z&d1d&Z'd2d'Z(d2d(Z)d3d4d)Z*d2d*Z+y)5    )annotationsN)Optional   )AnthropicErrorz+urn:ietf:params:oauth:grant-type:jwt-bearerrefresh_tokenz/v1/oauth/tokeng      >@zoauth-2025-04-20zoidc-federation-2026-04-01x      defaultzhttps://api.anthropic.comANTHROPIC_API_KEYANTHROPIC_AUTH_TOKENANTHROPIC_CONFIG_DIRANTHROPIC_PROFILEANTHROPIC_IDENTITY_TOKENANTHROPIC_IDENTITY_TOKEN_FILEANTHROPIC_FEDERATION_RULE_IDANTHROPIC_ORGANIZATION_IDANTHROPIC_SERVICE_ACCOUNT_IDANTHROPIC_WORKSPACE_IDANTHROPIC_SCOPEANTHROPIC_BASE_URLc                     ddl m}  d|  S )z``User-Agent`` value sent on token-endpoint POSTs.

    Computed lazily so this module doesn't need to import ``_version`` at
    module load time (the credentials package is otherwise import-light).
    r   __version__zanthropic-python/)_versionr   r   s    l/var/www/html/meridian/meridian-ai/venv/lib/python3.12/site-packages/anthropic/lib/credentials/_constants.py_user_agentr   8   s     ({m,,    c                    t         j                  j                  t              } | rt	        j
                  |       S t        j                  dk(  r_t         j                  j                  d      }|rt	        j
                  |      n#t        j
                  j                         dz  dz  }|dz  S t        j
                  j                         dz  dz  S )uY  Resolve the config directory.

    ``ANTHROPIC_CONFIG_DIR`` env var → platform default.

    Platform defaults:
      * Linux & macOS: ``~/.config/anthropic/`` — XDG-style on both platforms
        for consistency across SDKs (macOS does **not** use
        ``~/Library/Application Support/``).
      * Windows: ``%APPDATA%\Anthropic\``
    win32APPDATAAppDataRoaming	Anthropicz.config	anthropic)	osenvirongetENV_CONFIG_DIRpathlibPathsysplatformhome)envappdatabases      r   _config_dirr1   C   s     **..
(C
||C  
||w**..+(/w||G$W\\5F5F5H95TW`5`k!!<<*[88r   c                     	 t               dz  j                  d      j                         } | xs dS # t        $ r Y yw xY w)zxReturn the stripped contents of ``<config_dir>/active_config``, or ``None``
    if the pointer file is missing or empty.active_configzutf-8)encodingN)r1   	read_textstripOSError)names    r   _read_active_config_pointerr9   X   sJ    /::G:LRRT <4  s   +3 	??c                     t         j                  j                  t              } | rt	        | t               | S t               }|t        S t	        |d       |S )u   Resolve the active profile name.

    ``ANTHROPIC_PROFILE`` env var → ``<config_dir>/active_config`` pointer file
    → ``"default"`` literal. The resolved name is validated against path-
    traversal patterns before being returned.
    sourcezactive_config pointer file)r%   r&   r'   ENV_PROFILE_validate_profile_namer9   DEFAULT_PROFILE)r.   r8   s     r   _active_profiler@   b   sK     **..
%C
s;7
&(D|4(DEKr   c                   | j                         j                  d      }|j                  d      ry|j                  d      ryt        | d| d      )a;  Reject non-``https://`` token-endpoint URLs.

    Localhost is allowed for testing so ``base_url="http://localhost:8080"``
    works against a local ``oauth_server`` instance; everything else must be
    TLS-encrypted because the body of these POSTs carries the assertion JWT
    or a long-lived refresh token.
    /zhttps://N)zhttp://localhostzhttp://127.0.0.1zhttp://[::1]z must use https (got z^); the token-exchange endpoint carries secret material and cannot be used over cleartext HTTP.)lowerrstrip
startswithr   )urlfieldlowereds      r   _require_httpsrI   t   sb     iik  %G*%RS
'&sg .J 	K r   zprofile namer;   c          	     @   | st        | d      | | j                         k7  rt        | d| d      | j                  d      rt        | d| d      ddt        j                  fD ]  }|s|| v st        | d| d|d       d	| v rt        | d| d
      y)a  Reject profile names that could escape the config directory.

    Profile names come from user-controlled sources (``ANTHROPIC_PROFILE``,
    the ``active_config`` pointer file, ``CredentialsFile(profile=...)``) and
    are interpolated into filesystem paths. A value like ``"../../etc/shadow"``
    would otherwise let a read of ``configs/<profile>.json`` escape the config
    root entirely. Pass ``source=`` so the error message names where the bad
    value came from.
    z must not be empty. z$ has leading or trailing whitespace..z must not start with a dot.rB   \um    must not contain path separators — profiles are filenames under the config directory. Pick a name without  z must not contain null bytes.N)r   r6   rE   r%   sep)profiler<   rO   s      r   r>   r>      s     x':;<<'--/!xq3WXYY#xq3NOPPT266" 3'> (!G; 'ZZ]Y``ac  xq3PQRR r   c                    | j                  d      }|j                  d      }	 |j                  |       |S # t        $ r}t        d| d| d      |d}~ww xY w)u  Assert ``candidate`` resolves to a descendant of ``base``, return it verbatim.

    The containment check uses ``resolve(strict=False)`` on both sides so
    symlinks and ``..`` segments are normalized for the purposes of escape
    detection. The returned path is the *original* (unresolved) candidate —
    callers that care about symlink following must handle it themselves
    (e.g. ``os.stat(follow_symlinks=False)``).
    F)strictzResolved path z escapes config directory rL   N)resolverelative_to
ValueErrorr   )r0   	candidatebase_resolvedcandidate_resolvederrs        r   _resolve_underrZ      s{     LLL.M"**%*8w&&}5   w~.@-AA[\i[jjklmsvvws   9 	AAAc                V    t        |        t               }t        ||dz  |  dz        S )zCPath to ``<config_dir>/configs/<profile>.json`` (non-secret, 0644).configs.jsonr>   r1   rZ   rP   r0   s     r   _config_file_pathr`      s/    7#=D$y 0gYe3D DEEr   c                V    t        |        t               }t        ||dz  |  dz        S )zCPath to ``<config_dir>/credentials/<profile>.json`` (secret, 0600).credentialsr]   r^   r_   s     r   _credentials_file_pathrc      s/    7#=D$} 4'%7H HIIr   c                 p    	 t        t                     j                         S # t        t        f$ r Y yw xY w)a  Tighter auto-discover check for the tier-1 credential chain.

    Returns ``True`` only if the *active* profile's config file exists. The
    previous version returned ``True`` for any ``.json`` under ``configs/``,
    which meant a stray ``configs/work.json`` on disk was enough to steer
    ``default_credentials()`` into reading ``configs/default.json`` and
    failing because ``default.json`` wasn't there.
    F)r`   r@   is_filer7   r    r   r   _has_active_profile_configrg      s5     !23;;==^$ s    # 55c                     t               duS )u  True if the user wrote a non-empty ``active_config`` pointer file.

    This is an explicit opt-in signal equivalent to setting ``ANTHROPIC_PROFILE``:
    the user has told us which profile to load. If the target config file is
    missing or malformed, the chain should surface that error rather than
    silently falling through — matching how ``ANTHROPIC_PROFILE=missing``
    behaves today.
    N)r9   rf   r   r   _has_explicit_active_configri      s     '(44r   c                    | t        j                  |       S t        j                  j	                  t
              }|rt        j                  |      S y)u<   ctor arg → ``ANTHROPIC_IDENTITY_TOKEN_FILE`` → ``None``.N)r)   r*   r%   r&   r'   ENV_IDENTITY_TOKEN_FILE)pathr.   s     r   resolve_identity_token_pathrm      s?    ||D!!
**..0
1C
||C  r   c                    t         j                  j                  t              s#t         j                  j                  t              ryt               ryt         j                  j                  t              rjt         j                  j                  t              rGt         j                  j                  t              s#t         j                  j                  t              ryy)u  True if the environment / filesystem contains signals that would
    normally drive the tier-1 (profile) or tier-2 (env federation) paths of
    :func:`default_credentials`.

    Used by the shadow-warning detection in the client constructor: if a
    static ``ANTHROPIC_API_KEY`` / ``ANTHROPIC_AUTH_TOKEN`` is set alongside
    any of these signals, the auto-discovery would have yielded a credential
    but got silently shadowed — and the user should know.
    TF)
r%   r&   r'   r=   r(   ri   ENV_FEDERATION_RULE_IDENV_ORGANIZATION_IDrk   ENV_IDENTITY_TOKENrf   r   r   "_has_auto_discoverable_credentialsrr      sw     
zz~~k"bjjnn^&D"$	zz~~,-"**..AT2U::>>12bjjnnEW6Xr   )returnstr)rs   pathlib.Path)rs   zOptional[str])rF   rt   rG   rt   rs   None)rP   rt   r<   rt   rs   rv   )r0   ru   rV   ru   rs   ru   )rP   rt   rs   ru   )rs   bool)N)rl   zstr | os.PathLike[str] | Noners   zpathlib.Path | None),
__future__r   r%   r+   r)   typingr   _exceptionsr   GRANT_TYPE_JWT_BEARERGRANT_TYPE_REFRESH_TOKENTOKEN_ENDPOINTTOKEN_EXCHANGE_TIMEOUTOAUTH_API_BETA_HEADERFEDERATION_BETA_HEADERADVISORY_REFRESH_SECONDSMANDATORY_REFRESH_SECONDSr?   DEFAULT_BASE_URLENV_API_KEYENV_AUTH_TOKENr(   r=   rq   rk   ro   rp   ENV_SERVICE_ACCOUNT_IDENV_WORKSPACE_ID	ENV_SCOPEENV_BASE_URLr   r1   r9   r@   rI   r>   rZ   r`   rc   rg   ri   rm   rr   rf   r   r   <module>r      s    " 	 
   )E * "  
 +  6    .  "' (! 0 9 7 1 7 + 	#-9*$& ;I S4$FJ	5r   