File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/docker.tar
Back
auth.py 0000644 00000031261 15027665106 0006072 0 ustar 00 import base64 import json import logging from . import credentials, errors from .utils import config INDEX_NAME = 'docker.io' INDEX_URL = f'https://index.{INDEX_NAME}/v1/' TOKEN_USERNAME = '<token>' log = logging.getLogger(__name__) def resolve_repository_name(repo_name): if '://' in repo_name: raise errors.InvalidRepository( f'Repository name cannot contain a scheme ({repo_name})' ) index_name, remote_name = split_repo_name(repo_name) if index_name[0] == '-' or index_name[-1] == '-': raise errors.InvalidRepository( f'Invalid index name ({index_name}). ' 'Cannot begin or end with a hyphen.' ) return resolve_index_name(index_name), remote_name def resolve_index_name(index_name): index_name = convert_to_hostname(index_name) if index_name == f"index.{INDEX_NAME}": index_name = INDEX_NAME return index_name def get_config_header(client, registry): log.debug('Looking for auth config') if not client._auth_configs or client._auth_configs.is_empty: log.debug( "No auth config in memory - loading from filesystem" ) client._auth_configs = load_config(credstore_env=client.credstore_env) authcfg = resolve_authconfig( client._auth_configs, registry, credstore_env=client.credstore_env ) # Do not fail here if no authentication exists for this # specific registry as we can have a readonly pull. Just # put the header if we can. if authcfg: log.debug('Found auth config') # auth_config needs to be a dict in the format used by # auth.py username , password, serveraddress, email return encode_header(authcfg) log.debug('No auth config found') return None def split_repo_name(repo_name): parts = repo_name.split('/', 1) if len(parts) == 1 or ( '.' not in parts[0] and ':' not in parts[0] and parts[0] != 'localhost' ): # This is a docker index repo (ex: username/foobar or ubuntu) return INDEX_NAME, repo_name return tuple(parts) def get_credential_store(authconfig, registry): if not isinstance(authconfig, AuthConfig): authconfig = AuthConfig(authconfig) return authconfig.get_credential_store(registry) class AuthConfig(dict): def __init__(self, dct, credstore_env=None): if 'auths' not in dct: dct['auths'] = {} self.update(dct) self._credstore_env = credstore_env self._stores = {} @classmethod def parse_auth(cls, entries, raise_on_error=False): """ 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. """ conf = {} for registry, entry in entries.items(): if not isinstance(entry, dict): log.debug( f'Config entry for key {registry} is not auth config' ) # We sometimes fall back to parsing the whole config as if it # was the auth config by itself, for legacy purposes. In that # case, we fail silently and return an empty conf if any of the # keys is not formatted properly. if raise_on_error: raise errors.InvalidConfigFile( f'Invalid configuration for registry {registry}' ) return {} if 'identitytoken' in entry: log.debug(f'Found an IdentityToken entry for registry {registry}') conf[registry] = { 'IdentityToken': entry['identitytoken'] } continue # Other values are irrelevant if we have a token if 'auth' not in entry: # Starting with engine v1.11 (API 1.23), an empty dictionary is # a valid value in the auths config. # https://github.com/docker/compose/issues/3265 log.debug( f'Auth data for {registry} is absent. ' f'Client might be using a credentials store instead.' ) conf[registry] = {} continue username, password = decode_auth(entry['auth']) log.debug( f'Found entry (registry={registry!r}, username={username!r})' ) conf[registry] = { 'username': username, 'password': password, 'email': entry.get('email'), 'serveraddress': registry, } return conf @classmethod def load_config(cls, config_path, config_dict, credstore_env=None): """ 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 """ if not config_dict: config_file = config.find_config_file(config_path) if not config_file: return cls({}, credstore_env) try: with open(config_file) as f: config_dict = json.load(f) except (OSError, KeyError, ValueError) as e: # Likely missing new Docker config file or it's in an # unknown format, continue to attempt to read old location # and format. log.debug(e) return cls(_load_legacy_config(config_file), credstore_env) res = {} if config_dict.get('auths'): log.debug("Found 'auths' section") res.update({ 'auths': cls.parse_auth( config_dict.pop('auths'), raise_on_error=True ) }) if config_dict.get('credsStore'): log.debug("Found 'credsStore' section") res.update({'credsStore': config_dict.pop('credsStore')}) if config_dict.get('credHelpers'): log.debug("Found 'credHelpers' section") res.update({'credHelpers': config_dict.pop('credHelpers')}) if res: return cls(res, credstore_env) log.debug( "Couldn't find auth-related section ; attempting to interpret " "as auth-only file" ) return cls({'auths': cls.parse_auth(config_dict)}, credstore_env) @property def auths(self): return self.get('auths', {}) @property def creds_store(self): return self.get('credsStore', None) @property def cred_helpers(self): return self.get('credHelpers', {}) @property def is_empty(self): return ( not self.auths and not self.creds_store and not self.cred_helpers ) def resolve_authconfig(self, registry=None): """ 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. """ if self.creds_store or self.cred_helpers: store_name = self.get_credential_store(registry) if store_name is not None: log.debug( f'Using credentials store "{store_name}"' ) cfg = self._resolve_authconfig_credstore(registry, store_name) if cfg is not None: return cfg log.debug('No entry in credstore - fetching from auth dict') # Default to the public index server registry = resolve_index_name(registry) if registry else INDEX_NAME log.debug(f"Looking for auth entry for {repr(registry)}") if registry in self.auths: log.debug(f"Found {repr(registry)}") return self.auths[registry] for key, conf in self.auths.items(): if resolve_index_name(key) == registry: log.debug(f"Found {repr(key)}") return conf log.debug("No entry found") return None def _resolve_authconfig_credstore(self, registry, credstore_name): if not registry or registry == INDEX_NAME: # The ecosystem is a little schizophrenic with index.docker.io VS # docker.io - in that case, it seems the full URL is necessary. registry = INDEX_URL log.debug(f"Looking for auth entry for {repr(registry)}") store = self._get_store_instance(credstore_name) try: data = store.get(registry) res = { 'ServerAddress': registry, } if data['Username'] == TOKEN_USERNAME: res['IdentityToken'] = data['Secret'] else: res.update({ 'Username': data['Username'], 'Password': data['Secret'], }) return res except credentials.CredentialsNotFound: log.debug('No entry found') return None except credentials.StoreError as e: raise errors.DockerException( f'Credentials store error: {repr(e)}' ) from e def _get_store_instance(self, name): if name not in self._stores: self._stores[name] = credentials.Store( name, environment=self._credstore_env ) return self._stores[name] def get_credential_store(self, registry): if not registry or registry == INDEX_NAME: registry = INDEX_URL return self.cred_helpers.get(registry) or self.creds_store def get_all_credentials(self): auth_data = self.auths.copy() if self.creds_store: # Retrieve all credentials from the default store store = self._get_store_instance(self.creds_store) for k in store.list().keys(): auth_data[k] = self._resolve_authconfig_credstore( k, self.creds_store ) auth_data[convert_to_hostname(k)] = auth_data[k] # credHelpers entries take priority over all others for reg, store_name in self.cred_helpers.items(): auth_data[reg] = self._resolve_authconfig_credstore( reg, store_name ) auth_data[convert_to_hostname(reg)] = auth_data[reg] return auth_data def add_auth(self, reg, data): self['auths'][reg] = data def resolve_authconfig(authconfig, registry=None, credstore_env=None): if not isinstance(authconfig, AuthConfig): authconfig = AuthConfig(authconfig, credstore_env) return authconfig.resolve_authconfig(registry) def convert_to_hostname(url): return url.replace('http://', '').replace('https://', '').split('/', 1)[0] def decode_auth(auth): if isinstance(auth, str): auth = auth.encode('ascii') s = base64.b64decode(auth) login, pwd = s.split(b':', 1) return login.decode('utf8'), pwd.decode('utf8') def encode_header(auth): auth_json = json.dumps(auth).encode('ascii') return base64.urlsafe_b64encode(auth_json) def parse_auth(entries, raise_on_error=False): """ 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. """ return AuthConfig.parse_auth(entries, raise_on_error) def load_config(config_path=None, config_dict=None, credstore_env=None): return AuthConfig.load_config(config_path, config_dict, credstore_env) def _load_legacy_config(config_file): log.debug("Attempting to parse legacy auth file format") try: data = [] with open(config_file) as f: for line in f.readlines(): data.append(line.strip().split(' = ')[1]) if len(data) < 2: # Not enough data raise errors.InvalidConfigFile( 'Invalid or empty configuration file!' ) username, password = decode_auth(data[0]) return {'auths': { INDEX_NAME: { 'username': username, 'password': password, 'email': data[1], 'serveraddress': INDEX_URL, } }} except Exception as e: log.debug(e) log.debug("All parsing attempts failed - returning empty config") return {} constants.py 0000644 00000002253 15027665106 0007144 0 ustar 00 import sys from .version import __version__ DEFAULT_DOCKER_API_VERSION = '1.44' MINIMUM_DOCKER_API_VERSION = '1.24' DEFAULT_TIMEOUT_SECONDS = 60 STREAM_HEADER_SIZE_BYTES = 8 CONTAINER_LIMITS_KEYS = [ 'memory', 'memswap', 'cpushares', 'cpusetcpus' ] DEFAULT_HTTP_HOST = "127.0.0.1" DEFAULT_UNIX_SOCKET = "http+unix:///var/run/docker.sock" DEFAULT_NPIPE = 'npipe:////./pipe/docker_engine' BYTE_UNITS = { 'b': 1, 'k': 1024, 'm': 1024 * 1024, 'g': 1024 * 1024 * 1024 } INSECURE_REGISTRY_DEPRECATION_WARNING = \ 'The `insecure_registry` argument to {} ' \ 'is deprecated and non-functional. Please remove it.' IS_WINDOWS_PLATFORM = (sys.platform == 'win32') WINDOWS_LONGPATH_PREFIX = '\\\\?\\' DEFAULT_USER_AGENT = f"docker-sdk-python/{__version__}" DEFAULT_NUM_POOLS = 25 # The OpenSSH server default value for MaxSessions is 10 which means we can # use up to 9, leaving the final session for the underlying SSH connection. # For more details see: https://github.com/docker/docker-py/issues/2246 DEFAULT_NUM_POOLS_SSH = 9 DEFAULT_MAX_POOL_SIZE = 10 DEFAULT_DATA_CHUNK_SIZE = 1024 * 2048 DEFAULT_SWARM_ADDR_POOL = ['10.0.0.0/8'] DEFAULT_SWARM_SUBNET_SIZE = 24 __pycache__/version.cpython-310.pyc 0000644 00000000615 15027665106 0013154 0 ustar 00 o �h� � @ s^ z d dl mZ W dS ey. ddlmZmZ zed�ZW Y dS ey- dZY Y dS w w )� )�__version__� )�PackageNotFoundError�version�dockerz0.0.0N)�_versionr �ImportError�importlib.metadatar r � r r �D/usr/local/CyberPanel/lib/python3.10/site-packages/docker/version.py�<module> s �� __pycache__/__init__.cpython-310.pyc 0000644 00000000652 15027665106 0013227 0 ustar 00 o �h� � @ sL d dl mZ d dlmZmZ d dlmZmZ d dlm Z d dl mZ dZdS )� )� APIClient)�DockerClient�from_env)�Context� ContextAPI)� TLSConfig)�__version__�dockerN) �apir �clientr r �contextr r �tlsr �versionr � __title__� r r �E/usr/local/CyberPanel/lib/python3.10/site-packages/docker/__init__.py�<module> s __pycache__/client.cpython-310.pyc 0000644 00000020303 15027665106 0012741 0 ustar 00 o �h � @ s� d dl mZ d dlmZmZ d dlmZ d dlmZ d dl m Z d dlmZ d dl mZ d dlmZ d d lmZ d d lmZ d dlmZ d dlmZ d d lmZ G dd� d�ZejZdS )� )� APIClient)�DEFAULT_MAX_POOL_SIZE�DEFAULT_TIMEOUT_SECONDS��ConfigCollection��ContainerCollection��ImageCollection��NetworkCollection��NodeCollection��PluginCollection��SecretCollection��ServiceCollection��Swarm��VolumeCollection)�kwargs_from_envc @ s" e Zd ZdZdd� Zedd� �Zedd� �Zedd � �Z ed d� �Z edd � �Zedd� �Zedd� �Z edd� �Zedd� �Zedd� �Zedd� �Zdd� Zejje_dd� Zejje_dd� Zejje_d d!� Zejje_d"d#� Zejje_d$d%� Zejje_d&d'� Zejje_d(d)� Zd*S )+�DockerClienta� A client for communicating with a Docker server. Example: >>> import docker >>> client = docker.DockerClient(base_url='unix://var/run/docker.sock') Args: base_url (str): URL to the Docker server. For example, ``unix:///var/run/docker.sock`` or ``tcp://127.0.0.1:1234``. version (str): The version of the API to use. Set to ``auto`` to automatically detect the server's version. Default: ``1.35`` timeout (int): Default timeout for API calls, in seconds. tls (bool or :py:class:`~docker.tls.TLSConfig`): Enable TLS. Pass ``True`` to enable it with default options, or pass a :py:class:`~docker.tls.TLSConfig` object to use custom configuration. user_agent (str): Set a custom user agent for requests to the server. credstore_env (dict): Override environment variables when calling the credential store process. use_ssh_client (bool): If set to `True`, an ssh connection is made via shelling out to the ssh client. Ensure the ssh client is installed and configured on the host. max_pool_size (int): The maximum number of connections to save in the pool. c O s t |i |��| _d S �N)r �api��self�args�kwargs� r! �C/usr/local/CyberPanel/lib/python3.10/site-packages/docker/client.py�__init__, s zDockerClient.__init__c K sR |� dt�}|� dt�}|� dd�}|� dd�}| d||||d�tdi |����S ) a� Return a client configured from environment variables. The environment variables used are the same as those used by the Docker command-line client. They are: .. envvar:: DOCKER_HOST The URL to the Docker host. .. envvar:: DOCKER_TLS_VERIFY Verify the host against a CA certificate. .. envvar:: DOCKER_CERT_PATH A path to a directory containing TLS certificates to use when connecting to the Docker host. Args: version (str): The version of the API to use. Set to ``auto`` to automatically detect the server's version. Default: ``auto`` timeout (int): Default timeout for API calls, in seconds. max_pool_size (int): The maximum number of connections to save in the pool. environment (dict): The environment to read environment variables from. Default: the value of ``os.environ`` credstore_env (dict): Override environment variables when calling the credential store process. use_ssh_client (bool): If set to `True`, an ssh connection is made via shelling out to the ssh client. Ensure the ssh client is installed and configured on the host. Example: >>> import docker >>> client = docker.from_env() .. _`SSL version`: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLSv1 �timeout� max_pool_size�versionN�use_ssh_clientF)r$ r% r&