o
    g$                     @   s$  d Z ddlZddlZddlmZ ddlmZ ddlmZm	Z	m
Z
mZ ddlmZ ddlmZ er6dd	lmZ zdd
lmZ ddlmZmZ ddlmZ ddlmZ W n ey_   eddw z
ddlmZmZ W n eyw   eddw ddlmZ dZ dZ!dZ"dZ#dZ$G dd deZ%dS )zOCI Authentication Plugin.    N)	b64encode)Path)TYPE_CHECKINGAnyDictOptional   )errors)logger)MySQLSocket)UnsupportedAlgorithm)hashesserialization)padding)PRIVATE_KEY_TYPESz'Package 'cryptography' is not installed)config
exceptionszGPackage 'oci' (Oracle Cloud Infrastructure Python SDK) is not installed   )MySQLAuthPluginMySQLOCIAuthPlugini (  z0Ephemeral security token is too large (10KB max)zGEphemeral security token file ('security_token_file') could not be readzKOCI configuration file does not contain a 'fingerprint' or 'key_file' entryc                   @   s   e Zd ZU dZdZeed< dZeed< e	j
Zeed< ededeeef d	efd
dZeded	efddZd	eeef fddZed	efddZed	efddZdeded	ee fddZdddeded	efddZdS )r   z2Implement the MySQL OCI IAM authentication plugin.NcontextDEFAULToci_config_profileoci_config_file	signature
oci_configreturnc              
   C   s   t | }|d | d}|drCzt|d }| jtkr%tt	|j
dd|d< W n ttfyB } ztt|d}~ww tj|dd	S )
a=  Prepare client's authentication response

        Prepares client's authentication response in JSON format
        Args:
            signature (bytes):  server's nonce to be signed by client.
            oci_config (dict): OCI configuration object.

        Returns:
            str: JSON string with the following format:
                 {"fingerprint": str, "signature": str, "token": base64.base64.base64}

        Raises:
            ProgrammingError: If the ephemeral security token file can't be open or the
                              token is too large.
        fingerprint)r   r   security_token_filezutf-8)encodingtokenN),:)
separators)r   decodegetr   statst_sizeOCI_SECURITY_TOKEN_MAX_SIZEr	   ProgrammingErrorOCI_SECURITY_TOKEN_TOO_LARGE	read_textOSErrorUnicodeError%OCI_SECURITY_TOKEN_FILE_NOT_AVAILABLEjsondumps)r   r   signature_64auth_responser   err r4   k/var/www/html/api-tag/env/lib/python3.10/site-packages/mysql/connector/plugins/authentication_oci_client.py_prepare_auth_responseQ   s&   
	
z)MySQLOCIAuthPlugin._prepare_auth_responsekey_pathc                 C   s   z't tj| d}tj| dd}W d   W |S 1 s w   Y  W |S  ttt	t
fyB } ztd|  d| d}~ww )z+Get the private_key form the given locationrbN)passwordz2An error occurred while reading the API_KEY from "z": )openospath
expanduserr   load_pem_private_keyread	TypeErrorr,   
ValueErrorr   r	   r)   )r7   key_fileprivate_keyr3   r4   r4   r5   _get_private_keyy   s(   z#MySQLOCIAuthPlugin._get_private_keyc                 C   s   g }dd dd d}i }z>t | jpt j| jpd}| D ]*\}}z|| r7||| s7|d| d W q tyI   |d|  Y qw W n# tj	tj
tjtjtjfyn } z|t| W Y d	}~nd	}~ww |r}td
| j d| |S )z=Get a valid OCI config from the given configuration file pathc                 S   s   t | dkS )N    )lenxr4   r4   r5   <lambda>   s    z:MySQLOCIAuthPlugin._get_valid_oci_config.<locals>.<lambda>c                 S   s   t jt j| S )N)r;   r<   existsr=   rG   r4   r4   r5   rI      s    )r   rB   r   zParameter "z" is invalidzDoes not contain parameter NzInvalid oci-config-file: z. Errors found: )r   	from_filer   DEFAULT_LOCATIONr   itemsappendKeyErrorr   ConfigFileNotFoundInvalidConfigInvalidKeyFilePathInvalidPrivateKeyProfileNotFoundstrr	   r)   )self
error_listreq_keysr   req_key	req_valuer3   r4   r4   r5   _get_valid_oci_config   sH   


z(MySQLOCIAuthPlugin._get_valid_oci_configc                 C      dS )zPlugin official name.authentication_oci_clientr4   rV   r4   r4   r5   name      zMySQLOCIAuthPlugin.namec                 C   r\   )z'Signals whether or not SSL is required.Fr4   r^   r4   r4   r5   requires_ssl   r`   zMySQLOCIAuthPlugin.requires_ssl	auth_datakwargsc                 K   s^   t d|t| |  }| |d }||t t	 }| 
||}t d| | S )z-Prepare authentication string for the server.zserver nonce: %s, len %drB   zauthentication response: %s)r
   debugrF   r[   rD   signr   PKCS1v15r   SHA256r6   encode)rV   rb   rc   r   rC   r   r2   r4   r4   r5   r2      s   z MySQLOCIAuthPlugin.auth_responsesockr   c                 K   s   | dd| _| dtj| _td| j | j|fi |}|du r(t	dtd|t
| || | }td| t|S )	aS  Handles server's `auth switch request` response.

        Args:
            sock: Pointer to the socket connection.
            auth_data: Plugin provided data (extracted from a packet
                       representing an `auth switch request` response).
            kwargs: Custom configuration to be passed to the auth plugin
                    when invoked. The parameters defined here will override the ones
                    defined in the auth plugin itself.

        Returns:
            packet: Last server's response after back-and-forth
                    communication.
        r   r   r   z!# oci configuration file path: %sNzGot a NULL auth responsez# request: %s size: %sz# server response packet: %s)r%   r   r   rL   r   r
   rd   r2   r	   InterfaceErrorrF   sendrecvbytes)rV   ri   rb   rc   responsepacketr4   r4   r5   auth_switch_response   s   

z'MySQLOCIAuthPlugin.auth_switch_response)__name__
__module____qualname____doc__r   r   __annotations__r   rU   r   rL   r   staticmethodrm   r   r6   r   rD   r[   propertyr_   boolra   r   r2   rp   r4   r4   r4   r5   r   J   s0   
  '()&rt   r/   r;   base64r   pathlibr   typingr   r   r   r    r	   r
   networkr   cryptography.exceptionsr   cryptography.hazmat.primitivesr   r   )cryptography.hazmat.primitives.asymmetricr   /cryptography.hazmat.primitives.asymmetric.typesr   ImportErrorr)   ocir   r   r   AUTHENTICATION_PLUGIN_CLASSr(   r*   r.   OCI_PROFILE_MISSING_PROPERTIESr   r4   r4   r4   r5   <module>   sH   