
    @wj]                        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m	Z	m
Z
mZ ddlmZ erddlZddlZ ej"                  e      Z ej(                  d      Z ej(                  d      Z ej(                  d	      Z ej(                  d      Zd
Z G d de	      Z G d de      Z G d dej:                        Z G d de      Zd Z d Z! G d de      Z"de#fdZ$de#de#fdZ%de#de#fdZ&de#de#de#fdZ'y)z2Utilities for Regional Access Boundary management.    N)
NamedTupleOptionalTYPE_CHECKING)_helpers   )hours      )minuteszx-allowed-locationsc                       e Zd ZU dZee   ed<   eej                     ed<   eej                     ed<   ej                  ed<   y)_RegionalAccessBoundaryDataa  Data container for a Regional Access Boundary snapshot.

    Attributes:
        encoded_locations (Optional[str]): The encoded Regional Access Boundary string.
        expiry (Optional[datetime.datetime]): The hard expiration time of the boundary data.
        cooldown_expiry (Optional[datetime.datetime]): The time until which further lookups are skipped.
        cooldown_duration (datetime.timedelta): The current duration for the exponential cooldown.
    encoded_locationsexpirycooldown_expirycooldown_durationN)	__name__
__module____qualname____doc__r   str__annotations__datetime	timedelta     i/root/dashboard-youtube/.venv/lib/python3.12/site-packages/google/auth/_regional_access_boundary_utils.pyr   r   5   sA      }$X&&''h//00)))r   r   c                   `    e Zd ZdZd Zd Zd Zd Zd ZddZ	d	 Z
d
 Zd Zd Zd Zd Zd Zy)_RegionalAccessBoundaryManagerzManages the Regional Access Boundary state and its background refresh.

    The actual data is held in an immutable `_RegionalAccessBoundaryData` object
    and is swapped atomically to ensure thread-safe, lock-free reads.
    c                     t        d d d t              | _        t               | _        t        j                         | _        d| _        y )Nr   r   r   r   F)	r   )DEFAULT_REGIONAL_ACCESS_BOUNDARY_COOLDOWN_data%_RegionalAccessBoundaryRefreshManagerrefresh_manager	threadingLock_update_lock-_use_blocking_regional_access_boundary_lookupselfs    r   __init__z'_RegionalAccessBoundaryManager.__init__L   s?    0" G	

  EF%NN,=B:r   c                 D    | j                   j                         }d|d<   |S )z9Pickle helper that serializes the _update_lock attribute.Nr'   __dict__copyr*   states     r   __getstate__z+_RegionalAccessBoundaryManager.__getstate__W   s#    ""$ $nr   c                 l    | j                   j                  |       t        j                         | _        y)z;Pickle helper that deserializes the _update_lock attribute.N)r.   updater%   r&   r'   r0   s     r   __setstate__z+_RegionalAccessBoundaryManager.__setstate__]   s#    U#%NN,r   c                     t        |t              st        S | j                  |j                  k(  xr | j                  |j                  k(  S )z!Checks if two managers are equal.)
isinstancer   NotImplementedr"   r(   )r*   others     r   __eq__z%_RegionalAccessBoundaryManager.__eq__b   sF    %!?@!!JJ%++% CBBBBC	
r   c                     d| _         y)zEnables blocking Regional Access Boundary lookup.

        When enabled, the Regional Access Boundary lookup will be performed
        synchronously in the calling thread instead of asynchronously in a
        background thread.
        TN)r(   r)   s    r   enable_blocking_lookupz5_RegionalAccessBoundaryManager.enable_blocking_lookupl   s     >B:r   Nc                 <    |sd}t        ||dt              | _        y)aS  Manually sets the regional access boundary to the client provided initial values.

        Args:
            encoded_locations (Optional[str]): The encoded locations string.
            expiry (Optional[datetime.datetime]): The expiry time for the boundary.
                If encoded_locations is not provided, expiry is ignored.
        Nr    )r   r!   r"   )r*   r   r   s      r   $set_initial_regional_access_boundaryzC_RegionalAccessBoundaryManager.set_initial_regional_access_boundaryu   s$     !F0/ G	

r   c                     | j                   }|j                  rA|j                  5t        j                         |j                  k  r|j                  |t
        <   y|j                  t
        d       y)a\  Applies the Regional Access Boundary header to the provided dictionary.

        If the boundary is valid, the 'x-allowed-locations' header is added
        or updated. Otherwise, the header is removed to ensure no stale
        data is sent.

        Args:
            headers (MutableMapping[str, str]): The headers dictionary to update.
        N)r"   r   r   r   utcnow _REGIONAL_ACCESS_BOUNDARY_HEADERpop)r*   headersrab_datas      r   apply_headersz,_RegionalAccessBoundaryManager.apply_headers   sR     ::%%OO'HOO,=,O8@8R8RG45KK8$?r   c                     | j                   }|j                  r5|j                  r)t        j                         |j                  t
        z
  k  ry|j                  r"t        j                         |j                  k  ryy)zChecks if the Regional Access Boundary data needs a refresh and is not in cooldown.

        Returns:
            bool: True if a refresh is required, False otherwise.
        FT)r"   r   r   r   r@   *REGIONAL_ACCESS_BOUNDARY_REFRESH_THRESHOLDr   )r*   rD   s     r   _should_refreshz._RegionalAccessBoundaryManager._should_refresh   sf     :: &&!!KKM  ##(9H<T<T(Tr   c                     | j                         sy| j                  r| j                  ||       y| j                  j	                  |||        y)a  Starts a background thread to refresh the Regional Access Boundary if needed.

        Args:
            credentials (google.auth.credentials.Credentials): The credentials to refresh.
            request (google.auth.transport.Request): The object used to make HTTP requests.
        N)rH   r(   start_blocking_refreshr$   start_refreshr*   credentialsrequests      r   maybe_start_refreshz2_RegionalAccessBoundaryManager.maybe_start_refresh   sF     ##% ==''W=  ..{GTJr   c                    K   | j                         sy| j                  r| j                  ||       d{    y| j                  j	                  |||        y7 #w)a  Starts a background refresh or performs a blocking refresh asynchronously.

        Args:
            credentials (google.auth.credentials.Credentials): The credentials to refresh.
            request (google.auth.aio.transport.Request): The object used to make HTTP requests.
        N)rH   r(   start_blocking_refresh_asyncr$   rK   rL   s      r   maybe_start_refresh_asyncz8_RegionalAccessBoundaryManager.maybe_start_refresh_async   sV      ##% ==33KIII  ..{GTJ Js   3AA$Ac                 :   t        j                  |j                        r't        j	                  d       | j                  d       y	 |j                  |d      }| j                  |       y# t        $ r$}t        j	                  d|d       d}Y d}~:d}~ww xY w)a  Initiates a blocking lookup of the Regional Access Boundary.

        If the lookup raises an exception, it is caught and logged as a warning,
        and the lookup is treated as a failure (entering cooldown). Exceptions
        are not propagated to the caller.

        Args:
            credentials (google.auth.credentials.Credentials): The credentials to refresh.
            request (google.auth.transport.Request): The object used to make HTTP requests.
        zPBlocking Regional Access Boundary lookup is not supported for async credentials.NT	fail_fastz@Blocking Regional Access Boundary lookup raised an exception: %sexc_info)inspectiscoroutinefunction _lookup_regional_access_boundary_LOGGERdebug%process_regional_access_boundary_info	Exceptionr*   rM   rN   regional_access_boundary_infoes        r   rJ   z5_RegionalAccessBoundaryManager.start_blocking_refresh   s     &&{'S'STMMb 66t<	1
 <<WPT<U * 	223PQ  	1MMR  
 -1)	1s   A- -	B6BBc                    K   	 |j                  |d       d{   }| j	                  |       y7 # t        $ r$}t        j                  d|d       d}Y d}~<d}~ww xY ww)a  Initiates a blocking lookup of the Regional Access Boundary asynchronously.

        If the lookup raises an exception, it is caught and logged as a warning,
        and the lookup is treated as a failure (entering cooldown). Exceptions
        are not propagated to the caller.

        Args:
            credentials (google.auth.credentials.Credentials): The credentials to refresh.
            request (google.auth.aio.transport.Request): The object used to make HTTP requests.
        TrT   Nz7Regional Access Boundary lookup raised an exception: %srV   )rZ   r^   r[   r\   r]   r_   s        r   rQ   z;_RegionalAccessBoundaryManager.start_blocking_refresh_async   sy     	1
 "BBt C   * 	223PQ  	1MMI  
 -1)	1s6   A#3 13 A#3 	A AA#A  A#c                 n   | j                   5  | j                  }|rS|j                  d      }t        |t	        j
                         t        z   dt              }t        j                  d       nt        j                  d       t	        j
                         |j                  z   }t        |j                  dz  t              }|j                  r&t	        j
                         |j                  kD  rd}d}n|j                  }|j                  }t        ||||      }|| _        ddd       y# 1 sw Y   yxY w)zProcesses the regional access boundary info and updates the state.

        Args:
            regional_access_boundary_info (Optional[Mapping[str, str]]): The regional access
                boundary info to process.
        encodedLocationsNr    z+Regional Access Boundary lookup successful.z:Regional Access Boundary lookup failed. Entering cooldown.   )r'   r"   getr   r   r@   $DEFAULT_REGIONAL_ACCESS_BOUNDARY_TTLr!   r[   r\   r   min%MAX_REGIONAL_ACCESS_BOUNDARY_COOLDOWNr   r   )	r*   r`   current_datar   updated_datanext_cooldown_expirynext_cooldown_durationnext_encoded_locationsnext_expirys	            r   r]   zD_RegionalAccessBoundaryManager.process_regional_access_boundary_info  s"     /	&::L,$A$E$E&%!  ;&7#??,/SS$(&O	  KL P
 OO%(F(FF % *- 22Q69*&  &&8??+<|?R?R+R-1*"&K-9-K-K*"."5"5K:&<&$8&<	  &DJ_/	& /	& /	&s   DD++D4)NN)r   r   r   r   r+   r2   r5   r:   r<   r>   rE   rH   rO   rR   rJ   rQ   r]   r   r   r   r   r   E   sP    	C-

B
$@&.K K "RHR<6&r   r   c                   6     e Zd ZdZ	 	 	 	 	 	 d fdZd Z xZS )$_RegionalAccessBoundaryRefreshThreadzAThread for background refreshing of the Regional Access Boundary.c                 Z    t         |           d| _        || _        || _        || _        y )NT)superr+   daemon_credentials_request_rab_manager)r*   rM   rN   rab_manager	__class__s       r   r+   z-_RegionalAccessBoundaryRefreshThread.__init__O  s.     	''r   c                     	 | j                   j                  | j                        }| j                  j                  |       y# t        $ r$}t        j                  d|d       d}Y d}~Dd}~ww xY w)a  
        Performs the Regional Access Boundary lookup and updates the state.

        This method is run in a separate thread. It delegates the actual lookup
        to the credentials object's `_lookup_regional_access_boundary` method.
        Based on the lookup's outcome (success or complete failure after retries),
        it updates the cached Regional Access Boundary information,
        its expiry, its cooldown expiry, and its exponential cooldown duration.
        DAsynchronous Regional Access Boundary lookup raised an exception: %sTrV   N)ru   rZ   rv   r^   r[   r\   rw   r]   )r*   r`   ra   s      r   runz(_RegionalAccessBoundaryRefreshThread.run[  sq    
	1!!BB4==Q * 	??)	
  	1MMV  
 -1)	1s   %A 	A0A++A0)rM   z=google.auth.credentials.CredentialsWithRegionalAccessBoundaryrN   zgoogle.auth.transport.Requestrx   r   )r   r   r   r   r+   r|   __classcell__)ry   s   @r   rq   rq   L  s,    K
(T
( 1
( 6	
(
r   rq   c                   (    e Zd ZdZd Zd Zd Zd Zy)r#   zKManages a thread for background refreshing of the Regional Access Boundary.c                 D    t        j                         | _        d | _        y N)r%   r&   _lock_workerr)   s    r   r+   z._RegionalAccessBoundaryRefreshManager.__init__|  s    ^^%
r   c                 N    | j                   j                         }d|d<   d|d<   |S )z?Pickle helper that serializes the _lock and _worker attributes.Nr   r   r-   r0   s     r   r2   z2_RegionalAccessBoundaryRefreshManager.__getstate__  s,    ""$gir   c                 z    | j                   j                  |       t        j                         | _        d| _        y)zAPickle helper that deserializes the _lock and _worker attributes.N)r.   r4   r%   r&   r   r   r0   s     r   r5   z2_RegionalAccessBoundaryRefreshManager.__setstate__  s)    U#^^%
r   c                    | j                   5  | j                  r$| j                  j                         r
	 ddd       y	 t        j                  |      }t        |||      | _        | j                  j                          ddd       y# t
        $ r(}t        j                  d|       Y d}~ddd       yd}~ww xY w# 1 sw Y   yxY w)a  
        Starts a background thread to refresh the Regional Access Boundary if one is not already running.

        Args:
            credentials (CredentialsWithRegionalAccessBoundary): The credentials
                to refresh.
            request (google.auth.transport.Request): The object used to make
                HTTP requests.
            rab_manager (_RegionalAccessBoundaryManager): The manager container to update.
        NzCould not deepcopy transport for background RAB refresh. Skipping background refresh to avoid thread safety issues. Exception: %s)
r   r   is_aliver/   deepcopyr^   r[   r\   rq   start)r*   rM   rN   rx   copied_requestra   s         r   rK   z3_RegionalAccessBoundaryRefreshManager.start_refresh  s     ZZ 	!|| 5 5 7	! 	!
	!%w!7 @^[DL LL '	! 	!  $ 	 	! 	!	! 	!s4   (B=B	,B=		B:B5(B=5B::B==CNr   r   r   r   r+   r2   r5   rK   r   r   r   r#   r#   y  s    U!r   r#   c                    t        | t        j                        }|r| j                  n| }t	        |d      s| |dfS |j                         }||u}|r.t        j                  |g| j                  i | j                  }n|}|||fS )ak  Unwraps a request callable, clones the transport, and returns the new callable.

    Args:
        request: The original request callable (e.g. functools.partial or raw Request).

    Returns:
        Tuple[Callable, Any, bool]: A tuple containing the new lookup callable, the
            underlying request object, and a boolean indicating if it was cloned.
    _cloneF)r7   	functoolspartialfunchasattrr   argskeywords)rN   
is_partialbase_callablecloned_callable	is_clonednew_requests         r   _prepare_async_lookup_callabler     s     GY%6%67J$.GLLGM=(+u,,#**,O}4I''
%ll
.5.>.>
 &22r   c                   K   |rt        | d      syd}	 | j                         }t        j                  |      x}r| d{    yy7 # t        $ r)}|rdnd}t
        j                  d||d       Y d}~yd}~ww xY ww)	zSafely closes the underlying cloned request transport, if applicable.

    Args:
        lookup_request (Any): The request object/transport to close.
        is_cloned (bool): Whether the request was actually cloned.
    closeNFz asynchronous  z5Failed to cleanly close cloned%srequest transport: %sTrV   )r   r   rX   isawaitabler^   r[   r\   )lookup_requestr   is_async
maybe_corora   adapter_types         r   _close_cloned_requestr     s      GNG<H
#))+
**:6686 7 
+3'C	 	 	
 	

s@   A?,A
 AA
 A?A
 
	A<A72A?7A<<A?c                   (    e Zd ZdZd Zd Zd Zd Zy)*_AsyncRegionalAccessBoundaryRefreshManagerzXManages a task for background refreshing of the Regional Access Boundary in async flows.c                 D    t        j                         | _        d | _        y r   )r%   r&   r   _worker_taskr)   s    r   r+   z3_AsyncRegionalAccessBoundaryRefreshManager.__init__  s    ^^%
 r   c                 N    | j                   j                         }d|d<   d|d<   |S )zbPickle helper that excludes the un-picklable _lock and _worker_task attributes from serialization.Nr   r   r-   r0   s     r   r2   z7_AsyncRegionalAccessBoundaryRefreshManager.__getstate__  s,    ""$g $nr   c                 z    | j                   j                  |       t        j                         | _        d| _        y)z[Pickle helper that restores state and re-initializes the _lock and _worker_task attributes.N)r.   r4   r%   r&   r   r   r0   s     r   r5   z7_AsyncRegionalAccessBoundaryRefreshManager.__setstate__  s*    U#^^%
 r   c                   	 | j                   5  | j                  r$| j                  j                         s
	 ddd       y	 t        |      \  		fd} |       }	 t        j                  |      | _        	 ddd       y# t        $ r;}t
        j                  d|d       j                  d       Y d}~ddd       yd}~ww xY w# t        $ ra |j                          	 t        j                         j                  t        	             n# t        $ r Y nw xY wj                  d        w xY w# 1 sw Y   yxY w)a  
        Starts a background task to refresh the Regional Access Boundary if one is not already running.

        Args:
            credentials (CredentialsWithRegionalAccessBoundary): The credentials
                to refresh.
            request (google.auth.aio.transport.Request): The object used to make
                HTTP requests.
            rab_manager (_RegionalAccessBoundaryManager): The manager container to update.
        NzMSynchronous cloning of request for Regional Access Boundary lookup failed: %sTrV   c                  (  K   	 j                         d {   } t	               d {    j                  |        y 7 *# t        $ r$}t        j                  d|d       d } Y d }~Pd }~ww xY w7 H# t	               d {  7   w xY ww)Nr{   TrV   )rZ   r^   r[   r\   r   r]   )r`   ra   rM   r   lookup_callabler   rx   s     r   r   zI_AsyncRegionalAccessBoundaryRefreshManager.start_refresh.<locals>._worker  s     K)JJ+  2 0	JJJAA1 ! 9MM^!% " 
 5919 K/	JJJse   BA AA BA6BA 	A3A.)A8 .A33A8 6B8BB	BB)r   r   doner   r^   r[   r\   r]   asynciocreate_taskr   get_running_loopr   RuntimeError)
r*   rM   rN   rx   ra   r   coror   r   r   s
    ` `   @@@r   rK   z8_AsyncRegionalAccessBoundaryRefreshManager.start_refresh  sE    ZZ 6	  ):):)?)?)A6	 6	

 37;	#" * 9D$+$7$7$=!W6	 6	  c!  
 AA$G%6	 6	B  


,,.::-niH $ AA$G
Y6	 6	sk   (D<BD<$C	C)C:D<CD<D9)-DD9	D# D9"D##D99D<<ENr   r   r   r   r   r     s    b!!Ar   r   returnc                      ddl m}  t        | d      r#| j                         rdt        j
                   S dt        j
                   S )zDynamically determines the domain for IAM credentials based on active mTLS configuration.

    Returns:
        str: The dynamic domain string.
    r   _mtls_helpercheck_use_client_certziamcredentials.mtls.ziamcredentials.)google.auth.transportr   r   r   r   DEFAULT_UNIVERSE_DOMAINr   s    r   _get_domainr   <  sH     3 	56..0%h&F&F%GHH !A!A BCCr   service_account_emailc                 $    dt                d|  dS )zBuilds the Regional Access Boundary lookup URL for service accounts.

    Args:
        service_account_email: The service account email.

    Returns:
        str: The complete lookup URL.
    https://z/v1/projects/-/serviceAccounts//allowedLocationsr   )r   s    r    get_service_account_rab_endpointr   M  s     km_$CDYCZZkllr   pool_idc                 $    dt                d|  dS )zBuilds the Regional Access Boundary lookup URL for workforce pools.

    Args:
        pool_id: The workforce pool ID.

    Returns:
        str: The complete lookup URL.
    r   z$/v1/locations/global/workforcePools/r   r   )r   s    r   get_workforce_pool_rab_endpointr   Y  s     km_$H	Qbccr   project_numberc                 *    dt                d|  d| dS )zBuilds the Regional Access Boundary lookup URL for workload identity pools.

    Args:
        project_number: The Google Cloud project number.
        pool_id: The workload identity pool ID.

    Returns:
        str: The complete lookup URL.
    r   z/v1/projects/z(/locations/global/workloadIdentityPools/r   r   )r   r   s     r   'get_workload_identity_pool_rab_endpointr   e  s0     km_M.1AAijqir  sD  E  Er   )(r   r   r/   r   r   rX   loggingr%   typingr   r   r   google.authr   google.auth.credentialsgoogler   	getLoggerr   r[   r   rg   rG   r!   ri   rA   r   objectr   Threadrq   r#   r   r   r   r   r   r   r   r   r   r   r   <module>r      sM   9        6 6  " 
'

H
% (:x'9'9'B $ .@X-?-?a-H * -?H,>,>r,J ) );(:(:(C % $9  ** * D&V D&N*
9+;+; *
Z2!F 2!j3:
2U UpDS D"	mC 	mC 	m	dS 	dS 	d
EC 
E# 
ERU 
Er   