Skip to content

Commit 888c3b6

Browse files
committed
Abstract provider interface to keyring
1 parent 4fc2008 commit 888c3b6

File tree

1 file changed

+126
-55
lines changed

1 file changed

+126
-55
lines changed

src/pip/_internal/network/auth.py

Lines changed: 126 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
providing credentials in the context of network requests.
55
"""
66

7+
import os
78
import shutil
89
import subprocess
910
import urllib.parse
10-
from typing import Any, Dict, List, NamedTuple, Optional, Tuple
11+
from abc import ABC, abstractmethod
12+
from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Type
1113

1214
from pip._vendor.requests.auth import AuthBase, HTTPBasicAuth
1315
from pip._vendor.requests.models import Request, Response
@@ -27,89 +29,157 @@
2729

2830

2931
class Credentials(NamedTuple):
30-
service_name: str
32+
url: str
3133
username: str
3234
password: str
3335

3436

35-
class KeyRingCli:
36-
"""Mirror the parts of keyring's API which pip uses
37+
class KeyRingBaseProvider(ABC):
38+
"""Keyring base provider interface"""
39+
40+
@classmethod
41+
@abstractmethod
42+
def is_available(cls) -> bool:
43+
...
44+
45+
@classmethod
46+
@abstractmethod
47+
def get_auth_info(cls, url: str, username: Optional[str]) -> Optional[AuthInfo]:
48+
...
49+
50+
@classmethod
51+
@abstractmethod
52+
def save_auth_info(cls, url: str, username: str, password: str) -> None:
53+
...
54+
55+
56+
class KeyRingPythonProvider(KeyRingBaseProvider):
57+
"""Keyring interface which uses locally imported `keyring`"""
58+
59+
try:
60+
import keyring
61+
except ImportError:
62+
keyring = None # type: ignore[assignment]
63+
64+
@classmethod
65+
def is_available(cls) -> bool:
66+
return cls.keyring is not None
67+
68+
@classmethod
69+
def get_auth_info(cls, url: str, username: Optional[str]) -> Optional[AuthInfo]:
70+
if cls.is_available is False:
71+
return None
72+
73+
# Support keyring's get_credential interface which supports getting
74+
# credentials without a username. This is only available for
75+
# keyring>=15.2.0.
76+
if hasattr(cls.keyring, "get_credential"):
77+
logger.debug("Getting credentials from keyring for %s", url)
78+
cred = cls.keyring.get_credential(url, username)
79+
if cred is not None:
80+
return cred.username, cred.password
81+
return None
82+
83+
if username is not None:
84+
logger.debug("Getting password from keyring for %s", url)
85+
password = cls.keyring.get_password(url, username)
86+
if password:
87+
return username, password
88+
return None
89+
90+
@classmethod
91+
def save_auth_info(cls, url: str, username: str, password: str) -> None:
92+
cls.keyring.set_password(url, username, password)
93+
94+
95+
class KeyRingCliProvider(KeyRingBaseProvider):
96+
"""Provider which uses `keyring` cli
3797
3898
Instead of calling the keyring package installed alongside pip
3999
we call keyring on the command line which will enable pip to
40100
use which ever installation of keyring is available first in
41101
PATH.
42102
"""
43103

44-
def __init__(self, keyring: str) -> None:
45-
self.keyring = keyring
104+
keyring = shutil.which("keyring")
105+
106+
@classmethod
107+
def is_available(cls) -> bool:
108+
return cls.keyring is not None
46109

47-
def get_password(self, service_name: str, username: str) -> Optional[str]:
48-
cmd = [self.keyring, "get", service_name, username]
110+
@classmethod
111+
def get_auth_info(cls, url: str, username: Optional[str]) -> Optional[AuthInfo]:
112+
if cls.is_available is False:
113+
return None
114+
115+
# This is the default implementation of keyring.get_credential
116+
# https://github.com/jaraco/keyring/blob/97689324abcf01bd1793d49063e7ca01e03d7d07/keyring/backend.py#L134-L139
117+
if username is not None:
118+
password = cls._get_password(url, username)
119+
if password is not None:
120+
return username, password
121+
return None
122+
123+
@classmethod
124+
def save_auth_info(cls, url: str, username: str, password: str) -> None:
125+
if not cls.is_available:
126+
raise RuntimeError("keyring is not available")
127+
return cls._set_password(url, username, password)
128+
129+
@classmethod
130+
def _get_password(cls, service_name: str, username: str) -> Optional[str]:
131+
"""Mirror the implemenation of keyring.get_password using cli"""
132+
if cls.keyring is None:
133+
return None
134+
135+
cmd = [cls.keyring, "get", service_name, username]
136+
env = os.environ
137+
env["PYTHONIOENCODING"] = "utf-8"
49138
res = subprocess.run(
50139
cmd,
51140
stdin=subprocess.DEVNULL,
52141
capture_output=True,
53-
env=dict(PYTHONIOENCODING="utf-8"),
142+
env=env,
54143
)
55144
if res.returncode:
56145
return None
57146
return res.stdout.decode("utf-8").strip("\n")
58147

59-
def set_password(self, service_name: str, username: str, password: str) -> None:
60-
cmd = [self.keyring, "set", service_name, username]
148+
@classmethod
149+
def _set_password(cls, service_name: str, username: str, password: str) -> None:
150+
"""Mirror the implemenation of keyring.set_password using cli"""
151+
if cls.keyring is None:
152+
return None
153+
154+
cmd = [cls.keyring, "set", service_name, username]
61155
input_ = password.encode("utf-8") + b"\n"
62-
res = subprocess.run(cmd, input=input_, env=dict(PYTHONIOENCODING="utf-8"))
156+
env = os.environ
157+
env["PYTHONIOENCODING"] = "utf-8"
158+
res = subprocess.run(cmd, input=input_, env=env)
63159
res.check_returncode()
64160
return None
65161

66162

67-
try:
68-
import keyring
69-
except ImportError:
70-
keyring = None # type: ignore[assignment]
71-
keyring_path = shutil.which("keyring")
72-
if keyring_path is not None:
73-
keyring = KeyRingCli(keyring_path) # type: ignore[assignment]
74-
except Exception as exc:
75-
logger.warning(
76-
"Keyring is skipped due to an exception: %s",
77-
str(exc),
78-
)
79-
keyring = None # type: ignore[assignment]
163+
def get_keyring_provider() -> Optional[Type[KeyRingBaseProvider]]:
164+
if KeyRingPythonProvider.is_available():
165+
return KeyRingPythonProvider
166+
if KeyRingCliProvider.is_available():
167+
return KeyRingCliProvider
168+
return None
80169

81170

82171
def get_keyring_auth(url: Optional[str], username: Optional[str]) -> Optional[AuthInfo]:
83172
"""Return the tuple auth for a given url from keyring."""
84-
global keyring
85-
if not url or not keyring:
173+
# Do nothing if no url was provided
174+
if not url:
86175
return None
87176

88-
try:
89-
try:
90-
get_credential = keyring.get_credential
91-
except AttributeError:
92-
pass
93-
else:
94-
logger.debug("Getting credentials from keyring for %s", url)
95-
cred = get_credential(url, username)
96-
if cred is not None:
97-
return cred.username, cred.password
98-
return None
99-
100-
if username:
101-
logger.debug("Getting password from keyring for %s", url)
102-
password = keyring.get_password(url, username)
103-
if password:
104-
return username, password
177+
keyring = get_keyring_provider()
178+
# Do nothin if keyring is not available
179+
if keyring is None:
180+
return None
105181

106-
except Exception as exc:
107-
logger.warning(
108-
"Keyring is skipped due to an exception: %s",
109-
str(exc),
110-
)
111-
keyring = None # type: ignore[assignment]
112-
return None
182+
return keyring.get_auth_info(url, username)
113183

114184

115185
class MultiDomainBasicAuth(AuthBase):
@@ -283,7 +353,7 @@ def _prompt_for_password(
283353

284354
# Factored out to allow for easy patching in tests
285355
def _should_save_password_to_keyring(self) -> bool:
286-
if not keyring:
356+
if get_keyring_provider() is None:
287357
return False
288358
return ask("Save credentials to keyring [y/N]: ", ["y", "n"]) == "y"
289359

@@ -319,7 +389,7 @@ def handle_401(self, resp: Response, **kwargs: Any) -> Response:
319389
# Prompt to save the password to keyring
320390
if save and self._should_save_password_to_keyring():
321391
self._credentials_to_save = Credentials(
322-
service_name=parsed.netloc,
392+
url=parsed.netloc,
323393
username=username,
324394
password=password,
325395
)
@@ -355,15 +425,16 @@ def warn_on_401(self, resp: Response, **kwargs: Any) -> None:
355425

356426
def save_credentials(self, resp: Response, **kwargs: Any) -> None:
357427
"""Response callback to save credentials on success."""
428+
keyring = get_keyring_provider()
358429
assert keyring is not None, "should never reach here without keyring"
359430
if not keyring:
360-
return
431+
return None
361432

362433
creds = self._credentials_to_save
363434
self._credentials_to_save = None
364435
if creds and resp.status_code < 400:
365436
try:
366437
logger.info("Saving credentials to keyring")
367-
keyring.set_password(creds.service_name, creds.username, creds.password)
438+
keyring.save_auth_info(creds.url, creds.username, creds.password)
368439
except Exception:
369440
logger.exception("Failed to save credentials")

0 commit comments

Comments
 (0)