
    9i@                     ,   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j                         Z ej                  d        dZdZ ej                  ej                  j                   dd	      Zd
 Zd Zd0dZddedfdZ ed      Z ej0                  erej2                  nej4                         	 ddlmZ  e         ej:                  d       d Z d Z!d Z"d1dZ#d Z$d Z%dZ&dde&dZ'd gZ(d! Z)d" Z*d#Z+ ejX                  e+d$d%      Z-d&e+ ej\                  e-j_                  d'            ja                  d'      jc                  d(      dZ2d) Z3d* Z4d+ Z5d, Z6d- Z7d. Z8e9d/k(  r e8        yy# e$ r  ej>                  d       Y w xY w)2a  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                      t         j                  r1t        t        d      j	                  t         j                               S d S )Nw)global_cachehas_state_changedopen_token_cache_filenamewrite	serialize     @/var/www/html/venv/lib/python3.12/site-packages/msal/__main__.py<lambda>r      s=     %% 		$**<+A+A+CD  ,0 r   z$04b07795-8ddb-461a-bbee-02f9e1bf7b46z$04f0c124-f2bc-4f59-8241-bf6df9866bbdzhttps://example.com/endpointplaceholder)http_methodurlnoncec                 F    t        t        j                  | dd             y )N   T)indent	sort_keys)printjsondumps)blobs    r   
print_jsonr      s    	$**T!t
45r   c                 :    t        dj                  |             dvS )Nz9{} (N/n/F/f or empty means False, otherwise it is True): )NnFf )inputformat)messages    r   _input_booleanr%   "   s%    CJJ7S
)* *r   c                 \    t        | j                  |            j                         xs |S )N)default)r"   r#   strip)r$   r'   s     r   _inputr)   '   s&    01779DWDr   zYour options:z    Your choice? Fc           	      R   | sJ d       |rt        |       t        | d      D ]&  \  }}t        dj                  | ||                   ( |rt        d       	 t        |      }	 t	        |      }d|cxk  rt        |       k  rn n| |dz
     S 7# t        $ r |r|r|cY S Y w xY w)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choices	            r   _select_optionsr:   *   s     ///7f'+ :1l!!!_Q%789:78
=	 ]FF*c'l*vz**   	 2	 s   ')B B&%B&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                  `    t        g ddd      j                         } 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r2   r5   4https://pas.windows.net/CheckMyAccess/Linux/.defaultz9SSH Cert scope shall be tested by its dedicated functions)r:   splitr0   scopess    r   _input_scopesrC   J   sA     
 q#
 %'  >GTUUMr   c                 \    | j                         }|rt        |d d      S t        d       y )Nc                 2    dj                  | d   | d         S )Nz{}, came from {}usernameaccount_source)r#   as    r   r   z!_select_account.<locals>.<lambda>]   s    &8&?&?*qQaOb&c r   z0Account(s) already signed in inside MSAL Python:r4   r2   zRNo account available inside MSAL Python. Use other methods to acquire token first.)get_accountsr:   r   )appaccountss     r   _select_accountrN   X   s4    !HcE 	 	bcr   c           
          t        |       }|rQt        | j                  t               |t	        d      | j                         rt	        d      rt        nd             yy)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)rN   r   acquire_token_silent_with_errorrC   r%   is_pop_supportedplaceholder_auth_schemerL   rR   s     r   _acquire_token_silentrY   c   s[    c"G366O()LM'')n=Y.Z 0 7  	 r   c                    t        | t        j                        sJ |xs
 t               }t	        dddddddddgd d	
      d   }|dk(  rd}nHt	        dg| j                         D cg c]  }|d   	 c}z   dd      }t        |t              r|d   n|}| j                  || j                  | j                  t        t        fv d|||xs i | j                         rt        d      rt        nd      }|r@d|v r<|j                  di       j                  d      }||k7  rt!        j"                  d|       t%        |       |S c c}w )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.select_accountz.select_account. Prompt with an account picker.c                     | d   S )Nr\   r   r7   s    r   r   z,_acquire_token_interactive.<locals>.<lambda>y   s    !M"2 r   zPrompt behavior?rJ   r[   rF   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.)Tr>   i  rQ   )parent_window_handleenable_msa_passthroughportprompt
login_hintdatarT   id_token_claimspreferred_usernamez-Signed-in user "%s" does not match login_hint)
isinstancemsalPublicClientApplicationrC   r:   rK   dictacquire_token_interactiveCONSOLE_WINDOW_HANDLE	client_id
_AZURE_CLI_VISUAL_STUDIOrV   r%   rW   getloggingwarningr   )	rL   rB   rf   rd   re   rI   raw_login_hintresultsigned_in_users	            r   _acquire_token_interactiverx   p   st   c477888&}F'{|)pq"3cd

 3!# $+,F !!
(FS-=-=-?@a
m@@ u#'
 4>nd3S^J/Yg
** 66"}}1   *4:2##%.9U*V , + 
F '61$5r:>>?STZ'OOK^\vM- As   *E
c                     t        | j                  t        d      t        j                  d      t	                            y)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: rA   N)r   "acquire_token_by_username_passwordr)   getpassrC   rL   s    r   #_acquire_token_by_username_passwordr}      s5    s55|gool;MO 6 U Vr   c                    t        | t        j                        sJ | j                  t	                     }t        |d          t        j                  j                          t        d       | j                  |      }t        |       y)zNacquire_token_by_device_flow() - Note that this one does not go through brokerrA   r$   zNAfter you completed the step above, press ENTER in this console to continue...N)ri   rj   rk   initiate_device_flowrC   r   sysstdoutflushr"   acquire_token_by_device_flowr   )rL   flowrv   s      r   _acquire_token_by_device_flowr      sj    c477888##=?#;D	$y/JJ	
Z[--d3Fvr   aw  {"kty":"RSA", "n":"2tNr73xwcj6lH7bqRZrFzgSLj7OeLfbn8216uOMDHuaZ6TEUBDN8Uz0ve8jAlKsP9CQFCSVoSNovdE-fs7c15MxEGHjDcNKLWonznximj8pDGZQjVdfK-7mG6P6z-lgVcLuYu5JcWU_PeEqIKg5llOaz-qeQ4LEDS4T1D2qWRGpAra4rJX1-kmrWmX_XIamq30C9EIO0gGuT4rc2hJBWQ-4-FnE1NXmy125wfT3NdotAJGq5lMIfhjfglDbJCwhc8Oe17ORjO3FsB5CLuBRpYmP7Nzn66lRY3Fe11Xz8AEBl3anKFSJcTvlMnFtu3EpD-eiaHfTgRBU7CztGQqVbiQ", "e":"AQAB"}ssh-certkey1)
token_typekey_idreq_cnfr?   c                    t        | t        j                        sJ t        |       }|r_| j	                  t
        |t        t        d            }t        |       |r+|j                  d      dk7  rt        j                  d       yyyy)zFAcquire an SSH Cert silently- This typically only works with Azure CLIrP   )rf   rS   r   r   zUnable to acquire an ssh-cert.N)ri   rj   rk   rN   acquire_token_silent_SSH_CERT_SCOPE_SSH_CERT_DATAr%   r   rr   rs   error)rL   rR   rv   s      r   _acquire_ssh_cert_silentlyr      s    c477888c"G))()LM	 *  	6fjj.*<MM:; =6 r   c                     t        | t        j                        sJ t        | t        t
              }|j                  d      dk7  rt        j                  d       yy)zLAcquire an SSH Cert interactively - This typically only works with Azure CLIrB   rf   r   r   zUnable to acquire an ssh-certN)	ri   rj   rk   rx   r   r   rr   rs   r   )rL   rv   s     r   _acquire_ssh_cert_interactiver      sI    c477888'O.YFzz,:-56 .r   z+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-AAAAAAAAsw)kidxms_kslpopzutf-8=c                     t        | t        j                        sJ dg}t        | |t              }t        |       |j                  d      dk7  rt        j                  d       yy)zLAcquire a POP token interactively - This typically only works with Azure CLIz-6256c85f-0aad-4d50-b960-e6e9b21efe35/.defaultr   r   r   zUnable to acquire a pop tokenN)	ri   rj   rk   rx   	_POP_DATAr   rr   rs   r   )rL   	POP_SCOPErv   s      r   _acquire_pop_token_interactiver      sY    c477888@AI'IINFvzz,5(56 )r   c                 |    t        |       }|r/| j                  |       t        dj                  |d                yy)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 PythonrF   N)rN   remove_accountr   r#   rX   s     r   _remove_accountr      s=    c"G7#PWWX_`jXklm r   c                     t        | t        j                        sJ t        | j	                  t                            y)zKCCA.acquire_token_for_client() - Rerun this will get same token from cache.rA   N)ri   rj   ConfidentialClientApplicationr   acquire_token_for_clientrC   r|   s    r   _acquire_token_for_clientr      s0    c4==>>>s++=?+CDr   c                 \    t        | t        j                        sJ | j                          y)zECCA.remove_tokens_for_client() - Run this to evict tokens from cache.N)ri   rj   r   remove_tokens_for_clientr|   s    r   _remove_tokens_for_clientr      s$    c4==>>>  "r   c                     | j                   rdnd}t        dj                  |             t        j                          y)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)_enable_brokerr   r#   r   exit)rL   bug_links     r   _exitr      s:      	ub 
 

>
E
Eh
OPHHJr   c                     t        dj                  t        j                               t	        dddddj                  t
              dgd dd	
      } | d   dk(  rUt        j                  j                  t
              r2	 t        j                  t        t
        d      j                                t	        t        ddt        dddddt        j                   d      t        j                   d      ddgd dd
      }t#        |t$              xr d|v }|r|d   r|d   st'        d      | xr t)        d      }|rt*        rt)        d      nd	}t	        g ddd       }|r|j-                  d!      st)        d"      nd }|s7t        j.                  t#        |t$              r|d   n||||||||t        #	      n$t        j0                  |d   |d   |||t        $      }t2        gt#        |t        j.                        rt4        t6        t8        t:        t<        gng z   t>        t@        gz   t#        |t        j0                        rtB        tD        gng z   }	 t	        |tF        gz   d% d&'      }		  |	|       !# t        $ r Y w xY w# t&        $ r }
tI        jJ                  d(|
       Y d }
~
5d }
~
wtL        $ r t        d)       Y Nw xY w)*Nz4Welcome to the Msal Python {} Tester (Experimental)
emptyz<Start with an empty token cache. Suitable for one-off tests.)r9   descreusezReuse the previous token cache {} (if any) which was created during last test app exit. Useful for testing acquire_token_silent() repeatedlyc                     | d   S )Nr   r   r`   s    r   r   z_main.<locals>.<lambda>   
    !F) r   z1What token cache state do you want to begin with?F)r4   r2   r5   r9   rz+Azure CLI (Correctly configured for MSA-PT))ro   namez/Visual Studio (Correctly configured for MSA-PT)z$95de633a-083e-42f5-b444-a4295d8e9314zAWhiteboard Services (Non MSA-PT app. Accepts AAD & MSA accounts.)	CLIENT_IDCLIENT_SECRETzoA confidential client app (CCA) whose settings are defined in environment variables CLIENT_ID and CLIENT_SECRET)ro   client_secretr   c                     | d   S )Nr   r   rH   s    r   r   z_main.<locals>.<lambda>  r   r   zUImpersonate this app (or you can type in the client_id of your own public client app)Tr   ro   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)r>   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_discoveryenable_broker_on_windowsenable_broker_on_macenable_broker_on_linuxenable_broker_on_wslenable_pii_logtoken_cache)client_credentialr   r   r   r   c                     | j                   S N)__doc__)r    s    r   r   z_main.<locals>.<lambda>O  s
    aii r   zMSAL Python APIs:rJ   zInvalid input: %sAborted)'r   r#   rj   __version__r:   r   ospathexistsr   deserializer   readIOErrorrp   rq   getenvri   rl   r0   r%   enable_debug_log
startswithrk   r   rY   rx   r   r   r   r   r}   r   r   r   r   rs   r   KeyboardInterrupt)cache_choice
chosen_appis_ccaenable_brokerr   r   r   rL   methods_to_be_testedfunces              r   _mainr      s   	
A
H
HIYIY
Z["!V
 "KKQ6-L/	$
 ,B$&L  H(RWW^^<Q-R	$$T*?%E%J%J%LM ! *WX$._`<  GJ  	K;/YY7G	
	
"
 ,O#%J 
D)Ko.KFz+.:o3N\]]Z 
^ 5U &
M GTXh^$ABnsN !
 ]#	
I y33/ 1 (	R
 7;	   
&
&#-j$#?
;Z-!.*,*% 

 "??;$_5-% 
 & "
 C!=!=> ')&)* EG	
 0

 C!C!CD &% KM
"  E7*/8KM	I U  		`  	2MM-q11  	)	s0    1I7 .J 7	JJ	KJ++KK__main__r   )NN):r   base64r{   r   rs   r   r   atexitrj   r   SerializableTokenCacher   registerrp   rq   PopAuthSchemeHTTP_GETrW   r   r%   r)   strr:   r   basicConfigDEBUGINFOdotenvr<   infoImportErrorrt   rC   rN   rY   rx   r}   r   _JWK1r   r   r   r   _POP_KEY_IDr   _RAW_REQ_CNFurlsafe_b64encodeencodedecoderstripr   r   r   r   r   r   r   __name__r   r   r   <module>r      s   = < < <( *t**,  0  4
7,$,,""++&
 6*
E (0CUX$ * ""CD    +;'-- N?"MGLL>?	d%NV
 	F *fOIJ<7 <tzz+$?@'v''(;(;G(DELLWU\\]`a	7nE
#
hT z	G e  ?GOO	>??s   <E9 9FF