
    xiG                        U d dl mZ d dlZd dlZd dlmZmZ d dlmZmZm	Z	 d dl
mZmZmZmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZmZ  ee      Zded<   er G d de      ZdZded<   dZ ded<    e!e       Z"ded<   dZ#ded<   dZ$ded<    G d d      Z%d)dZ&d*dZ'd+dZ(d,dZ)d-dZ*d.dZ+d/d Z,d0d!Z-	 	 	 	 	 	 	 	 	 	 d1d"Z.	 	 	 	 	 	 d2d#Z/	 	 	 	 	 	 	 	 	 	 d3d$Z0 ejb                  d%      Z2	 	 	 	 	 	 d4d&Z3	 	 	 	 	 	 	 	 d5d'Z4d6d(Z5y)7    )annotationsN)CallableMapping)datetime	timedeltatimezone)TYPE_CHECKINGAnyFinal	TypedDictcast)urlparse)config)StreamlitAuthError)
get_logger)AttrDictsecrets_singletonr   _LOGGERc                  "    e Zd ZU ded<   ded<   y)ProviderTokenPayloadstrproviderintexpN)__name__
__module____qualname____annotations__     _/var/www/html/chatbot/card-advisor-bot/venv/lib/python3.12/site-packages/streamlit/auth_util.pyr   r   !   s    r    r   i   MAX_COOKIE_BYTESz; Path=/; HttpOnlyCOOKIE_ATTRIBUTESCOOKIE_ATTR_SIZE2   SIGNING_OVERHEAD_SAFETY_BUFFER   SINGLE_BYTE_BASE64_SIZEc                  :    e Zd ZdZddZd	dZd
ddZddZddZy)	AuthCachezBSimple cache implementation for storing info required for Authlib.c                    i | _         y Ncacheselfs    r!   __init__zAuthCache.__init__4   s	    %'
r    c                8    | j                   j                  |      S r,   )r.   getr0   keys     r!   r3   zAuthCache.get7   s    zz~~c""r    Nc                "    || j                   |<   y r,   r-   )r0   r5   value
expires_ins       r!   setzAuthCache.set<   s    

3r    c                    | j                   S r,   r-   r/   s    r!   get_dictzAuthCache.get_dict?   s    zzr    c                <    | j                   j                  |d        y r,   )r.   popr4   s     r!   deletezAuthCache.deleteB   s    

sD!r    )returnNone)r5   r   r?   r
   r,   )r5   r   r7   r
   r8   z
int | Noner?   r@   )r?   dict[str, Any])r5   r   r?   r@   )	r   r   r   __doc__r1   r3   r9   r;   r>   r   r    r!   r*   r*   1   s    L(#
 "r    r*   c                     	 ddl } | j                  }t        t        t        |j                  d                  }|dk  ry	 y# t        t        f$ r Y yw xY w)zCheck if Authlib is installed.r   N.)         FT)authlib__version__tuplemapr   splitImportErrorModuleNotFoundError)rH   authlib_versionauthlib_version_tuples      r!   is_authlib_installedrQ   F   sa    	!-- %c#/D/DS/I&J K 9, -  ,- s   =A AAc                     t        j                  d      } t        j                         r)t        j                  d      }|r|j	                  d|       } | S )zEGet the cookie signing secret from the configuration or secrets.toml.zserver.cookieSecretauthcookie_secret)r   
get_optionr   load_if_toml_existsr3   )signing_secretauth_sections     r!   get_signing_secretrY   U   sJ     ++,ABN,,.(,,V4)--o~NNr    c            	         t        i       } t        j                         r)t        dt        j                  dt        i                   } | S )z+Get the 'auth' section of the secrets.toml.r   rS   )r   r   rV   r   r3   )rX   s    r!   get_secrets_auth_sectionr[   _   s;    B<L,,.J(9(=(=fhrl(STr    c                     t               } | j                  d      }t        |t              r|g}n+t        |t              r|D cg c]  }t        |       }}ng S t        |      ddhz
  rt        d      |S c c}w )zGet the expose_tokens configuration from secrets.toml.

    Returns a list of token types to expose. Accepts both string and list formats:
    - expose_tokens = "id" -> ["id"]
    - expose_tokens = ["id", "access"] -> ["id", "access"]
    expose_tokensidaccesszHInvalid expose_tokens configuration. Only 'id' and 'access' are allowed.)r[   r3   
isinstancer   listr9   r   )rX   r]   restokens       r!   get_expose_tokens_configrd   h   s     ,-L $$_5M-%o	M4	('45es5z55	
3x4"" V
 	
 J 6s   A8c                    d| vry| d   }d|v r.|j                  dt        t        j                  d                  }	 t	        |      }|j                         S # t
        $ r t        d| d      w xY w)zJGet the redirect_uri from auth_section - filling in port number if needed.redirect_uriNz{port}zserver.portzInvalid redirect_uri: ". Please check your configuration.)replacer   r   rU   r   
ValueErrorr   geturl)rX   rf   redirect_uri_parseds      r!   get_redirect_urirl      s     \)$^4L<#++c&++M:;

&|4 %%''  
 $\N2TU
 	

s   A A2c                   	 ddl m} ddi}| t	        j
                  t        j                        t        d      z   d	}|j                  ||t                     }|j                  d
      S # t        $ r t        d      dw xY w)zAReturns a signed JWT token with the provider and expiration time.r   )jwtcTo use authentication features, you need to install Authlib>=1.3.2, e.g. via `pip install Authlib`.NalgHS256rG   )minutes)r   r   zlatin-1)authlib.josern   rM   r   r   nowr   utcr   encoderY   decode)r   rn   headerpayloadprovider_tokens        r!   encode_provider_tokenr{      s    $ WF||HLL)Ia,@@G  JJvw8J8LMN  ++   u
	s   A+ +Bc                   	 ddl m}m}m} ddiddid}	 |j                  | t               |      }|j                          t        d
|      S # t        $ r t        d      dw xY w# |$ r}t        d	|       dd}~ww xY w)z-Decode the JWT token and validate the claims.r   )	JoseError	JWTClaimsrn   ro   N	essentialT)r   r   )claims_optionszError decoding provider token: r   )
rs   r}   r~   rn   rM   r   rw   rY   validater   )rz   r}   r~   rn   claim_optionsry   es          r!   decode_provider_tokenr      s    :: )$/k4=PQMR ZZ.0 ( 
 	 &00!   u
	  R #B1#!FGTQRs"   
A ,A' A$'B ,A;;B c           	        i }| j                  d      r| j                  d      |d<   | j                  d      r| j                  d      |d<   | j                  d      r| j                  d      |d<   | j                  d      r6t        d| j                  dt        i                   j                         |d<   | j                  d      r| j                  d      |d<   |S )zKGenerate a default provider section for the 'auth' section of secrets.toml.	client_idclient_secretserver_metadata_urlclient_kwargsr   r]   )r3   r   r   to_dict)rX   default_provider_sections     r!   !generate_default_provider_sectionr      s    !$0<0@0@0M -(4@4D4D_4U 1-.:F:J:J!;
 !67 (48(((2,G5

') 	!1 (4@4D4D_4U 1##r    c                    t        j                  |      } |||      }t        |      dz   t        |      z   t        z   }|t        kD  r%t
        j                  d|       t        | |||       y | ||       y)a[  Set a cookie, splitting into multiple cookies if necessary.

    Args:
        set_single_cookie_fn: Function to set a single cookie (cookie_name, value)
        create_signed_value_fn: Function to create a signed cookie value (cookie_name, value)
        cookie_name: Name of the cookie
        value: Dictionary value to serialize and store
    rE   zNCookie size (%d bytes) exceeds browser limit. Splitting into multiple cookies.N)jsondumpslenr$   r"   r   debug_set_split_cookie)set_single_cookie_fncreate_signed_value_fncookie_namer7   serialized_cookie_valuesigned_valueactual_cookie_sizes          r!   set_cookie_with_chunksr      s     #jj/ *+7NOL [)A-L0AADTT ,,\	
 	 "#		
 	[*ABr    c                <    d} | ||      }t        |      t        z
  S )a  Calculate the server's signing overhead by measuring the size difference.

    This empirically measures the overhead added by the signing function (e.g., Tornado's
    create_signed_value) by signing a minimal test value and computing the difference.

    Args:
        create_signed_value_fn: Function to create a signed cookie value
        cookie_name: Name of the cookie (affects overhead due to length prefix)

    Returns
    -------
        The number of bytes added by signing (excluding the base64-encoded value)
    x)r   r(   )r   r   
test_valuesigneds       r!   _calculate_signing_overheadr      s%    " J#K<Fv;000r    c                   t        ||      t        z   }t        t        |      z
  dz
  t        z
  }||z
  }|t
        k  rt        d      |dz  dz  }g }t        dt        |      |      D ]  }	||	|	|z    }
|j                  |
        t        |      dk(  r | ||d          y | |dt        |              t        t        |            D ]  }	| d|	dz    } | |||	           t        j                  d	|t        |             y)
a  Split a large cookie value into multiple smaller cookies.

    The main cookie always exists and either contains the whole value or the chunk count.
    Additional chunks are stored as cookie_name_1, cookie_name_2, etc.

    Args:
        set_single_cookie_fn: Function to set a single cookie (cookie_name, value)
        create_signed_value_fn: Function to create a signed cookie value
        cookie_name: Name of the cookie
        value: Serialized string value to split and store
    rE   z0Not enough space available for the signed value.rF   r'   r   Nzchunks-_z Split cookie '%s' into %d chunks)r   r&   r"   r   r$   r(   r   rangeappendr   info)r   r   r   r7   signing_overheadavailable_for_signed_valueavailable_for_base64_value
chunk_sizechunksichunk
chunk_names               r!   r   r     s;   & 	$$:KH
(	)  	3{++a/2BB 
 "<>N!N "$;; !STT -q0Q6JF1c%j*- a!j.)e 6{a[&)4 F}&=> 3v; 4#}Aa!eW-
Z34 LL*Fr    s   chunks-(\d+)c                    | |      }||S t         j                  |      }||S 	 t        |j                  d            }g }t        |      D ]C  }| d|dz    } | |      }|t        j                  d|dz   |        y|j                  |       E dj                  |      }	|	S # t        t
        f$ r t        j                  d|       Y yw xY w)a  Get a cookie, reconstructing from chunks if it was split.

    If a count cookie exists, the main cookie contains the first chunk,
    and additional chunks are in cookie_name_1, cookie_name_2, etc.
    If no count cookie exists, the main cookie contains the entire value.

    Args:
        get_single_cookie_fn: Function to get a single cookie (cookie_name) -> bytes | None
        cookie_name: Name of the cookie

    Returns
    -------
        Cookie value as bytes, or None if not found
    NrE   z#Invalid chunk count for cookie '%s'r   z Missing chunk %d for cookie '%s'r    )_chunks_regexmatchr   groupri   	TypeErrorr   	exceptionr   r   join)
get_single_cookie_fnr   cookie_valuer   chunk_countr   r   r   chunk_valuereconstructed_values
             r!   get_cookie_with_chunksr   S  s    $ (4L-E}%++a.) F; ##}Aa!eW-
*:6@!a%Uk"# ((6*! 	" ?Ms   B' '%CCc                     | |      } ||       |yt         j                  |      }|y	 t        |j                  d            }t	        d|dz         D ]  } || d|         y# t
        t        f$ r Y yw xY w)a  Clear a cookie and any associated chunk cookies.

    The main cookie always exists. If there are chunks, also clear
    cookie_name_1, cookie_name_2, etc., and the count cookie.

    Args:
        get_single_cookie_fn: Function to get a single cookie (cookie_name) -> bytes | None
        clear_single_cookie_fn: Function to clear a single cookie (cookie_name)
        cookie_name: Name of the cookie
    NrE   r   )r   r   r   r   r   ri   r   )r   clear_single_cookie_fnr   r   r   r   r   s          r!   clear_cookie_and_chunksr     s     (4L;'-E}%++a.)q+/* 	9A"k]!A3#78	9	"  	s   ;A) )A;:A;c                8   t        j                         st        d      t        j                  d      }|t        d      d|vrt        d      d|vrt        d      |j                  |       }d| v rt        d	|  d
      || dk(  rt	        |      }|| dk(  rt        d      t        d|  d      t        |t              st        d|  d      g d}|D cg c]	  }||vs| }}|r&| dk(  rt        d| d      t        d|  d| d      yc c}w )z[Validate the general auth credentials and auth credentials for the given
    provider.
    zTo use authentication features you need to configure credentials for at
            least one authentication provider in `.streamlit/secrets.toml`.rS   Nrf   zAuthentication credentials in `.streamlit/secrets.toml` are missing the
            "redirect_uri" key. Please check your configuration.rT   zAuthentication credentials in `.streamlit/secrets.toml` are missing the
            "cookie_secret" key. Please check your configuration.r   zAuth provider name "zI" contains an underscore. Please use a provider name without underscores.defaultzAuthentication credentials in `.streamlit/secrets.toml` are missing for
                the default authentication provider. Please check your configuration.zeAuthentication credentials in `.streamlit/secrets.toml` are missing for the authentication provider "z#". Please check your configuration.zYAuthentication credentials in `.streamlit/secrets.toml` for the authentication provider "z6" must be valid TOML. Please check your configuration.)r   r   r   zAuthentication credentials in `.streamlit/secrets.toml` for the default authentication provider are missing the following keys: rg   z"" are missing the following keys: )r   rV   r   r3   r   r`   r   )r   rX   provider_sectionrequired_keysr5   missing_keyss         r!   validate_auth_credentialsr     s    002 O
 	

 %((0L O
 	
 \) D
 	
 l* E
 	

 $''1 h "8* -> ?
 	

 H	$9<\Jy $Y  !,,4: 6
 	
 &0 ((0z 2"#
 	
 JM#0PCC?O4OCPLPy $S. BD 
 !((0z1Sn>@
 	
  Qs   	D(D)r?   bool)r?   r   )r?   r   )r?   z	list[str])rX   r   r?   z
str | None)r   r   r?   r   )rz   r   r?   r   )rX   r   r?   rA   )
r   Callable[[str, str], None]r   Callable[[str, str], bytes]r   r   r7   rA   r?   r@   )r   r   r   r   r?   r   )
r   r   r   r   r   r   r7   r   r?   r@   )r   Callable[[str], bytes | None]r   r   r?   zbytes | None)r   r   r   zCallable[[str], None]r   r   r?   r@   )r   r   r?   r@   )6
__future__r   r   recollections.abcr   r   r   r   r   typingr	   r
   r   r   r   urllib.parser   	streamlitr   streamlit.errorsr   streamlit.loggerr   streamlit.runtime.secretsr   r   r   r   r   r   r"   r#   r   r$   r&   r(   r*   rQ   rY   r[   rd   rl   r{   r   r   r   r   r   compiler   r   r   r   r   r    r!   <module>r      s   #  	 - 2 2 = = !  / ' AH% %y 
  % / 5 //0 % 0 )+  *!"  "" "*2(,,&1.$(#C4#C7#C #C 	#C
 
#CL1711 	1,<4<7< < 	<
 
<~ 

+,-7-- -` 7 1    
	 FH
r    