o
    i@                     @   s  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Z	e
 Zedd  dZdZejejjdd	d
Zdd Zdd ZdCddZddedfddZedZejer^ejnejd zddlmZ e  ed W n ey   ed Y nw dd Z dd Z!dd  Z"dDd!d"Z#d#d$ Z$d%d& Z%d'Z&d(d)e&d*Z'd+gZ(d,d- Z)d.d/ Z*d0Z+e,e+d1d2Z-d3e+e.e-/d40d41d5d*Z2d6d7 Z3d8d9 Z4d:d; Z5d<d= Z6d>d? Z7d@dA Z8e9dBkre8  dS dS )Ea  MSAL Python Tester

Usage 1: Run it on the fly.
    python -m msal
    Note: We choose to not define a console script to avoid name conflict.

Usage 2: Build an all-in-one executable file for bug bash.
    shiv -e msal.__main__._main -o msaltest-on-os-name.pyz .
    Nzmsal_cache.binc                   C   s   t jrttdt  S d S )Nw)global_cacheZhas_state_changedopen_token_cache_filenamewrite	serialize r   r   D/home/app/Keep/.python/lib/python3.10/site-packages/msal/__main__.py<lambda>   s   r
   z$04b07795-8ddb-461a-bbee-02f9e1bf7b46z$04f0c124-f2bc-4f59-8241-bf6df9866bbdzhttps://example.com/endpointplaceholder)Zhttp_methodurlnoncec                 C   s   t tj| ddd d S )N   T)indent	sort_keys)printjsondumps)Zblobr   r   r	   
print_json      r   c                 C   s   t d| dvS )Nz9{} (N/n/F/f or empty means False, otherwise it is True): )NnFf )inputformat)messager   r   r	   _input_boolean"   s
   r   c                 C   s   t | j|d p|S )N)default)r   r   strip)r   r   r   r   r	   _input'   r   r!   zYour options:z    Your choice? Fc           	      C   s   | sJ d|rt | t| ddD ]\}}t d||| q|r't d 	 t|}zt|}d|  kr=t| krFn n| |d  W S W n tyX   |rV|rV| Y S Y nw q()Nzoptions must not be empty   )startz
    {}: {}z'    Or you can just type in your input.)r   	enumerater   r   intlen
ValueError)	optionsheaderfooteroption_rendereraccept_nonempty_stringioraw_datachoicer   r   r	   _select_options*   s(   r1   zEnable MSAL Python's DEBUG log?)level)load_dotenvz+Loaded environment variables from .env filezSpython-dotenv is not installed. You may need to set environment variables manually.c                  C   s*   t g dddd } d| v rtd| S )N)z$https://graph.microsoft.com/.defaultz%https://management.azure.com/.defaultz	User.ReadzUser.ReadBasic.Allz_Select a scope (multiple scopes can only be input by manually typing them, delimited by space):Tr)   r,   4https://pas.windows.net/CheckMyAccess/Linux/.defaultz9SSH Cert scope shall be tested by its dedicated functions)r1   splitr'   scopesr   r   r	   _input_scopesJ   s   	r9   c                 C   s*   |   }|rt|dd ddS td d S )Nc                 S   s   d | d | d S )Nz{}, came from {}usernameZaccount_source)r   ar   r   r	   r
   ]       z!_select_account.<locals>.<lambda>z0Account(s) already signed in inside MSAL Python:r+   r)   zRNo account available inside MSAL Python. Use other methods to acquire token first.)get_accountsr1   r   )appZaccountsr   r   r	   _select_accountX   s   rA   c                 C   sD   t | }|r t| jt |td|  rtdrtndd dS dS )zIacquire_token_silent() - with an account already signed into MSAL Python.!Bypass MSAL Python's token cache?Acquire AT POP via Broker?N)accountforce_refreshauth_scheme)rA   r   Zacquire_token_silent_with_errorr9   r   is_pop_supportedplaceholder_auth_schemer@   rD   r   r   r	   _acquire_token_silentc   s   rJ   c              
   C   s
  t | tjsJ |pt }tdddddddddgdd	 d
dd }|dkr+d}ntdgdd |  D  ddd}t |trE|d n|}| j|| j| j	t
tfv d|||pXi |  rbtdrbtndd}|rd|v r|di d}||krtd| t| |S )zUacquire_token_interactive() - User will be prompted if app opts to do select_account.NzRUnspecified. Proceed silently with a default account (if any), fallback to prompt.)valuedescriptionnonezEnone. Proceed silently with a default account (if any), or error out.Zselect_accountz.select_account. Prompt with an account picker.c                 S      | d S )NrL   r   r.   r   r   r	   r
   y       z,_acquire_token_interactive.<locals>.<lambda>zPrompt behavior?r>   rK   c                 S   s   g | ]}|d  qS )r:   r   ).0r<   r   r   r	   
<listcomp>   r=   z._acquire_token_interactive.<locals>.<listcomp>zlogin_hint? (If you have multiple signed-in sessions in browser/broker, and you specify a login_hint to match one of them, you will bypass the account picker.)Tr4   r:   i  rC   )Zparent_window_handleZenable_msa_passthroughportprompt
login_hintdatarF   Zid_token_claimsZpreferred_usernamez-Signed-in user "%s" does not match login_hint)
isinstancemsalPublicClientApplicationr9   r1   r?   dictZacquire_token_interactiveZCONSOLE_WINDOW_HANDLE	client_id
_AZURE_CLI_VISUAL_STUDIOrG   r   rH   getloggingwarningr   )r@   r8   rV   rT   rU   Zraw_login_hintresultZsigned_in_userr   r   r	   _acquire_token_interactivep   sP   

rb   c                 C   s$   t | jtdtdt d dS )zacquire_token_by_username_password() - See constraints here: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#constraints-for-ropcz
username: z
password: r7   N)r   Z"acquire_token_by_username_passwordr!   getpassr9   r@   r   r   r	   #_acquire_token_by_username_password   s   re   c                 C   sR   t | tjsJ | jt d}t|d  tj  t	d | 
|}t| dS )zNacquire_token_by_device_flow() - Note that this one does not go through brokerr7   r   zNAfter you completed the step above, press ENTER in this console to continue...N)rW   rX   rY   Zinitiate_device_flowr9   r   sysstdoutflushr   Zacquire_token_by_device_flowr   )r@   Zflowra   r   r   r	   _acquire_token_by_device_flow   s   

ri   aw  {"kty":"RSA", "n":"2tNr73xwcj6lH7bqRZrFzgSLj7OeLfbn8216uOMDHuaZ6TEUBDN8Uz0ve8jAlKsP9CQFCSVoSNovdE-fs7c15MxEGHjDcNKLWonznximj8pDGZQjVdfK-7mG6P6z-lgVcLuYu5JcWU_PeEqIKg5llOaz-qeQ4LEDS4T1D2qWRGpAra4rJX1-kmrWmX_XIamq30C9EIO0gGuT4rc2hJBWQ-4-FnE1NXmy125wfT3NdotAJGq5lMIfhjfglDbJCwhc8Oe17ORjO3FsB5CLuBRpYmP7Nzn66lRY3Fe11Xz8AEBl3anKFSJcTvlMnFtu3EpD-eiaHfTgRBU7CztGQqVbiQ", "e":"AQAB"}ssh-certkey1)
token_typeZkey_idZreq_cnfr5   c                 C   sf   t | tjsJ t| }|r-| jt|ttdd}t| |r/|	ddkr1t
d dS dS dS dS )zFAcquire an SSH Cert silently- This typically only works with Azure CLIrB   )rV   rE   rl   rj   zUnable to acquire an ssh-cert.N)rW   rX   rY   rA   Zacquire_token_silent_SSH_CERT_SCOPE_SSH_CERT_DATAr   r   r^   r_   error)r@   rD   ra   r   r   r	   _acquire_ssh_cert_silently   s   rp   c                 C   s>   t | tjsJ t| ttd}|ddkrtd dS dS )zLAcquire an SSH Cert interactively - This typically only works with Azure CLIr8   rV   rl   rj   zUnable to acquire an ssh-certN)	rW   rX   rY   rb   rm   rn   r^   r_   ro   )r@   ra   r   r   r	   _acquire_ssh_cert_interactive   s
   rr   z+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-AAAAAAAAsw)kidZxms_kslpopzutf-8=c                 C   sL   t | tjsJ dg}t| |td}t| |ddkr$td dS dS )zLAcquire a POP token interactively - This typically only works with Azure CLIz-6256c85f-0aad-4d50-b960-e6e9b21efe35/.defaultrq   rl   ru   zUnable to acquire a pop tokenN)	rW   rX   rY   rb   	_POP_DATAr   r^   r_   ro   )r@   Z	POP_SCOPEra   r   r   r	   _acquire_pop_token_interactive   s   rx   c                 C   s0   t | }|r| | td|d  dS dS )zoremove_account() - Invalidate account and/or token(s) from cache, so that acquire_token_silent() would be resetz@Account "{}" and/or its token(s) are signed out from MSAL Pythonr:   N)rA   Zremove_accountr   r   rI   r   r   r	   _remove_account   s
   
ry   c                 C   s&   t | tjsJ t| jt d dS )zKCCA.acquire_token_for_client() - Rerun this will get same token from cache.r7   N)rW   rX   ConfidentialClientApplicationr   Zacquire_token_for_clientr9   rd   r   r   r	   _acquire_token_for_client   s   r{   c                 C   s   t | tjsJ |   dS )zECCA.remove_tokens_for_client() - Run this to evict tokens from cache.N)rW   rX   rz   Zremove_tokens_for_clientrd   r   r   r	   _remove_tokens_for_client   s   r|   c                 C   s(   | j rdnd}td| t  dS )ZExitzjhttps://identitydivision.visualstudio.com/Engineering/_queries/query/79b3a352-a775-406f-87cd-a487c382a8ed/zXhttps://github.com/AzureAD/microsoft-authentication-library-for-python/issues/new/choosez2Bye. If you found a bug, please report it here: {}N)Z_enable_brokerr   r   rf   exit)r@   Zbug_linkr   r   r	   _exit   s   r~   c                  C   sv  t dtj tdddddtdgdd d	d
d} | d dkr?tjtr?zt	
ttd  W n	 ty>   Y nw ttddtdddddtdtdddgdd ddd}t|tohd|v }|rw|d rs|d swtd| o}td}|rtrtdnd
}tg dd dd!}|r|d"std#nd }|stjt|tr|d n||||||||t	d$	ntj|d |d |||t	d%}tgt|tjrtttttgng  tt g t|tjrt!t"gng  }	 t|t#g d&d d'd(}	z|	| W n> ty }
 zt$%d)|
 W Y d }
~
n*d }
~
w t&y!   t d* Y n t'y9 }
 zt$%d+|
 W Y d }
~
nd }
~
ww q),Nz4Welcome to the Msal Python {} Tester (Experimental)
emptyz<Start with an empty token cache. Suitable for one-off tests.)r0   descZreusezReuse the previous token cache {} (if any) which was created during last test app exit. Useful for testing acquire_token_silent() repeatedlyc                 S   rN   )Nr   r   rO   r   r   r	   r
      rP   z_main.<locals>.<lambda>z1What token cache state do you want to begin with?F)r+   r)   r,   r0   rz+Azure CLI (Correctly configured for MSA-PT))r[   namez/Visual Studio (Correctly configured for MSA-PT)z$95de633a-083e-42f5-b444-a4295d8e9314zAWhiteboard Services (Non MSA-PT app. Accepts AAD & MSA accounts.)Z	CLIENT_IDZCLIENT_SECRETzoA confidential client app (CCA) whose settings are defined in environment variables CLIENT_ID and CLIENT_SECRET)r[   client_secretr   c                 S   rN   )Nr   r   r;   r   r   r	   r
     rP   zUImpersonate this app (or you can type in the client_id of your own public client app)Tr   r[   zAYou need to set environment variables CLIENT_ID and CLIENT_SECRETzYEnable broker? (It will error out later if your app has not registered some redirect URI)zEnable PII in broker's log?)z(https://login.microsoftonline.com/commonz/https://login.microsoftonline.com/organizationsz;https://login.microsoftonline.com/microsoft.onmicrosoft.comz:https://login.microsoftonline.com/msidlab4.onmicrosoft.comz+https://login.microsoftonline.com/consumerszKInput authority (Note that MSA-PT apps would NOT use the /common authority)r4   z!https://login.microsoftonline.comzYou input an unusual authority which might fail the Instance Discovery. Now, do you want to perform Instance Discovery on your input authority?)	authorityinstance_discoveryZenable_broker_on_windowsZenable_broker_on_macZenable_broker_on_linuxZenable_broker_on_wslenable_pii_logtoken_cache)Zclient_credentialr   r   r   r   c                 S   s   | j S N)__doc__)r   r   r   r	   r
   O  s    zMSAL Python APIs:r>   zInvalid input: %sZAbortedz	Error: %s)(r   r   rX   __version__r1   r   ospathexistsr   Zdeserializer   readIOErrorr\   r]   getenvrW   rZ   r'   r   enable_debug_log
startswithrY   rz   rJ   rb   ri   rp   rr   rx   re   ry   r{   r|   r~   r_   ro   KeyboardInterrupt	Exception)Zcache_choiceZ
chosen_appZis_ccaZenable_brokerr   r   r   r@   Zmethods_to_be_testedfuncer   r   r	   _main   s   



r   __main__r   )NN):r   base64rc   r   r_   rf   r   atexitrX   r   ZSerializableTokenCacher   registerr\   r]   ZPopAuthSchemeZHTTP_GETrH   r   r   r!   strr1   r   basicConfigDEBUGINFOZdotenvr3   infoImportErrorr`   r9   rA   rJ   rb   re   ri   Z_JWK1rn   rm   rp   rr   Z_POP_KEY_IDr   Z_RAW_REQ_CNFurlsafe_b64encodeencodedecoderstriprw   rx   ry   r{   r|   r~   r   __name__r   r   r   r	   <module>   sn   @	


'
	
l
