-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathpassword_manager.py
226 lines (167 loc) · 6.89 KB
/
password_manager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
from __future__ import annotations
import dataclasses
import logging
from contextlib import suppress
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from poetry.config.config import Config
logger = logging.getLogger(__name__)
class PasswordManagerError(Exception):
pass
class PoetryKeyringError(Exception):
pass
@dataclasses.dataclass
class HTTPAuthCredential:
username: str | None = dataclasses.field(default=None)
password: str | None = dataclasses.field(default=None)
class PoetryKeyring:
def __init__(self, namespace: str) -> None:
self._namespace = namespace
self._is_available = True
self._check()
def is_available(self) -> bool:
return self._is_available
def get_credential(
self, *names: str, username: str | None = None
) -> HTTPAuthCredential:
default = HTTPAuthCredential(username=username, password=None)
if not self.is_available():
return default
import keyring
for name in names:
credential = keyring.get_credential(name, username)
if credential:
return HTTPAuthCredential(
username=credential.username, password=credential.password
)
return default
def get_password(self, name: str, username: str) -> str | None:
if not self.is_available():
return None
import keyring
import keyring.errors
name = self.get_entry_name(name)
try:
return keyring.get_password(name, username)
except (RuntimeError, keyring.errors.KeyringError):
raise PoetryKeyringError(
f"Unable to retrieve the password for {name} from the key ring"
)
def set_password(self, name: str, username: str, password: str) -> None:
if not self.is_available():
return
import keyring
import keyring.errors
name = self.get_entry_name(name)
try:
keyring.set_password(name, username, password)
except (RuntimeError, keyring.errors.KeyringError) as e:
raise PoetryKeyringError(
f"Unable to store the password for {name} in the key ring: {e}"
)
def delete_password(self, name: str, username: str) -> None:
if not self.is_available():
return
import keyring.errors
name = self.get_entry_name(name)
try:
keyring.delete_password(name, username)
except (RuntimeError, keyring.errors.KeyringError):
raise PoetryKeyringError(
f"Unable to delete the password for {name} from the key ring"
)
def get_entry_name(self, name: str) -> str:
return f"{self._namespace}-{name}"
def _check(self) -> None:
try:
import keyring
except Exception as e:
logger.debug(f"An error occurred while importing keyring: {e!s}")
self._is_available = False
return
backend = keyring.get_keyring()
name = backend.name.split(" ")[0]
if name in ("fail", "null"):
logger.debug("No suitable keyring backend found")
self._is_available = False
elif "plaintext" in backend.name.lower():
logger.debug("Only a plaintext keyring backend is available. Not using it.")
self._is_available = False
elif name == "chainer":
try:
import keyring.backend
backends = keyring.backend.get_all_keyring()
self._is_available = any(
b.name.split(" ")[0] not in ["chainer", "fail", "null"]
and "plaintext" not in b.name.lower()
for b in backends
)
except Exception:
self._is_available = False
if not self._is_available:
logger.debug("No suitable keyring backends were found")
class PasswordManager:
def __init__(self, config: Config) -> None:
self._config = config
self._keyring: PoetryKeyring | None = None
@property
def keyring(self) -> PoetryKeyring:
if self._keyring is None:
self._keyring = PoetryKeyring("poetry-repository")
if not self._keyring.is_available():
logger.debug(
"<warning>Keyring is not available, credentials will be stored and "
"retrieved from configuration files as plaintext.</>"
)
return self._keyring
@staticmethod
def warn_plaintext_credentials_stored() -> None:
logger.warning("Using a plaintext file to store credentials")
def set_pypi_token(self, name: str, token: str) -> None:
if not self.keyring.is_available():
self.warn_plaintext_credentials_stored()
self._config.auth_config_source.add_property(f"pypi-token.{name}", token)
else:
self.keyring.set_password(name, "__token__", token)
def get_pypi_token(self, name: str) -> str | None:
if not self.keyring.is_available():
token: str | None = self._config.get(f"pypi-token.{name}")
return token
return self.keyring.get_password(name, "__token__")
def delete_pypi_token(self, name: str) -> None:
if not self.keyring.is_available():
return self._config.auth_config_source.remove_property(f"pypi-token.{name}")
self.keyring.delete_password(name, "__token__")
def get_http_auth(self, name: str) -> dict[str, str | None] | None:
auth = self._config.get(f"http-basic.{name}")
if not auth:
username = self._config.get(f"http-basic.{name}.username")
password = self._config.get(f"http-basic.{name}.password")
if not username and not password:
return None
else:
username, password = auth["username"], auth.get("password")
if password is None:
password = self.keyring.get_password(name, username)
return {
"username": username,
"password": password,
}
def set_http_password(self, name: str, username: str, password: str) -> None:
auth = {"username": username}
if not self.keyring.is_available():
self.warn_plaintext_credentials_stored()
auth["password"] = password
else:
self.keyring.set_password(name, username, password)
self._config.auth_config_source.add_property(f"http-basic.{name}", auth)
def delete_http_password(self, name: str) -> None:
auth = self.get_http_auth(name)
if not auth:
return
username = auth.get("username")
if username is None:
return
with suppress(PoetryKeyringError):
self.keyring.delete_password(name, username)
self._config.auth_config_source.remove_property(f"http-basic.{name}")