o
    2.a3                     @   s   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 d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.z/v1/z<token>c                 C   sZ   d| v rt d|  dt| \}}|d dks|d dkr't d|t||fS )Nz://z)Repository name cannot contain a scheme ()r   -z;Invalid index name ({}). Cannot begin or end with a hyphen.)r   InvalidRepositorysplit_repo_nameformatresolve_index_name)	repo_name
index_nameremote_name r   -/usr/lib/python3/dist-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rt d t| jd| _t| j|| jd}|r,t 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debug_auth_configsis_emptyload_configr   resolve_authconfigencode_header)clientregistryauthcfgr   r   r   get_config_header&   s   



r    c                 C   sL   |  dd}t|dksd|d vr"d|d vr"|d dkr"t| fS t|S )N/r   .r   :	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,   F   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)selfdctr   r   r   r   __init__M   s
   

zAuthConfig.__init__Fc                 C   s   i }|  D ]f\}}t|ts%td| |r!td|i   S d|v r:td| d|d i||< qd|vrKt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 {} is not auth configz%Invalid configuration for registry {}identitytokenz,Found an IdentityToken entry for registry {}IdentityTokenauthzNAuth data for {} is absent. Client might be using a credentials store instead.z&Found entry (registry={}, username={})emailusernamepasswordr9   serveraddress)itemsr*   dictr   r   r   r   InvalidConfigFiledecode_authreprget)clsentriesraise_on_errorconfr   entryr;   r<   r   r   r   
parse_authT   sT   
	zAuthConfig.parse_authc              
   C   sH  |sKt |}|s| i |S zt|}t|}W d   n1 s#w   Y  W n! tttfyJ } zt	| | t
||W  Y d}~S d}~ww i }|drft	d |d| j|dddi |drzt	d |d|di |drt	d	 |d|di |r| ||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)rF   
credsStorezFound 'credsStore' sectioncredHelperszFound 'credHelpers' sectionzNCouldn't find auth-related section ; attempting to interpret as auth-only file)r   find_config_fileopenjsonloadOSErrorKeyError
ValueErrorr   r   _load_legacy_configrC   r0   rI   pop)rD   config_pathconfig_dictr   config_fileferesr   r   r   r      sD   












zAuthConfig.load_configc                 C      |  di S r.   rC   r3   r   r   r   r/         zAuthConfig.authsc                 C   s   |  dd S )NrJ   r\   r]   r   r   r   creds_store   r^   zAuthConfig.creds_storec                 C   r[   )NrK   r\   r]   r   r   r   cred_helpers   r^   zAuthConfig.cred_helpersc                 C   s   | j  o| j o| j S r)   )r/   r_   r`   r]   r   r   r   r      s   zAuthConfig.is_emptyc                 C   s   | j s| jr)| |}|dur)td| d | ||}|dur$|S td |r/t|nt}tdt|  || j	v rOtdt|  | j	| S | j	
 D ]\}}t||krltdt|  |  S qTt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 ""z/No entry in credstore - fetching from auth dictLooking for auth entry for zFound No entry found)r_   r`   r,   r   r   _resolve_authconfig_credstorer   r   rB   r/   r>   )r3   r   
store_namecfgkeyrG   r   r   r   r      s,   





zAuthConfig.resolve_authconfigc              
   C   s   |r|t krt}tdt|  | |}z'||}d|i}|d tkr0|d |d< |W S ||d |d d |W S  t	j
yN   td Y d S  t	jyd } z
tdt| d }~ww )	Nrb   ServerAddressUsernameSecretr7   )ri   Passwordrc   zCredentials store error: )r   	INDEX_URLr   r   rB   _get_store_instancerC   TOKEN_USERNAMEr0   r   CredentialsNotFound
StoreErrorr   DockerException)r3   r   credstore_namestoredatarZ   rY   r   r   r   rd      s2   


z(AuthConfig._resolve_authconfig_credstorec                 C   s*   || j vrtj|| jd| j |< | j | S )N)environment)r2   r   Storer1   )r3   namer   r   r   rm     s
   

zAuthConfig._get_store_instancec                 C   s"   |r|t krt}| j|p| jS r)   )r   rl   r`   rC   r_   )r3   r   r   r   r   r,   !  s   zAuthConfig.get_credential_storec                 C   s   | j  }| jr(| | j}|  D ]}| || j||< || |t|< q| j	 D ]\}}| ||||< || |t|< q-|S r)   )
r/   copyr_   rm   listkeysrd   r   r`   r>   )r3   	auth_datars   kregre   r   r   r   get_all_credentials'  s   
zAuthConfig.get_all_credentialsc                 C   s   || d |< d S r.   r   )r3   r}   rt   r   r   r   add_auth;  s   zAuthConfig.add_authr)   F)__name__
__module____qualname__r5   classmethodrI   r   propertyr/   r_   r`   r   r   rd   rm   r,   r~   r   r   r   r   r   r+   L   s(    
D/




#r+   c                 C   s   t | ts
t| |} | |S r)   )r*   r+   r   )r-   r   r   r   r   r   r   ?  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   E  s    r   c                 C   sB   t | tr
| d} t| }|dd\}}|d|dfS )Nascii   :r   utf8)r*   strencodebase64	b64decoder%   decode)r8   sloginpwdr   r   r   rA   I  s
   


rA   c                 C   s   t | d}t|S )Nr   )rN   dumpsr   r   urlsafe_b64encode)r8   	auth_jsonr   r   r   r   Q  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+   rI   )rE   rF   r   r   r   rI   V  s   rI   c                 C   s   t | ||S r)   )r+   r   )rU   rV   r   r   r   r   r   f  s   r   c              
   C   s   t d zJg }t| &}| D ]}|| dd  qt|dk r+t	dW d    n1 s5w   Y  t
|d \}}dt|||d tdiiW S  tyf } zt | W Y d }~nd }~ww t d	 i S )
Nz+Attempting to parse legacy auth file formatz = r      z$Invalid or empty configuration file!r   r/   r:   z4All parsing attempts failed - returning empty config)r   r   rM   	readlinesappendstripr%   r&   r   r@   rA   r   rl   	Exception)rW   rt   rX   liner;   r<   rY   r   r   r   rS   j  s8   

	

rS   )NNr   )NNN)r   rN   loggingr   r   r   utilsr   r   rl   rn   	getLoggerr   r   r   r   r    r
   r,   r?   r+   r   r   rA   r   rI   r   rS   r   r   r   r   <module>   s0    

 
t

