def test_load_config_custom_config_env_utf8(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, 'config.json') registry = 'https://your.private.registry.io' auth_ = base64.b64encode( b'sakuya\xc3\xa6:izayoi\xc3\xa6').decode('ascii') config = { 'auths': { registry: { 'auth': '{0}'.format(auth_), 'email': '*****@*****.**' } } } with open(dockercfg_path, 'w') as f: json.dump(config, f) with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}): cfg = auth.load_config(None) assert registry in cfg['auths'] cfg = cfg['auths'][registry] assert cfg['username'] == b'sakuya\xc3\xa6'.decode('utf8') assert cfg['password'] == b'izayoi\xc3\xa6'.decode('utf8') assert cfg['email'] == '*****@*****.**' assert cfg.get('auth') is None
def test_load_config_with_random_name(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, '.{0}.dockercfg'.format( random.randrange(100000))) registry = 'https://your.private.registry.io' auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii') config = { registry: { 'auth': '{0}'.format(auth_), 'email': '*****@*****.**' } } with open(dockercfg_path, 'w') as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert registry in cfg assert cfg[registry] is not None cfg = cfg[registry] assert cfg['username'] == 'sakuya' assert cfg['password'] == 'izayoi' assert cfg['email'] == '*****@*****.**' assert cfg.get('auth') is None
def pull(self, repository, tag=None, stream=False): registry, repo_name = auth.resolve_repository_name(repository) if repo_name.count(":") == 1: repository, tag = repository.rsplit(":", 1) params = { 'tag': tag, 'fromImage': repository } headers = {} if utils.compare_version('1.5', self._version) >= 0: if getattr(self, '_cfg', None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) # do not fail if no atuhentication exists # for this specific registry as we can have a readonly pull if authcfg: headers['X-Registry-Auth'] = auth.encode_header(authcfg) u = self._url("/images/create") response = self._post(u, params=params, headers=headers, stream=stream, timeout=None) if stream: return self._stream_helper(response) else: return self._result(response)
def test_load_config_invalid_auth_dict(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, "config.json") config = {"auths": {"scarlet.net": {"sakuya": "izayoi"}}} with open(dockercfg_path, "w") as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert cfg == {"scarlet.net": {}}
def test_load_config_unknown_keys(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, 'config.json') config = {'detachKeys': 'ctrl-q, ctrl-u, ctrl-i'} with open(dockercfg_path, 'w') as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert cfg == {}
def test_load_config_unknown_keys(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, "config.json") config = {"detachKeys": "ctrl-q, ctrl-u, ctrl-i"} with open(dockercfg_path, "w") as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert cfg == {}
def test_load_config_invalid_auth_dict(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, 'config.json') config = {'auths': {'scarlet.net': {'sakuya': 'izayoi'}}} with open(dockercfg_path, 'w') as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert cfg == {'scarlet.net': {}}
def __init__(self, base_url="unix://var/run/docker.sock", version="1.4"): super(Client, self).__init__() if base_url.startswith('unix:///'): base_url = base_url.replace('unix:/', 'unix:') self.mount('unix://', unixconn.UnixAdapter(base_url)) self.base_url = base_url self._version = version try: self._cfg = auth.load_config() except Exception: pass
def __init__(self, base_url="unix://var/run/docker.sock", version="1.6", timeout=DEFAULT_TIMEOUT_SECONDS): super(Client, self).__init__() if base_url.startswith("unix:///"): base_url = base_url.replace("unix:/", "unix:") self.base_url = base_url self._version = version self._timeout = timeout self.mount("unix://", unixconn.UnixAdapter(base_url, timeout)) try: self._cfg = auth.load_config() except Exception: pass
def push(self, repository): registry, repo_name = auth.resolve_repository_name(repository) u = self._url("/images/{0}/push".format(repository)) headers = {} if getattr(self, '_cfg', None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) if utils.compare_version('1.5', self._version) >= 0: # do not fail if no atuhentication exists # for this specific registry as we can have an anon push if authcfg: headers['X-Registry-Auth'] = auth.encode_header(authcfg) return self._result(self._post_json(u, None, headers=headers)) return self._result(self._post_json(u, authcfg))
def push_image(self, name, tag=None): ''' If the name of the image contains a repository path, then push the image. :param name Name of the image to push. :param tag Use a specific tag. :return: None ''' repository = name if not tag: repository, tag = utils.parse_repository_tag(name) registry, repo_name = auth.resolve_repository_name(repository) if re.search('/', repository): if registry: config = auth.load_config() if not auth.resolve_authconfig(config, registry): self.fail( "Error: configuration for %s not found. Try logging into %s first." % (registry, registry)) self.log("pushing image %s" % repository) self.results['actions'].append( "Pushed image %s to %s:%s" % (self.name, self.repository, self.tag)) self.results['changed'] = True if not self.check_mode: status = None try: for line in self.client.push(repository, tag=tag, stream=True): line = json.loads(line) self.log(line, pretty_print=True) if line.get('errorDetail'): raise Exception(line['errorDetail']['message']) status = line.get('status') except Exception as exc: if re.search('unauthorized', str(exc)): self.fail( "Error pushing image %s: %s. Does the repository exist?" % (repository, str(exc))) self.fail("Error pushing image %s: %s" % (repository, str(exc))) self.results['image'] = self.client.find_image(name=repository, tag=tag) if not self.results['image']: self.results['image'] = dict() self.results['image']['push_status'] = status
def login(self, username, password=None, email=None, registry=None): url = self._url("/auth") if registry is None: registry = auth.INDEX_URL if getattr(self, "_cfg", None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) if "username" in authcfg and authcfg["username"] == username: return authcfg req_data = {"username": username, "password": password, "email": email} res = self._result(self._post_json(url, data=req_data), True) if res["Status"] == "Login Succeeded": self._cfg["Configs"][registry] = req_data return res
def login(self, username, password=None, email=None, registry=None): url = self._url("/auth") if registry is None: registry = auth.INDEX_URL if getattr(self, '_cfg', None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) if 'username' in authcfg and authcfg['username'] == username: return authcfg req_data = {'username': username, 'password': password, 'email': email} res = self._result(self._post_json(url, data=req_data), True) if res['Status'] == 'Login Succeeded': self._cfg['Configs'][registry] = req_data return res
def test_load_config_invalid_auth_dict(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, 'config.json') config = { 'auths': { 'scarlet.net': {'sakuya': 'izayoi'} } } with open(dockercfg_path, 'w') as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert cfg == {'auths': {'scarlet.net': {}}}
def test_load_json_config(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) cfg_path = os.path.join(folder, '.dockercfg') auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii') email = '*****@*****.**' with open(cfg_path, 'w') as f: json.dump({auth.INDEX_URL: {'auth': auth_, 'email': email}}, f) cfg = auth.load_config(cfg_path) assert auth.resolve_authconfig(cfg) is not None assert cfg['auths'][auth.INDEX_URL] is not None cfg = cfg['auths'][auth.INDEX_URL] assert cfg['username'] == 'sakuya' assert cfg['password'] == 'izayoi' assert cfg['email'] == email assert cfg.get('Auth') is None
def test_load_config(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, ".dockercfg") with open(dockercfg_path, "w") as f: auth_ = base64.b64encode(b"sakuya:izayoi").decode("ascii") f.write("auth = {0}\n".format(auth_)) f.write("email = [email protected]") cfg = auth.load_config(dockercfg_path) assert auth.INDEX_NAME in cfg self.assertNotEqual(cfg[auth.INDEX_NAME], None) cfg = cfg[auth.INDEX_NAME] self.assertEqual(cfg["username"], "sakuya") self.assertEqual(cfg["password"], "izayoi") self.assertEqual(cfg["email"], "*****@*****.**") self.assertEqual(cfg.get("auth"), None)
def test_load_config_identity_token(self): folder = tempfile.mkdtemp() registry = "scarlet.net" token = "1ce1cebb-503e-7043-11aa-7feb8bd4a1ce" self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, "config.json") auth_entry = encode_auth({"username": "******"}).decode("ascii") config = {"auths": {registry: {"auth": auth_entry, "identitytoken": token}}} with open(dockercfg_path, "w") as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert registry in cfg cfg = cfg[registry] assert "IdentityToken" in cfg assert cfg["IdentityToken"] == token
def __init__(self, base_url="unix://var/run/docker.sock", version="1.6", timeout=DEFAULT_TIMEOUT_SECONDS): super(Client, self).__init__() if base_url.startswith('unix:///'): base_url = base_url.replace('unix:/', 'unix:') self.base_url = base_url self._version = version self._timeout = timeout self.mount('unix://', unixconn.UnixAdapter(base_url, timeout)) try: self._cfg = auth.load_config() except Exception: pass
def test_load_config(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, '.dockercfg') with open(dockercfg_path, 'w') as f: auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii') f.write('auth = {0}\n'.format(auth_)) f.write('email = [email protected]') cfg = auth.load_config(dockercfg_path) assert auth.INDEX_NAME in cfg self.assertNotEqual(cfg[auth.INDEX_NAME], None) cfg = cfg[auth.INDEX_NAME] self.assertEqual(cfg['username'], 'sakuya') self.assertEqual(cfg['password'], 'izayoi') self.assertEqual(cfg['email'], '*****@*****.**') self.assertEqual(cfg.get('auth'), None)
def test_load_config(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, '.dockercfg') with open(dockercfg_path, 'w') as f: auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii') f.write('auth = {0}\n'.format(auth_)) f.write('email = [email protected]') cfg = auth.load_config(dockercfg_path) assert auth.INDEX_NAME in cfg assert cfg[auth.INDEX_NAME] is not None cfg = cfg[auth.INDEX_NAME] assert cfg['username'] == 'sakuya' assert cfg['password'] == 'izayoi' assert cfg['email'] == '*****@*****.**' assert cfg.get('auth') is None
def test_load_legacy_config(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) cfg_path = os.path.join(folder, '.dockercfg') auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii') with open(cfg_path, 'w') as f: f.write('auth = {0}\n'.format(auth_)) f.write('email = [email protected]') cfg = auth.load_config(cfg_path) assert auth.resolve_authconfig(cfg) is not None assert cfg['auths'][auth.INDEX_NAME] is not None cfg = cfg['auths'][auth.INDEX_NAME] assert cfg['username'] == 'sakuya' assert cfg['password'] == 'izayoi' assert cfg['email'] == '*****@*****.**' assert cfg.get('Auth') is None
def get_jwt_for_registry(auth_url, registry, appname): # get auth username and password from dockercfg try: cfgs = auth.load_config() cfg = cfgs[registry] username = cfg['username'] password = cfg['password'] # phase, phase_config = get_phase_config_from_registry(registry) # domain = phase_config.get(user_config.domain_key, '') # only use `lain.local` as service url = "%s?service=%s&scope=repository:%s:push,pull&account=%s" % (auth_url, "lain.local", appname, username) response = requests.get(url, auth=HTTPBasicAuth(username, password)) if response.status_code < 400 and response.json()['token']: return response.json()['token'] except Exception as e: warn("can not load registry auth config : %s, need lain login first." % e) return ''
def get_jwt_for_registry(auth_url, registry, appname): # get auth username and password from dockercfg try: cfg = auth.resolve_authconfig(auth.load_config(), registry=registry) username = cfg['username'] if 'username' in cfg else cfg['Username'] password = cfg['password'] if 'password' in cfg else cfg['Password'] # phase, phase_config = get_phase_config_from_registry(registry) # domain = phase_config.get(user_config.domain_key, '') # only use `lain.local` as service url = "%s?service=%s&scope=repository:%s:push,pull&account=%s" % ( auth_url, "lain.local", appname, username) response = requests.get(url, auth=HTTPBasicAuth(username, password)) if response.status_code < 400 and response.json()['token']: return response.json()['token'] except Exception as e: warn("can not load registry auth config : %s, need lain login first." % e) return ''
def test_load_config_custom_config_env_with_headers(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, "config.json") config = {"HttpHeaders": {"Name": "Spike", "Surname": "Spiegel"}} with open(dockercfg_path, "w") as f: json.dump(config, f) with mock.patch.dict(os.environ, {"DOCKER_CONFIG": folder}): cfg = auth.load_config(None) assert "HttpHeaders" in cfg self.assertNotEqual(cfg["HttpHeaders"], None) cfg = cfg["HttpHeaders"] self.assertEqual(cfg["Name"], "Spike") self.assertEqual(cfg["Surname"], "Spiegel")
def login(self, username, password=None, email=None, registry=None): url = self._url("/auth") if registry is None: registry = auth.INDEX_URL if getattr(self, '_cfg', None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) if 'username' in authcfg and authcfg['username'] == username: return authcfg req_data = { 'username': username, 'password': password, 'email': email } res = self._result(self._post_json(url, data=req_data), True) if res['Status'] == 'Login Succeeded': self._cfg['Configs'][registry] = req_data return res
def pull(self, repository, tag=None): registry, repo_name = auth.resolve_repository_name(repository) if repo_name.count(":") == 1: repository, tag = repository.rsplit(":", 1) params = {'tag': tag, 'fromImage': repository} headers = {} if utils.compare_version('1.5', self._version) >= 0: if getattr(self, '_cfg', None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) # do not fail if no atuhentication exists # for this specific registry as we can have a readonly pull if authcfg: headers['X-Registry-Auth'] = auth.encode_header(authcfg) u = self._url("/images/create") return self._result(self.post(u, params=params, headers=headers))
def push(self, repository, authcfg=None): registry, _ = auth.resolve_repository_name(repository) u = self._url("/images/{0}/push".format(repository)) headers = {} if authcfg is None: if getattr(self, '_cfg', None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) if utils.compare_version('1.5', self._version) >= 0: # do not fail if no atuhentication exists # for this specific registry as we can have an anon push if authcfg: headers['X-Registry-Auth'] = auth.encode_header(authcfg) response = self._post_json(u, None, headers=headers, stream=True) else: response = self._post_json(u, authcfg, stream=True) response.raise_for_status() return response.iter_content(1)
def test_load_config_from_file_obj(self): registry = 'https://your.private.registry.io' auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii') config = { registry: { 'auth': '{0}'.format(auth_), 'email': '*****@*****.**' } } f = io.StringIO(six.text_type(json.dumps(config))) cfg = auth.load_config(f) assert registry in cfg assert cfg[registry] is not None cfg = cfg[registry] assert cfg['username'] == 'sakuya' assert cfg['password'] == 'izayoi' assert cfg['email'] == '*****@*****.**' assert cfg.get('auth') is None
def test_load_config_with_random_name(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, ".{0}.dockercfg".format(random.randrange(100000))) registry = "https://your.private.registry.io" auth_ = base64.b64encode(b"sakuya:izayoi").decode("ascii") config = {registry: {"auth": "{0}".format(auth_), "email": "*****@*****.**"}} with open(dockercfg_path, "w") as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert registry in cfg self.assertNotEqual(cfg[registry], None) cfg = cfg[registry] self.assertEqual(cfg["username"], "sakuya") self.assertEqual(cfg["password"], "izayoi") self.assertEqual(cfg["email"], "*****@*****.**") self.assertEqual(cfg.get("auth"), None)
def push(self, repository, stream=False): registry, repo_name = auth.resolve_repository_name(repository) u = self._url("/images/{0}/push".format(repository)) headers = {} if getattr(self, "_cfg", None) is None: self._cfg = auth.load_config() authcfg = auth.resolve_authconfig(self._cfg, registry) if utils.compare_version("1.5", self._version) >= 0: # do not fail if no atuhentication exists # for this specific registry as we can have an anon push if authcfg: headers["X-Registry-Auth"] = auth.encode_header(authcfg) if stream: return self._stream_helper(self._post_json(u, None, headers=headers, stream=True)) else: return self._result(self._post_json(u, None, headers=headers, stream=False)) if stream: return self._stream_helper(self._post_json(u, authcfg, stream=True)) else: return self._result(self._post_json(u, authcfg, stream=False))
def test_load_config_custom_config_env_utf8(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, "config.json") registry = "https://your.private.registry.io" auth_ = base64.b64encode(b"sakuya\xc3\xa6:izayoi\xc3\xa6").decode("ascii") config = {"auths": {registry: {"auth": "{0}".format(auth_), "email": "*****@*****.**"}}} with open(dockercfg_path, "w") as f: json.dump(config, f) with mock.patch.dict(os.environ, {"DOCKER_CONFIG": folder}): cfg = auth.load_config(None) assert registry in cfg self.assertNotEqual(cfg[registry], None) cfg = cfg[registry] self.assertEqual(cfg["username"], b"sakuya\xc3\xa6".decode("utf8")) self.assertEqual(cfg["password"], b"izayoi\xc3\xa6".decode("utf8")) self.assertEqual(cfg["email"], "*****@*****.**") self.assertEqual(cfg.get("auth"), None)
def _run(self): registry = LoginTask.registry_for_container(self.container, self._registries) if not registry: # No registry found, or no registry login needed. return if not registry.get('username'): registry_auth_config = auth.load_config().\ get(urlparse.urlparse(registry['registry']).netloc) registry['username'] = registry_auth_config.get('username') \ if registry_auth_config else None if not registry.get('username'): # Still no username found; bail out. return retry_spec = LoginTask.get_registry_retry_spec(registry) args = dict((k, registry[k]) for k in ['username', 'password', 'email', 'registry']) self.o.reset() self.o.pending('logging in to {}...'.format(registry['registry'])) attempts = retry_spec['attempts'] while attempts > 0: try: self.container.ship.backend.login(**args) break except APIError as e: status = e.response.status_code if status in retry_spec['when']: self.o.pending(red('... got {}; retrying in 1s' .format(status))) attempts -= 1 time.sleep(1) continue raise exceptions.ContainerOrchestrationException( self.container, 'Login to {} as {} failed: {}' .format(registry['registry'], registry['username'], e))
def push_image(self, name, tag=None): ''' If the name of the image contains a repository path, then push the image. :param name Name of the image to push. :param tag Use a specific tag. :return: None ''' repository = name if not tag: repository, tag = utils.parse_repository_tag(name) registry, repo_name = auth.resolve_repository_name(repository) if re.search('/', repository): if registry: config = auth.load_config() if not auth.resolve_authconfig(config, registry): self.fail("Error: configuration for %s not found. Try logging into %s first." % registry) self.log("pushing image %s" % repository) self.results['actions'].append("Pushed image %s to %s:%s" % (self.name, self.repository, self.tag)) self.results['changed'] = True if not self.check_mode: status = None try: for line in self.client.push(repository, tag=tag, stream=True): line = json.loads(line) self.log(line, pretty_print=True) if line.get('errorDetail'): raise Exception(line['errorDetail']['message']) status = line.get('status') except Exception as exc: if re.search('unauthorized', str(exc)): self.fail("Error pushing image %s: %s. Does the repository exist?" % (repository, str(exc))) self.fail("Error pushing image %s: %s" % (repository, str(exc))) self.results['image'] = self.client.find_image(name=repository, tag=tag) if not self.results['image']: self.results['image'] = dict() self.results['image']['push_status'] = status
def push_image(self, name, tag=None): ''' Push an image to a repository. :param name - name of the image to push. Type: str :param tag - use a specific tag. Type: str :return: None ''' repository = name if not tag: repository, tag = utils.parse_repository_tag(name) registry, repo_name = auth.resolve_repository_name(repository) if registry: config = auth.load_config() if not auth.resolve_authconfig(config, registry): self.fail("Error: configuration for %s not found. Try logging into %s first." % registry) try: self.log("pushing image %s" % (repository)) status = None if not self.check_mode: self.results['actions'].append("Pushed image %s to %s:%s" % (self.name, self.repository, self.tag)) for line in self.client.push(repository, tag=tag, stream=True): response = json.loads(line) self.log(response, pretty_print=True) if response.get('errorDetail'): # there was an error raise Exception(response['errorDetail']['message']) status = response.get('status') self.results['changed'] = True image = self.client.find_image(name=repository, tag=tag) if image: self.results['image'] = image self.results['image']['push_status'] = status except Exception, exc: if re.search(r'unauthorized', str(exc)): self.fail("Error pushing image %s: %s. Does the repository exist?" % (repository, str(exc))) self.fail("Error pushing image %s: %s" % (repository, str(exc)))
def test_load_config_custom_config_env_with_headers(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, 'config.json') config = { 'HttpHeaders': { 'Name': 'Spike', 'Surname': 'Spiegel' }, } with open(dockercfg_path, 'w') as f: json.dump(config, f) with mock.patch.dict(os.environ, {'DOCKER_CONFIG': folder}): cfg = auth.load_config(None) assert 'HttpHeaders' in cfg self.assertNotEqual(cfg['HttpHeaders'], None) cfg = cfg['HttpHeaders'] self.assertEqual(cfg['Name'], 'Spike') self.assertEqual(cfg['Surname'], 'Spiegel')
def test_load_config_identity_token(self): folder = tempfile.mkdtemp() registry = 'scarlet.net' token = '1ce1cebb-503e-7043-11aa-7feb8bd4a1ce' self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, 'config.json') auth_entry = encode_auth({'username': '******'}).decode('ascii') config = { 'auths': { registry: { 'auth': auth_entry, 'identitytoken': token } } } with open(dockercfg_path, 'w') as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert registry in cfg cfg = cfg[registry] assert 'IdentityToken' in cfg assert cfg['IdentityToken'] == token
def _run(self): registry = LoginTask.registry_for_container(self.container, self._registries) if not registry.get('username'): registry_auth_config = auth.load_config().\ get(urlparse.urlparse(registry['registry']).netloc) registry['username'] = registry_auth_config.get('username') \ if registry_auth_config else None if not registry or not registry['username']: return self.o.reset() self.o.pending('logging in to {}...'.format(registry['registry'])) try: self.container.ship.backend.login(**registry) except Exception as e: raise exceptions.ContainerOrchestrationException( self.container, 'Login to {} as {} failed: {}'.format(registry['registry'], registry['username'], e))
def test_load_config_identity_token(self): folder = tempfile.mkdtemp() registry = 'scarlet.net' token = '1ce1cebb-503e-7043-11aa-7feb8bd4a1ce' self.addCleanup(shutil.rmtree, folder) dockercfg_path = os.path.join(folder, 'config.json') auth_entry = encode_auth({'username': '******'}).decode('ascii') config = { 'auths': { registry: { 'auth': auth_entry, 'identitytoken': token } } } with open(dockercfg_path, 'w') as f: json.dump(config, f) cfg = auth.load_config(dockercfg_path) assert registry in cfg['auths'] cfg = cfg['auths'][registry] assert 'IdentityToken' in cfg assert cfg['IdentityToken'] == token
def _swarm_login(self): config_file = os.path.join(os.environ['HOME'], '.docker', 'config.json') registry = self._args.SERVER try: conf = load_config(config_file) except errors.InvalidConfigFile as e: print(e) exit(1) username_input, password_input, email_input = None, None, None if self._args.username: username_input = self._args.username if conf.get(registry) is not None: if username_input == conf[registry]['username']\ and self._args.password is None: password_input = conf[registry]['password'] else: if conf.get(registry) is not None: username = conf[registry]['username'] prompt = 'Username ({username}): '.format(username=username) string = raw_input(prompt).strip() if string in (username, ''): username_input = username password_input = conf[registry]['password'] email_input = conf[registry]['email'] else: username_input = string else: prompt = 'Username: '******'username'] == username_input: password_input = conf[registry]['password'] else: prompt = 'Password: '******'Password: '******'email'] else: prompt = 'Email: ' email_input = raw_input(prompt).strip() ret = self._args.func(username_input, password=password_input, email=email_input, registry=registry) if ret is not None: if ret.get('Status') == 'Login Succeeded': try: if os.path.exists(config_file): with open(config_file) as f: data = json.load(f) else: data = { 'auths': {} } auth = base64.b64encode('{user}:{passwd}'.format(user=username_input,passwd=password_input)).decode('ascii') data['auths'][registry] = { 'auth': auth, 'email': email_input } try: os.mkdir(os.path.join(os.environ['HOME'], '.docker')) except OSError as e: if e.errno != os.errno.EEXIST: raise with open(config_file, 'w') as f: f.write(json.dumps(data, indent=4)) except IOError as e: print (e) exit(1) print('WARNING: login credentials saved in {config_file}'.format(config_file=config_file)) print(ret['Status']) elif ret.get('serveraddress') is not None: print('Login Succeeded')
def _swarm_login(self): config_file = os.path.join(os.environ['HOME'], '.docker', 'config.json') registry = self._args.SERVER try: conf = load_config(config_file) except errors.InvalidConfigFile as e: print(e) exit(1) username_input, password_input, email_input = None, None, None if self._args.username: username_input = self._args.username if conf.get(registry) is not None: if username_input == conf[registry]['username'] and\ self._args.password is None: password_input = conf[registry]['password'] else: if conf.get(registry) is not None: username = conf[registry]['username'] prompt = 'Username ({username}): '.format(username=username) string = raw_input(prompt).strip() if string in (username, ''): username_input = username password_input = conf[registry]['password'] email_input = conf[registry]['email'] else: username_input = string else: prompt = 'Username: '******'username'] == username_input: password_input = conf[registry]['password'] else: prompt = 'Password: '******'Password: '******'email'] else: prompt = 'Email: ' email_input = raw_input(prompt).strip() ret = self._args.func(username_input, password=password_input, email=email_input, registry=registry) if ret is not None: if ret.get('Status') == 'Login Succeeded': try: if os.path.exists(config_file): with open(config_file) as f: data = json.load(f) else: data = { 'auths': {} } auth = base64.b64encode('{user}:{passwd}'.format(user=username_input,\ passwd=password_input)).decode('ascii') data['auths'][registry] = { 'auth': auth, 'email': email_input } try: os.mkdir(os.path.join(os.environ['HOME'], '.docker')) except OSError as e: if e.errno != os.errno.EEXIST: raise with open(config_file, 'w') as f: f.write(json.dumps(data, indent=4)) except IOError as e: print (e) exit(1) print('WARNING: login credentials saved in {config_file}'.format(config_file=config_file)) print(ret['Status']) elif ret.get('serveraddress') is not None: print('Login Succeeded')
def test_load_config_no_file(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) cfg = auth.load_config(folder) self.assertTrue(cfg is not None)
def test_load_config_no_file(self): folder = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, folder) cfg = auth.load_config(folder) assert cfg is not None