
    @wj6                         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mZm	Z	 ddl
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!y)z'Helpers for Agent Identity credentials.    N)quoteurlparse)environment_vars
exceptionszThe 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.pem2   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/dashboard-youtube/.venv/lib/python3.12/site-packages/google/auth/_agent_identity_utils.py_is_certificate_file_readyr   ;   sY    
 WWT]||BJJ':BJJN:  s   AA
 
AAc                     t         j                  j                  t        j                        } | syt         j
                  j                  t              }	 t         j
                  j                  |       }t         j
                  j                  |      }t         j
                  j                  ||g      |k(  }t        | |      S # t        $ r d}Y w xY w)a\  Gets the agent certificate path from the certificate config file.

    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.

    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.
    NF)r
   environgetr   GOOGLE_API_CERTIFICATE_CONFIGr   dirname_WELL_KNOWN_CERT_PATHabspath
commonpath
ValueError$_get_cert_path_with_optional_polling)cert_config_pathwell_known_dirabs_cert_pathabs_well_known_dirshould_polls        r   #get_agent_identity_certificate_pathr$   L   s     zz~~&6&T&TU WW__%:;N(89WW__^<GG 2MBC!" 	 00@+NN  s   A"C CCc                    d}d}t         D ]^  }	 t        |       }| yt        |      r|c S |s y|s"t        j                  d| dt
         d       d}t        j                   |       ` 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 zCertificate 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   warningswarn_TOTAL_TIMEOUTr   IOErrorr   KeyErrorr
   r   existsr   r   timesleepr   RefreshError7GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES)r   r#   has_logged_config_warninghas_logged_cert_warninginterval	cert_pathes          r   r   r   s   sk     !&#& .*	145EFI ))4   *4YK?ghvgw  xJ  K +/'6 	

8].` 
!
!	\SS
T U*	* 7  	MM[\][^ _^ ^ X. 	1ww~~./ ,Gs''EEF G==K<LL^`
 -1)!	1s>   BBB$B	D>B;;D>D97D9?5D99D>c                 2   ddl }t        | dd      5 }|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   Nrutf-8)encodingcert_configsworkloadr6   )jsonopenload
isinstancedictr   )r   r>   fcert_configr<   workload_configs         r   r(   r(      s      	g	6 #!iil# ,6k4+H'd  )3<(F$D  ot,?0R;''# #s   BBc                     t         j                  j                  t        j                  d      j                         dk(  } | ryddlm} |j                         }|du ryt               }|sy	 t        |d      5 }|j                         }ddd       t              S # 1 sw Y   xY w# t        $ r&}t        j                  d| d	| d
       Y d}~yd}~ww xY w)a1  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:
        The parsed certificate object if found and not opted out, otherwise None.
    truefalseNr   _mtls_helperFrbz2Failed to read agent identity certificate file at z: r&   )r
   r   r   r   r2   lowergoogle.auth.transportrJ   _check_use_client_cert_envr$   r?   readr   r)   r*   parse_certificate)is_opted_outrJ   env_overrider6   	cert_file
cert_bytesr7   s          r   (get_and_parse_agent_identity_certificaterU      s     	

TT	
 %'		   3::<Lu35I)T" 	*i")J	* Z((	* 	* @2aS QZ Z	
 s0   ,B( 8B	B( B%!B( (	C1CCc                 t    	 ddl m} |j                  |       S # t        $ r}t        t              |d}~ww xY w)zParses a PEM-encoded certificate.

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

    Returns:
        cryptography.x509.Certificate: The parsed certificate object.
    r   x509N)cryptographyrX   load_pem_x509_certificateImportErrorCRYPTOGRAPHY_NOT_FOUND_ERROR)rT   rX   r7   s      r   rP   rP     s9    ?%--j99 ?67Q>?s    	727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   rW   )ExtensionOIDFspiffeTN)rY   rX   cryptography.x509.oidr^   
extensionsget_extension_for_oidSUBJECT_ALTERNATIVE_NAMEExtensionNotFoundvalueget_values_for_typeUniformResourceIdentifierr   schemenetloc,_AGENT_IDENTITY_SPIFFE_TRUST_DOMAIN_PATTERNSrematchr[   r\   )
certrX   r^   exturisuri
parsed_uritrust_domainpatternr7   s
             r   _is_agent_identity_certificatert     s    ?%6	//7755C
 yy,,T-K-KL 	$C!#J  H,)00K $Gxx6#$		$  %% 		  ?67Q>?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   )serializationr:   =N)cryptography.hazmat.primitivesrv   public_bytesEncodingDERhashlibsha256digestbase64	b64encodedecoderstripr   r[   r\   )rm   rv   der_certfingerprintbase64_fingerprintunpadded_base64_fingerprintr7   s          r   !calculate_certificate_fingerprintr   C  s    ?@$$]%;%;%?%?@nnX.557 $--k:AA'J&8&?&?&D#011 ?67Q>?s   BB 	B.B))B.c                     t        |       }t        j                  j                  t        j
                  d      j                         dk(  }|r|syddlm} |j                         }|du ryy)a  Determines if a bound token should be requested.

    This is based on the GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES
    environment variable 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.
    rG   Fr   rI   T)
rt   r
   r   r   r   r2   rL   rM   rJ   rN   )rm   is_agent_certis_opted_inrJ   rR   s        r   should_request_bound_tokenr   ^  sk     348M


TT	
 %'		  k 3::<Lu    c                 L    | rt        |       }t        |      }|S t        d      )z2Returns the fingerprint of the cached certificate.z"mTLS connection is not configured.)rP   r   r   )cached_certcert_objcached_cert_fingerprints      r   get_cached_cert_fingerprintr     s0    $[1"CH"M #" =>>r   )"__doc__r   r|   r
   rk   r   r/   urllib.parser   r   r)   google.authr   r   r\   rj   r   _FAST_POLL_CYCLES_FAST_POLL_INTERVAL_SLOW_POLL_INTERVALr+   int_SLOW_POLL_CYCLESr'   r   r$   r   r(   rU   rP   rt   r   r   r    r   r   <module>r      s    .   	 	   (  4F 0 , X      (+>>?CVV  ++.??-- 
"$ONHV(D*)Z?""?J?6B#r   