a
   2sd                   @   s   d dl Z d dlZd dlZd dlZddlmZ ddlmZ ddlmZ dZ	d
e	ZdZeeZd	d
 Zdd Zdd Zdd Zdd ZG dd deZd$ddZdd Zdd Zdd Zd%ddZd&d d!Zd"d# ZdS )'    N   )credentials)errors)configz	docker.iozhttps://index.{0}/v1/z<token>c                 C   sX   d| v rt d| t| \}}|d dks<|d dkrLt d|t||fS )Nz://z-Repository name cannot contain a scheme ({0})r   -z<Invalid index name ({0}). Cannot begin or end with a hyphen.)r   ZInvalidRepositoryformatsplit_repo_nameresolve_index_name)	repo_name
index_nameZremote_name r   //usr/lib/python3.9/site-packages/docker/auth.pyresolve_repository_name   s    r   c                 C   s   t | } | dt krt} | S )Nzindex.)convert_to_hostname
INDEX_NAME)r   r   r   r   r
   !   s    r
   c                 C   sf   t d | jr| jjr0t d t| jd| _t| j|| jd}|rXt d t|S t d d S )NzLooking for auth configz2No auth config in memory - loading from filesystem)credstore_envzFound auth configzNo auth config found)logdebugZ_auth_configsis_emptyload_configr   resolve_authconfigencode_header)ZclientregistryZauthcfgr   r   r   get_config_header(   s    



r   c                 C   sL   |  dd}t|dks<d|d vrDd|d vrD|d dkrDt| fS t|S )N/r   .r   :Z	localhost)splitlenr   tuple)r   partsr   r   r   r	   >   s    


r	   c                 C   s   t | tst| } | |S N)
isinstance
AuthConfigget_credential_store)
authconfigr   r   r   r   r%   H   s    
r%   c                   @   s   e Zd ZdddZedddZedddZed	d
 Zedd Z	edd Z
edd Zd ddZdd Zdd Zdd Zdd Zdd ZdS )!r$   Nc                 C   s*   d|vri |d< |  | || _i | _d S Nauths)update_credstore_env_stores)selfZdctr   r   r   r   __init__O   s
    
zAuthConfig.__init__Fc                 C   s   i }t |D ]\}}t|tsLtd| |rDtd|i   S d|v rvtd| d|d i||< qd|vrtd| i ||< qt	|d \}}tdt
|t
| |||d	|d
||< q|S )a   
        Parses authentication entries

        Args:
          entries:        Dict of authentication entries.
          raise_on_error: If set to true, an invalid format will raise
                          InvalidConfigFile

        Returns:
          Authentication registry.
        z+Config entry for key {0} is not auth configz&Invalid configuration for registry {0}Zidentitytokenz-Found an IdentityToken entry for registry {0}IdentityTokenauthzOAuth data for {0} is absent. Client might be using a credentials store instead.z(Found entry (registry={0}, username={1})emailusernamepasswordr0   Zserveraddress)six	iteritemsr#   dictr   r   r   r   InvalidConfigFiledecode_authreprget)clsentriesraise_on_errorconfr   entryr2   r3   r   r   r   
parse_authV   sX    
	zAuthConfig.parse_authc              
   C   sN  |st |}|s| i |S z6t|}t|}W d   n1 sF0    Y  W nB tttfy } z$t	| | t
||W  Y d}~S d}~0 0 i }|drt	d |d| j|dddi |d rt	d |d|di |dr t	d	 |d|di |r0| ||S t	d
 | d| |i|S )a8  
        Loads authentication data from a Docker configuration file in the given
        root directory or if config_path is passed use given path.
        Lookup priority:
            explicit config_path parameter > DOCKER_CONFIG environment
            variable > ~/.docker/config.json > ~/.dockercfg
        Nr(   zFound 'auths' sectionT)r=   
credsStorezFound 'credsStore' sectioncredHelperszFound 'credHelpers' sectionzNCouldn't find auth-related section ; attempting to interpret as auth-only file)r   Zfind_config_fileopenjsonloadIOErrorKeyError
ValueErrorr   r   _load_legacy_configr:   r)   r@   pop)r;   config_pathconfig_dictr   config_fileferesr   r   r   r      s<    



,
$





zAuthConfig.load_configc                 C   s   |  di S r'   r:   r,   r   r   r   r(      s    zAuthConfig.authsc                 C   s   |  dd S )NrA   rQ   rR   r   r   r   creds_store   s    zAuthConfig.creds_storec                 C   s   |  di S )NrB   rQ   rR   r   r   r   cred_helpers   s    zAuthConfig.cred_helpersc                 C   s   | j  o| j o| j S r"   )r(   rS   rT   rR   r   r   r   r      s    zAuthConfig.is_emptyc                 C   s   | j s| jrP| |}|durPtd| | ||}|durF|S td |r\t|nt}tdt	| || j
v rtdt	| | j
| S t| j
D ]0\}}t||krtdt	| |  S qtd dS )a+  
        Returns the authentication data from the given auth configuration for a
        specific registry. As with the Docker client, legacy entries in the
        config with full URLs are stripped down to hostnames before checking
        for a match. Returns None if no match was found.
        NzUsing credentials store "{0}"z/No entry in credstore - fetching from auth dictLooking for auth entry for {0}z	Found {0}No entry found)rS   rT   r%   r   r   r   _resolve_authconfig_credstorer
   r   r9   r(   r4   r5   )r,   r   
store_nameZcfgkeyr>   r   r   r   r      s*    





zAuthConfig.resolve_authconfigc              
   C   s   |r|t krt}tdt| | |}zJ||}d|i}|d tkr\|d |d< n|	|d |d d |W S  t
jy   td Y d S  t
jy } z tdt|W Y d }~n
d }~0 0 d S )	NrU   ZServerAddressUsernameZSecretr.   )rZ   ZPasswordrV   zCredentials store error: {0})r   	INDEX_URLr   r   r   r9   _get_store_instancer:   TOKEN_USERNAMEr)   r   ZCredentialsNotFoundZ
StoreErrorr   ZDockerException)r,   r   Zcredstore_namestoredatarP   rO   r   r   r   rW      s,    


z(AuthConfig._resolve_authconfig_credstorec                 C   s*   || j vr tj|| jd| j |< | j | S )N)Zenvironment)r+   r   ZStorer*   )r,   namer   r   r   r\     s
    
zAuthConfig._get_store_instancec                 C   s"   |r|t krt}| j|p | jS r"   )r   r[   rT   r:   rS   )r,   r   r   r   r   r%   #  s    zAuthConfig.get_credential_storec                 C   s   | j  }| jrP| | j}|  D ]&}| || j||< || |t|< q(| j	 D ](\}}| ||||< || |t|< qZ|S r"   )
r(   copyrS   r\   listkeysrW   r   rT   items)r,   Z	auth_datar^   kregrX   r   r   r   get_all_credentials)  s    
zAuthConfig.get_all_credentialsc                 C   s   || d |< d S r'   r   )r,   rf   r_   r   r   r   add_auth=  s    zAuthConfig.add_auth)N)F)N)N)__name__
__module____qualname__r-   classmethodr@   r   propertyr(   rS   rT   r   r   rW   r\   r%   rg   rh   r   r   r   r   r$   N   s&   
D/




#r$   c                 C   s   t | tst| |} | |S r"   )r#   r$   r   )r&   r   r   r   r   r   r   A  s    

r   c                 C   s    |  dd ddddd S )Nzhttp:// zhttps://r   r   r   )replacer   )urlr   r   r   r   G  s    r   c                 C   sD   t | tjr| d} t| }|dd\}}|d|dfS )Nascii   :r   utf8)r#   r4   Zstring_typesencodebase64Z	b64decoder   decode)r/   sZloginpwdr   r   r   r8   K  s
    

r8   c                 C   s   t | d}t|S )Nrq   )rD   dumpsrt   ru   Zurlsafe_b64encode)r/   Z	auth_jsonr   r   r   r   S  s    r   Fc                 C   s   t | |S )a   
    Parses authentication entries

    Args:
      entries:        Dict of authentication entries.
      raise_on_error: If set to true, an invalid format will raise
                      InvalidConfigFile

    Returns:
      Authentication registry.
    )r$   r@   )r<   r=   r   r   r   r@   X  s    r@   c                 C   s   t | ||S r"   )r$   r   )rK   rL   r   r   r   r   r   h  s    r   c              
   C   s   t d zg }t| L}| D ]}|| dd  q"t|dk rVt	dW d    n1 sj0    Y  t
|d \}}dt|||d tdiiW S  ty } zt | W Y d }~n
d }~0 0 t d	 i S )
Nz+Attempting to parse legacy auth file formatz = r      z$Invalid or empty configuration file!r   r(   r1   z4All parsing attempts failed - returning empty config)r   r   rC   	readlinesappendstripr   r   r   r7   r8   r   r[   	Exception)rM   r_   rN   liner2   r3   rO   r   r   r   rI   l  s0    

"

rI   )NN)F)NNN)ru   rD   Zloggingr4   rn   r   r   Zutilsr   r   r   r[   r]   Z	getLoggerri   r   r   r
   r   r	   r%   r6   r$   r   r   r8   r   r@   r   rI   r   r   r   r   <module>   s0   


 t


