Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add auth_plugin with tests #16942

Merged
merged 19 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions conan/cli/commands/remote.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,16 @@ def remote_login(conan_api, parser, subparser, *args):
raise ConanException("There are no remotes matching the '{}' pattern".format(args.remote))

creds = RemoteCredentials(conan_api.cache_folder, conan_api.config.global_conf)
user, password = creds.auth(args.remote, args.username, args.password)
if args.username is not None and args.username != user:
raise ConanException(f"User '{args.username}' doesn't match user '{user}' in "
f"credentials.json or environment variables")

ret = OrderedDict()
for r in remotes:
previous_info = conan_api.remotes.user_info(r)

user, password = creds.auth(r, args.username, args.password)
if args.username is not None and args.username != user:
raise ConanException(f"User '{args.username}' doesn't match user '{user}' in "
f"credentials.json or environment variables")

conan_api.remotes.user_login(r, user, password)
info = conan_api.remotes.user_info(r)
ret[r.name] = {"previous_info": previous_info, "info": info}
Expand Down
4 changes: 4 additions & 0 deletions conan/internal/cache/home_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ def profiles_path(self):
def profile_plugin_path(self):
return os.path.join(self._home, _EXTENSIONS_FOLDER, _PLUGINS, "profile.py")

@property
def auth_plugin_path(self):
return os.path.join(self._home, _EXTENSIONS_FOLDER, _PLUGINS, "auth.py")

@property
def sign_plugin_path(self):
return os.path.join(self._home, _EXTENSIONS_FOLDER, _PLUGINS, "sign", "sign.py")
Expand Down
33 changes: 27 additions & 6 deletions conans/client/rest/remote_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,19 @@

from jinja2 import Template

from conan.internal.cache.home_paths import HomePaths

from conans.client.loader import load_python_file
from conan.api.output import ConanOutput
from conans.client.userio import UserInput
from conans.errors import ConanException
from conans.errors import ConanException, scoped_traceback
from conans.util.files import load


class RemoteCredentials:
def __init__(self, cache_folder, global_conf):
self._global_conf = global_conf
self._urls = {}
self.auth_plugin_path = HomePaths(cache_folder).auth_plugin_path
creds_path = os.path.join(cache_folder, "credentials.json")
if not os.path.exists(creds_path):
return
Expand All @@ -32,24 +35,36 @@ def auth(self, remote, user=None, password=None):
if user is not None and password is not None:
return user, password

# First prioritize the cache "credentials.json" file
creds = self._urls.get(remote)
# First get the auth_plugin
auth_plugin = _load_auth_plugin(self.auth_plugin_path)
if auth_plugin is not None:
ErniGH marked this conversation as resolved.
Show resolved Hide resolved
try:
plugin_user, plugin_password = auth_plugin(remote, user=user, password=password)
except Exception as e:
msg = f"Error while processing 'auth.py' plugin"
msg = scoped_traceback(msg, e, scope="/extensions/plugins")
raise ConanException(msg)
if plugin_user and plugin_password:
return plugin_user, plugin_password

# Then prioritize the cache "credentials.json" file
creds = self._urls.get(remote.name)
if creds is not None:
try:
return creds["user"], creds["password"]
except KeyError as e:
raise ConanException(f"Authentication error, wrong credentials.json: {e}")

# Then, check environment definition
env_user, env_passwd = self._get_env(remote, user)
env_user, env_passwd = self._get_env(remote.name, user)
ErniGH marked this conversation as resolved.
Show resolved Hide resolved
if env_passwd is not None:
if env_user is None:
raise ConanException("Found password in env-var, but not defined user")
return env_user, env_passwd

# If not found, then interactive prompt
ui = UserInput(self._global_conf.get("core:non_interactive", check_type=bool))
input_user, input_password = ui.request_login(remote, user)
input_user, input_password = ui.request_login(remote.name, user)
return input_user, input_password

@staticmethod
Expand All @@ -66,3 +81,9 @@ def _get_env(remote, user):
if passwd:
ConanOutput().info("Got password '******' from environment")
return user, passwd

def _load_auth_plugin(auth_plugin_path):
if os.path.exists(auth_plugin_path):
mod, _ = load_python_file(auth_plugin_path)
if hasattr(mod, "auth_plugin"):
return mod.auth_plugin
ErniGH marked this conversation as resolved.
Show resolved Hide resolved
60 changes: 60 additions & 0 deletions test/integration/configuration/test_auth_plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os
import textwrap

import pytest

from conan.test.utils.tools import TestClient
from conans.util.files import save


class TestErrorsAuthPlugin:
""" when the plugin fails, we want a clear message and a helpful trace
"""
def test_error_profile_plugin(self):
c = TestClient(default_server_user=True)
auth_plugin = textwrap.dedent("""\
def auth_plugin(remote, user=None, password=None):
raise Exception("Test Error")
""")
save(os.path.join(c.cache.plugins_path, "auth.py"), auth_plugin)
c.run("remote logout default")
c.run("remote login default", assert_error=True)
assert "Error while processing 'auth.py' plugin" in c.out
assert "Test Error" in c.out

def test_remove_plugin_file(self):
c = TestClient()
c.run("version") # to trigger the creation
os.remove(os.path.join(c.cache.plugins_path, "auth.py"))
c.run("remote add default http://fake")
c.run("remote login default", assert_error=True)
assert "ERROR: The 'auth.py' plugin file doesn't exist" in c.out

@pytest.mark.parametrize("password", ["password", "bad-password"])
def test_profile_plugin_direct_credentials(self, password):
should_fail = password == "bad-password"
c = TestClient(default_server_user=True)
auth_plugin = textwrap.dedent(f"""\
def auth_plugin(remote, user=None, password=None):
return "admin", "{password}"
""")
save(os.path.join(c.cache.plugins_path, "auth.py"), auth_plugin)
c.run("remote logout default")
c.run("remote login default", assert_error=should_fail)
if should_fail:
assert "ERROR: Wrong user or password. [Remote: default]" in c.out
else:
assert "Changed user of remote 'default' from 'None' (anonymous) to 'admin' (authenticated)" in c.out

def test_profile_plugin_fallback(self):
ErniGH marked this conversation as resolved.
Show resolved Hide resolved
c = TestClient(default_server_user=True)
auth_plugin = textwrap.dedent("""\
def auth_plugin(remote, user=None, password=None):
return None, None
""")
save(os.path.join(c.cache.plugins_path, "auth.py"), auth_plugin)
c.run("remote logout default")
c.run("remote login default")
# As the auth plugin is not returning any password the code is falling back to the rest of
# the input methods in this case the stdin provided by TestClient.
assert "Changed user of remote 'default' from 'None' (anonymous) to 'admin' (authenticated)" in c.out