Ë
    ¹ÿjÜ@  ã                   ó  — d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
mZ ddlmZmZ dZg d¢ZdZdZd	Zd
ZdZ eeeez  z
  ez  «      Zegez  egez  z   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$y)z'Helpers for Agent Identity credentials.é    N)ÚquoteÚurlparse)Úenvironment_varsÚ
exceptionsz‰The cryptography library is required for certificate-based authentication.Please install it with `pip install google-auth[cryptography]`.)z+^agents\.global\.org-\d+\.system\.id\.goog$z,^agents\.global\.proj-\d+\.system\.id\.goog$z3^agents-nonprod\.global\.org-\d+\.system\.id\.goog$z4^agents-nonprod\.global\.proj-\d+\.system\.id\.goog$z=/var/run/secrets/workload-spiffe-credentials/certificates.pemé2   gš™™™™™¹?g      à?é   c                 óÄ   — | sy	 t        j                  | «      }t        j                  |j                  «      xr |j                  dkD  S # t
        $ r ‚ t        $ r Y yw xY w)z=Checks if a file exists, is a regular file, and is not empty.Fr   )ÚosÚstatÚS_ISREGÚst_modeÚst_sizeÚPermissionErrorÚOSError)ÚpathÚsts     ú[/root/telegram-saas/.venv/lib/python3.12/site-packages/google/auth/_agent_identity_utils.pyÚ_is_certificate_file_readyr   <   sY   € áØð
ô �W‰W�T‹]ˆÜ�|‰|˜BŸJ™JÓ'Ò:¨B¯J©J¸©NÐ:øÜò àÜò Ùðús   …AA
 Á
AÁAc                 ó2  — | syt         j                  j                  t        «      }	 t         j                  j	                  | «      }t         j                  j	                  |«      }t         j                  j                  ||g«      |k(  S # t        $ r Y yw xY w)zKChecks if the given path is inside the well-known Agent Identity directory.F)r
   r   ÚdirnameÚ_WELL_KNOWN_CERT_PATHÚrealpathÚ
commonpathÚ
ValueError)r   Úwell_known_dirÚ	real_pathÚreal_well_known_dirs       r   Ú_is_in_well_known_dirr   M   s€   € áØÜ—W‘W—_‘_Ô%:Ó;€NðÜ—G‘G×$Ñ$ TÓ*ˆ	Ü Ÿg™g×.Ñ.¨~Ó>Ðä�G‰G×ÑÐ 3°YÐ?Ó@ÐDWÑWð	
øô ò Ùðús   ¨A!B
 Â
	BÂBc                  ó  — ddl m}  t        j                  j	                  t
        j                  «      }|s<| j                  «       s+| j                  | j                  «       «      r| j                  S yt        |«      }t        ||«      S )af  Gets the agent certificate path from the certificate config file or GKE bundle.

    The path to the certificate config file is read from the
    GOOGLE_API_CERTIFICATE_CONFIG environment variable. This function
    can optionally trigger polling to handle cases where the environment
    variable is set before the files are available on the filesystem.
    When GOOGLE_API_CERTIFICATE_CONFIG and
    CLOUDSDK_CONTEXT_AWARE_CERTIFICATE_CONFIG_FILE_PATH are unset and no
    implicit certificate_config.json is present, it falls back to checking
    the GKE workload credential bundle path without polling.

    Returns:
        Optional[str]: The path to the agent's certificate file, or None if unavailable.

    Raises:
        google.auth.exceptions.RefreshError: If the certificate config file
            or the certificate file cannot be found after retries.
    r   ©Ú_mtls_helperN)Úgoogle.auth.transportr!   r
   ÚenvironÚgetr   ÚGOOGLE_API_CERTIFICATE_CONFIGÚ_has_explicit_cert_config_envÚ!_should_use_gke_credential_bundleÚ_get_cert_config_pathÚ_GKE_CREDENTIAL_BUNDLE_PATHr   Ú$_get_cert_path_with_optional_polling)r!   Úcert_config_pathÚshould_polls      r   Ú#get_agent_identity_certificate_pathr-   \   sv   € õ& 3ä—z‘z—~‘~Ô&6×&TÑ&TÓUÐáà×:Ñ:Ô<Ø×>Ñ>Ø×2Ñ2Ó4ôð  ×;Ñ;Ð;Øô (Ð(8Ó9€Kä/Ð0@À+ÓNÐNó    c                 ó˜  — d}d}t         D ]i  }	 t        | «      }|€ yt        |«      r|c S |rt        |«      s y|s"t	        j
                  d|› dt        › d�«       d}t!        j"                  |«       Œk t%        j&                  dt        j(                  › d�«      ‚# t        $ r$}t	        j
                  d|› d�«       Y d}~ yd}~wt        t        t        f$ rl}t        j                  j                  | «      rY d}~ y|sY d}~ y|s3t	        j
                  d	|› d
t        j                  › dt        › d�«       d}Y d}~Œäd}~ww xY w)ai  Gets the certificate path, optionally polling until it is ready.

    Args:
        cert_config_path (str): The path to the certificate configuration file.
        should_poll (bool): If True, the function will poll for the file and
            certificate to be ready. If False, it will check only once and
            return early if they are not immediately available.

    Returns:
        str: The path to the certificate file, or None if unavailable.

    Raises:
        google.auth.exceptions.RefreshError: If the certificate config file
            or the certificate file cannot be found after retries.
    FNzCertificate file not ready at z(. Retrying until startup timeout (up to z seconds total)...TzIPermission denied when accessing certificate config or certificate file: úM. Token binding protection cannot be enabled. Falling back to unbound tokens.z1Certificate config file not found or incomplete: z (from z> environment variable). Retrying until startup timeout (up to zšCertificate config or certificate file not found after multiple retries. Token binding protection is failing. You can turn off this protection by setting z) to false to fall back to unbound tokens.)Ú_POLLING_INTERVALSÚ_parse_cert_path_from_configr   r   ÚwarningsÚwarnÚ_TOTAL_TIMEOUTr   ÚIOErrorr   ÚKeyErrorr
   r   Úexistsr   r%   ÚtimeÚsleepr   ÚRefreshErrorÚ%GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN)r+   r,   Úhas_logged_config_warningÚhas_logged_cert_warningÚintervalÚ	cert_pathÚes          r   r*   r*   ‡   ss  € ð  !&ÐØ#Ðä&ò .ˆð*	1Ü4Ð5EÓFˆIàÐ Ùä)¨)Ô4Ø Ò ñ  Ô$9¸)Ô$DÙá*Ü—‘Ø4°Y°KÐ?gÔhvÐgwð  xJð  Kôð +/Ð'ô6 	�
‰
�8Õð].ô` ×
!Ñ
!ð	\ä×AÑAÐ
Bð C*ð	*óð øô7 ò 	Ü�M‰MØ[Ð\]Ð[^ð _^ð ^ôõ ûÜœ¤XÐ.ò 	1Ü�w‰w�~‰~Ð.Ô/õ áåá,Ü—‘ØGÈÀsÈ'Ü'×EÑEÐFð G=Ü=KÐ<LÐL^ð`ôð
 -1Ð)ÿøð!	1ús>   �BžB­B¼$BÂ	E	Â'CÃE	ÃEÄEÄ
5EÅE	c                 ó2  — t        | dd¬«      5 }t        j                  |«      }ddd«       t        t        «      r|j                  d«      nd}t        |t        «      r|j                  d«      nd}t        |t        «      rd|vry|d   S # 1 sw Y   ŒixY w)a	  Reads the cert config file and returns the cert_path.

    Args:
        cert_config_path (str): The path to the certificate configuration file.

    Returns:
        Optional[str]: The path to the certificate file, or None if not found
            in the config.

    Raises:
        IOError: If the certificate config file cannot be read.
        ValueError: If the certificate config file contains invalid JSON.
        KeyError: If the certificate config file does not contain the
            expected structure.
    Úrúutf-8)ÚencodingNÚcert_configsÚworkloadr@   )ÚopenÚjsonÚloadÚ
isinstanceÚdictr$   )r+   ÚfÚcert_configrF   Úworkload_configs        r   r2   r2   Ò   s”   € ô  
Ð ¨gÔ	6ð #¸!Ü—i‘i “lˆ÷#ô ,6°kÄ4Ô+Hˆ�‰˜Ô'Èdð ô )3°<ÄÔ(Fˆ×Ñ˜Ô$ÈDð ô �o¤tÔ,°À?Ñ0RØà˜;Ñ'Ð'÷#ð #ús   �BÂBc                  ó  — t         j                  j                  t        j                  d«      j                  «       } | s<t         j                  j                  t        j                  d«      j                  «       } | j                  «       dk(  S )zGReturns True only if bound tokens are explicitly disabled via env vars.Ú ÚtrueÚfalse)r
   r#   r$   r   r<   ÚstripÚ7GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICESÚlower)Úvals    r   Ú_is_bound_token_opted_outrX   ò   sk   € ä
�*‰*�.‰.Ü×>Ñ>Àóç�eƒgð ñ ä�j‰j�n‰nÜ×TÑTØó
÷ ‰%‹'ð 	ð �9‰9‹;˜'Ñ!Ð!r.   c                  ó`  — ddl m}  t        «       ry| j                  «       }|du ryt	        «       }|sy	 t        |d«      5 }|j                  «       }ddd«       | j                  j                  «      }|st        j                  d
|› d	�«       ydj                  d„ |D «       «      dz   }	 t        |«      |fS # 1 sw Y   ŒixY w# t        $ r&}t        j                  d|› d|› d	�«       Y d}~yd}~ww xY w# t        t        f$ r&}t        j                  d|› d|› d	�«       Y d}~yd}~ww xY w)a®  Gets and parses the agent identity certificate if not opted out.

    Checks if the user has opted out of certificate-bound tokens. If not,
    it gets the certificate path, reads the file, and parses it.

    Returns:
        Tuple[Optional[cryptography.x509.Certificate], Optional[bytes]]: A tuple
            of (parsed certificate object, certificate bytes) if found and not
            opted out, otherwise (None, None).
    r   r    )NNFÚrbNz2Failed to read agent identity certificate file at z: r0   z#No PEM certificate blocks found in ó   
c              3   ó<   K  — | ]  }|j                  «       –— Œ y ­w)N)rT   )Ú.0Úblocks     r   ú	<genexpr>z;get_agent_identity_certificate_and_bytes.<locals>.<genexpr>-  s   è ø€ ÒC¨e˜EŸK™KŸMÑCùs   ‚z.Failed to parse agent identity certificate at )r"   r!   rX   Ú_check_use_client_cert_envr-   rH   Úreadr   r3   r4   Ú_CERT_REGEXÚfindallÚjoinÚparse_certificater   ÚImportError)r!   Úenv_overrider@   Ú	cert_fileÚ	raw_bytesrA   Úcert_blocksÚ
cert_bytess           r   Ú(get_agent_identity_certificate_and_bytesrl      sU  € õ 3ô !Ô"Øð  ×:Ñ:Ó<€LØ�uÑØä3Ó5€IÙØðÜ�)˜TÓ"ð 	) iØ!Ÿ™Ó(ˆI÷	)ð ×*Ñ*×2Ñ2°9Ó=€KÙÜ�‰Ø1°)°ð =Zð Zô	
ð à—‘ÑC°{ÔCÓCÀeÑK€JðÜ  Ó+¨ZÐ7Ð7÷'	)ð 	)ûäò Ü�‰Ø@ÀÀÈ2ÈaÈSð QZð Zô	
ô ûðûô$ œÐ$ò Ü�‰Ø<¸Y¸KÀrÈ!Èð MZð Zô	
ô ûðúsG   µC ÁB:ÁC Â-C8 Â:CÂ?C Ã	C5ÃC0Ã0C5Ã8D-ÄD(Ä(D-c                 ó^  — ddl m} | st        d«      ‚	 ddlm} |j
                  j                  | «      }|s|j                  | «      S |j                  | |«      rt        d«      ‚|D �cg c]  }|j                  |«      ‘Œ }}|d   S c c}w # t        $ r}t        t        «      |‚d}~ww xY w)aÂ  Parses a PEM-encoded certificate or certificate chain and returns the leaf certificate.

    Args:
        cert_bytes (bytes): The PEM-encoded certificate bytes.

    Returns:
        cryptography.x509.Certificate: The leaf (first) parsed certificate object.

    Raises:
        ValueError: If no certificates are found or any certificate in the chain
            is malformed.
        ImportError: If the cryptography library is not installed.
    r   r    z*Certificate bytes cannot be empty or None.©Úx509z-Malformed or truncated PEM certificate chain.N)r"   r!   r   Úcryptographyro   rb   rc   Úload_pem_x509_certificateÚ_has_unmatched_pem_markersrf   ÚCRYPTOGRAPHY_NOT_FOUND_ERROR)rk   r!   ro   rj   r^   ÚcertsrA   s          r   re   re   8  s¯   € õ 3áÜÐEÓFÐFð?Ý%à"×.Ñ.×6Ñ6°zÓBˆÙØ×1Ñ1°*Ó=Ð=Ø×2Ñ2°:¸{ÔKÜÐLÓMÐMØDOÖP¸5�×/Ñ/°Õ6ÐPˆÐPØ�Q‰xˆùò Qøäò ?ÜÔ6Ó7¸QÐ>ûð?ús/   •3B Á	!B Á*B	ÂB Â	B Â	B,ÂB'Â'B,c                 óÄ  — 	 ddl m} ddlm} 	 | j                  j                  |j                  «      }|j                  j                  |j                  «      }|D ]M  }t        |«      }|j                  dk(  sŒ|j                  }t        D ]  }t        j                   ||«      sŒ  y ŒO y# |j                  $ r Y yw xY w# t"        $ r}	t#        t$        «      |	‚d}	~	ww xY w)aš  Checks if a certificate is an Agent Identity certificate.

    This is determined by checking the Subject Alternative Name (SAN) for a
    SPIFFE ID with a trust domain matching Agent Identity patterns.

    Args:
        cert (cryptography.x509.Certificate): The parsed certificate object.

    Returns:
        bool: True if the certificate is an Agent Identity certificate,
            False otherwise.
    r   rn   )ÚExtensionOIDFÚspiffeTN)rp   ro   Úcryptography.x509.oidrv   Ú
extensionsÚget_extension_for_oidÚSUBJECT_ALTERNATIVE_NAMEÚExtensionNotFoundÚvalueÚget_values_for_typeÚUniformResourceIdentifierr   ÚschemeÚnetlocÚ,_AGENT_IDENTITY_SPIFFE_TRUST_DOMAIN_PATTERNSÚreÚmatchrf   rs   )
Úcertro   rv   ÚextÚurisÚuriÚ
parsed_uriÚtrust_domainÚpatternrA   s
             r   Ú_is_agent_identity_certificaterŒ   Y  sÚ   € ð?Ý%Ý6ð	Ø—/‘/×7Ñ7Ø×5Ñ5óˆCð
 �y‰y×,Ñ,¨T×-KÑ-KÓLˆàò 	$ˆCÜ! #›ˆJØ× Ñ  HÓ,Ø)×0Ñ0�ÜKò $�GÜ—x‘x ¨Õ6Ú#ñ$ð		$ð øð ×%Ñ%ò 	Ùð	ûô ò ?ÜÔ6Ó7¸QÐ>ûð?úsL   ‚C �%B, ´AC Á9+C Â%C Â(C Â,B>Â;C Â=B>Â>C Ã	CÃ
CÃCc                 ób  — 	 ddl m} | j                  |j                  j                  «      }t        j                  |«      j                  «       }t        j                  |«      j                  d«      }|j                  d«      }t        |«      S # t        $ r}t        t        «      |‚d}~ww xY w)a  Calculates the URL-encoded, unpadded, base64-encoded SHA256 hash of a
    DER-encoded certificate.

    Args:
        cert (cryptography.x509.Certificate): The parsed certificate object.

    Returns:
        str: The URL-encoded, unpadded, base64-encoded SHA256 fingerprint.
    r   )ÚserializationrD   ú=N)Úcryptography.hazmat.primitivesrŽ   Úpublic_bytesÚEncodingÚDERÚhashlibÚsha256ÚdigestÚbase64Ú	b64encodeÚdecodeÚrstripr   rf   rs   )r…   rŽ   Úder_certÚfingerprintÚbase64_fingerprintÚunpadded_base64_fingerprintrA   s          r   Ú!calculate_certificate_fingerprintrŸ   ~  s–   € ð?Ý@à×$Ñ$ ]×%;Ñ%;×%?Ñ%?Ó@ˆÜ—n‘n XÓ.×5Ñ5Ó7ˆô $×-Ñ-¨kÓ:×AÑAÀ'ÓJÐØ&8×&?Ñ&?ÀÓ&DÐ#ÜÐ0Ó1Ð1øÜò ?ÜÔ6Ó7¸QÐ>ûð?ús   ‚BB Â	B.ÂB)Â)B.c                 ód   — ddl m} t        «       ry|j                  «       }|du ryt	        | «      S )aÕ  Determines if a bound token should be requested.

    This is based on the GOOGLE_API_ENABLE_RUNTIME_BOUND_TOKEN env var
    (falls back to the deprecated GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES
    if unset or empty) and whether the certificate is an agent identity cert.

    Args:
        cert (cryptography.x509.Certificate): The parsed certificate object.

    Returns:
        bool: True if a bound token should be requested, False otherwise.
    r   r    F)r"   r!   rX   r`   rŒ   )r…   r!   rg   s      r   Úshould_request_bound_tokenr¡   ™  s6   € õ 3ä Ô"Øð  ×:Ñ:Ó<€LØ�uÑØä)¨$Ó/Ð/r.   c                 óL   — | rt        | «      }t        |«      }|S t        d«      ‚)z2Returns the fingerprint of the cached certificate.z"mTLS connection is not configured.)re   rŸ   r   )Úcached_certÚcert_objÚcached_cert_fingerprints      r   Úget_cached_cert_fingerprintr¦   ³  s0   € áÜ$ [Ó1ˆÜ"CÀHÓ"MÐð #Ð"ô Ð=Ó>Ð>r.   )%Ú__doc__r—   r”   rI   r
   rƒ   r   r9   r3   Úurllib.parser   r   Úgoogle.authr   r   rs   r‚   r   Ú_FAST_POLL_CYCLESÚ_FAST_POLL_INTERVALÚ_SLOW_POLL_INTERVALr5   ÚintÚ_SLOW_POLL_CYCLESr1   r   r   r-   r*   r2   rX   rl   re   rŒ   rŸ   r¡   r¦   © r.   r   ú<module>r°      så   ðñ .ã Û Û Û 	Û 	Û Û Û ß (ç 4ðFð ò0Ð ,ð XÐ ð Ð ØÐ ØÐ Ø€ñ ØÐ(Ð+>Ñ>Ñ?ÐCVÑVóÐ ð +Ð+Ð.?Ñ?ØÐÐ-Ñ-ñÐ ò
ò"ò(OòVHòV(ò@"ò5òp?òB"?òJ?ò60ó4#r.   