amazon-auth 0.2.0__tar.gz → 0.2.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/PKG-INFO +2 -2
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/README.md +1 -1
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazon_auth.egg-info/PKG-INFO +2 -2
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/__init__.py +1 -1
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/conf.py +38 -11
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/constants.py +32 -9
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/browser/playwright.py +23 -13
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/session.py +42 -21
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/util.py +31 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/tests/test_conf.py +69 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/tests/test_constants.py +37 -6
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/tests/test_session.py +85 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/LICENSE +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazon_auth.egg-info/SOURCES.txt +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazon_auth.egg-info/dependency_links.txt +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazon_auth.egg-info/requires.txt +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazon_auth.egg-info/top_level.txt +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/cli.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/__init__.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/browser/__init__.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/waf/__init__.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/waf/anticaptcha.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/waf/base.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/waf/capsolver.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/contrib/waf/twocaptcha.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/exception.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/forms.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/py.typed +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/region_data.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/amazonauth/selectors.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/pyproject.toml +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/setup.cfg +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/tests/test_cli.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/tests/test_package.py +0 -0
- {amazon_auth-0.2.0 → amazon_auth-0.2.2}/tests/test_util.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: amazon-auth
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Sign in to Amazon's consumer website and reuse the session from Python.
|
|
5
5
|
Author-email: Alex Laird <contact@alexlaird.com>
|
|
6
6
|
Maintainer-email: Alex Laird <contact@alexlaird.com>
|
|
@@ -68,7 +68,7 @@ Requires-Dist: types-Pillow; extra == "dev"
|
|
|
68
68
|
Requires-Dist: responses; extra == "dev"
|
|
69
69
|
Dynamic: license-file
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
<p align="center"><img alt="amazon-auth - Sign in to Amazon's consumer website from Python" src="https://amazon-auth.readthedocs.io/_images/logo.png" /></p>
|
|
72
72
|
|
|
73
73
|
[](https://pypi.org/project/amazon-auth)
|
|
74
74
|
[](https://pypi.org/project/amazon-auth)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center"><img alt="amazon-auth - Sign in to Amazon's consumer website from Python" src="https://amazon-auth.readthedocs.io/_images/logo.png" /></p>
|
|
2
2
|
|
|
3
3
|
[](https://pypi.org/project/amazon-auth)
|
|
4
4
|
[](https://pypi.org/project/amazon-auth)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: amazon-auth
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: Sign in to Amazon's consumer website and reuse the session from Python.
|
|
5
5
|
Author-email: Alex Laird <contact@alexlaird.com>
|
|
6
6
|
Maintainer-email: Alex Laird <contact@alexlaird.com>
|
|
@@ -68,7 +68,7 @@ Requires-Dist: types-Pillow; extra == "dev"
|
|
|
68
68
|
Requires-Dist: responses; extra == "dev"
|
|
69
69
|
Dynamic: license-file
|
|
70
70
|
|
|
71
|
-
|
|
71
|
+
<p align="center"><img alt="amazon-auth - Sign in to Amazon's consumer website from Python" src="https://amazon-auth.readthedocs.io/_images/logo.png" /></p>
|
|
72
72
|
|
|
73
73
|
[](https://pypi.org/project/amazon-auth)
|
|
74
74
|
[](https://pypi.org/project/amazon-auth)
|
|
@@ -5,7 +5,7 @@ import inspect
|
|
|
5
5
|
import logging
|
|
6
6
|
import os
|
|
7
7
|
import threading
|
|
8
|
-
from typing import Any, Dict, Optional, Union
|
|
8
|
+
from typing import Any, Dict, Optional, Set, Union
|
|
9
9
|
from urllib.parse import urlparse
|
|
10
10
|
|
|
11
11
|
import yaml
|
|
@@ -67,6 +67,7 @@ class AmazonAuthConfig:
|
|
|
67
67
|
self._environment: Dict[str, Any] = self.read_environment()
|
|
68
68
|
self._resolved_classes: Dict[str, Any] = {}
|
|
69
69
|
self._assigned_classes: Dict[str, Any] = {}
|
|
70
|
+
self._unavailable_class_paths: Set[str] = set()
|
|
70
71
|
|
|
71
72
|
with config_file_lock:
|
|
72
73
|
if os.path.exists(self.config_path):
|
|
@@ -174,10 +175,35 @@ class AmazonAuthConfig:
|
|
|
174
175
|
Instantiate the constants and selectors, which the auth layer itself uses and so are always
|
|
175
176
|
needed. The entity, output, and Transactions page classes resolve on first use instead.
|
|
176
177
|
"""
|
|
177
|
-
selectors_class_split = self._class_path("selectors_class").split(".")
|
|
178
|
-
|
|
179
178
|
self.constants = self._instantiate_constants()
|
|
180
|
-
self.selectors =
|
|
179
|
+
self.selectors = self._load_configured_class("selectors_class")()
|
|
180
|
+
|
|
181
|
+
def _load_configured_class(self,
|
|
182
|
+
key: str) -> Any:
|
|
183
|
+
"""
|
|
184
|
+
Load the class the given config key names. The config file can be shared with other packages built on this
|
|
185
|
+
one, which save their own class paths to it, so a class whose package isn't installed here falls back to the
|
|
186
|
+
default, with a warning. Any other failure to load it is raised.
|
|
187
|
+
|
|
188
|
+
:param key: The config key naming the class.
|
|
189
|
+
:return: The class.
|
|
190
|
+
"""
|
|
191
|
+
class_path = self._class_path(key)
|
|
192
|
+
module_path, class_name = class_path.rsplit(".", 1)
|
|
193
|
+
try:
|
|
194
|
+
return util.load_class(module_path.split("."), class_name)
|
|
195
|
+
except ModuleNotFoundError as e:
|
|
196
|
+
default_class_path = self._default_data()[key]
|
|
197
|
+
if (class_path == default_class_path or not e.name or
|
|
198
|
+
not (module_path == e.name or module_path.startswith(f"{e.name}."))):
|
|
199
|
+
raise
|
|
200
|
+
|
|
201
|
+
if class_path not in self._unavailable_class_paths:
|
|
202
|
+
self._unavailable_class_paths.add(class_path)
|
|
203
|
+
logger.warning(f"Configured {key} '{class_path}' is unavailable, since '{e.name}' isn't installed; "
|
|
204
|
+
f"using the default '{default_class_path}'.")
|
|
205
|
+
default_module_path, default_class_name = default_class_path.rsplit(".", 1)
|
|
206
|
+
return util.load_class(default_module_path.split("."), default_class_name)
|
|
181
207
|
|
|
182
208
|
def _validate_class_paths(self) -> None:
|
|
183
209
|
"""
|
|
@@ -209,8 +235,7 @@ class AmazonAuthConfig:
|
|
|
209
235
|
source["bs4_parser"] = "html.parser"
|
|
210
236
|
|
|
211
237
|
def _instantiate_constants(self) -> Any:
|
|
212
|
-
|
|
213
|
-
constants_cls = util.load_class(constants_class_split[:-1], constants_class_split[-1])
|
|
238
|
+
constants_cls = self._load_configured_class("constants_class")
|
|
214
239
|
# Pass ``self`` only when the constants class accepts a config arg, to keep backward
|
|
215
240
|
# compatibility with existing zero-arg ``constants_class`` subclasses.
|
|
216
241
|
init_params = inspect.signature(constants_cls.__init__).parameters
|
|
@@ -283,6 +308,7 @@ class AmazonAuthConfig:
|
|
|
283
308
|
self.__dict__.update(state)
|
|
284
309
|
self.__dict__.setdefault("_environment", {})
|
|
285
310
|
self._resolved_classes = {}
|
|
311
|
+
self._unavailable_class_paths = set()
|
|
286
312
|
self._load_classes()
|
|
287
313
|
|
|
288
314
|
def update_config(self,
|
|
@@ -302,6 +328,9 @@ class AmazonAuthConfig:
|
|
|
302
328
|
try:
|
|
303
329
|
self._validate_bs4_parser()
|
|
304
330
|
self._validate_class_paths()
|
|
331
|
+
if key in ("constants_class", "selectors_class"):
|
|
332
|
+
module_path, class_name = self._class_path(key).rsplit(".", 1)
|
|
333
|
+
util.load_class(module_path.split("."), class_name)
|
|
305
334
|
self._load_classes()
|
|
306
335
|
except (AmazonAuthError, AttributeError, ImportError):
|
|
307
336
|
self._data = previous_data
|
|
@@ -319,9 +348,7 @@ class AmazonAuthConfig:
|
|
|
319
348
|
Persist the current state of this config object to the config file.
|
|
320
349
|
"""
|
|
321
350
|
with config_file_lock:
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
with open(self.config_path, "w") as config_file:
|
|
325
|
-
logger.debug(f"Saving config to {self.config_path} ...")
|
|
351
|
+
util.make_private_dirs(os.path.dirname(self.config_path))
|
|
326
352
|
|
|
327
|
-
|
|
353
|
+
logger.debug(f"Saving config to {self.config_path} ...")
|
|
354
|
+
util.write_private_file(self.config_path, yaml.dump(self._data))
|
|
@@ -6,6 +6,7 @@ from typing import Dict, Optional
|
|
|
6
6
|
from urllib.parse import urlencode, urlparse
|
|
7
7
|
|
|
8
8
|
from amazonauth.conf import AmazonAuthConfig
|
|
9
|
+
from amazonauth.exception import AmazonAuthError
|
|
9
10
|
from amazonauth.region_data import REGION_SITES
|
|
10
11
|
|
|
11
12
|
logger = logging.getLogger(__name__)
|
|
@@ -173,10 +174,10 @@ class AuthConstants:
|
|
|
173
174
|
Override the URL-derived attributes for the given Amazon domain, and the values that depend on which Amazon
|
|
174
175
|
site it is, from its region data: the sign-in ``openid.assoc_handle`` (Amazon rejects a sign-in, with HTTP 404,
|
|
175
176
|
whose handle doesn't match the site), ``Accept-Language``, and
|
|
176
|
-
``COOKIES_SET_WHEN_AUTHENTICATED``. Each is applied only when a subclass hasn't overridden it
|
|
177
|
-
isn't known keeps the defaults.
|
|
177
|
+
``COOKIES_SET_WHEN_AUTHENTICATED``. Each is applied only when a subclass hasn't overridden it.
|
|
178
178
|
|
|
179
179
|
:param domain: The Amazon domain (e.g. ``amazon.com.au``) or full URL (e.g. ``https://www.amazon.com.au``).
|
|
180
|
+
:raises AmazonAuthError: If the domain isn't an Amazon site in the region data, over ``https``.
|
|
180
181
|
"""
|
|
181
182
|
base_url = self._normalize_base_url(domain)
|
|
182
183
|
tld = self._tld(base_url)
|
|
@@ -244,11 +245,33 @@ class AuthConstants:
|
|
|
244
245
|
host = host[len("www."):]
|
|
245
246
|
return host[len("amazon."):] if host.startswith("amazon.") else ""
|
|
246
247
|
|
|
247
|
-
@
|
|
248
|
-
def _normalize_base_url(
|
|
249
|
-
|
|
248
|
+
@classmethod
|
|
249
|
+
def _normalize_base_url(cls,
|
|
250
|
+
domain: str) -> str:
|
|
251
|
+
"""
|
|
252
|
+
The base URL for an Amazon domain or full URL. Only Amazon's own sites, in the region data and over ``https``,
|
|
253
|
+
are accepted, so sign-in never sends credentials to another host, whether through a typo or a value a
|
|
254
|
+
downstream passed along.
|
|
255
|
+
|
|
256
|
+
:param domain: The Amazon domain (e.g. ``amazon.com.au``) or full URL (e.g. ``https://www.amazon.com.au``).
|
|
257
|
+
:return: The base URL.
|
|
258
|
+
:raises AmazonAuthError: If the domain isn't an Amazon site in the region data, over ``https``.
|
|
259
|
+
"""
|
|
260
|
+
value = domain.strip().rstrip("/")
|
|
250
261
|
if value.startswith(("http://", "https://")):
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
262
|
+
base_url = value
|
|
263
|
+
elif value.startswith("www."):
|
|
264
|
+
base_url = f"https://{value}"
|
|
265
|
+
else:
|
|
266
|
+
base_url = f"https://www.{value}"
|
|
267
|
+
|
|
268
|
+
parsed = urlparse(base_url)
|
|
269
|
+
host = (parsed.hostname or "").removeprefix("www.")
|
|
270
|
+
if (parsed.scheme == "https" and host.startswith("amazon.") and cls._tld(base_url) in REGION_SITES and
|
|
271
|
+
not (parsed.port or parsed.username or parsed.password or parsed.path or parsed.params or
|
|
272
|
+
parsed.query or parsed.fragment)):
|
|
273
|
+
return base_url
|
|
274
|
+
|
|
275
|
+
supported_sites = ", ".join(f"amazon.{tld}" for tld in sorted(REGION_SITES))
|
|
276
|
+
raise AmazonAuthError(f"The domain \"{domain}\" isn't an Amazon site. Use one of {supported_sites}, as "
|
|
277
|
+
f"amazon.<site> or https://www.amazon.<site>.")
|
|
@@ -25,7 +25,7 @@ from amazonauth.exception import (
|
|
|
25
25
|
AmazonAuthWafSolverError,
|
|
26
26
|
)
|
|
27
27
|
from amazonauth.forms import AuthForm
|
|
28
|
-
from amazonauth.util import AmazonSessionResponse, has_display
|
|
28
|
+
from amazonauth.util import AmazonSessionResponse, has_display, make_private_dirs, write_private_file
|
|
29
29
|
|
|
30
30
|
if TYPE_CHECKING:
|
|
31
31
|
from amazonauth.contrib.waf.base import AwsWafForm
|
|
@@ -39,6 +39,17 @@ SIGN_IN_SETTLE_MS = 2000
|
|
|
39
39
|
SIGN_IN_PREFILL_TIMEOUT_MS = 5000
|
|
40
40
|
|
|
41
41
|
|
|
42
|
+
def _jar_cookie_attributes(pw_cookie: Dict[str, Any]) -> Dict[str, Any]:
|
|
43
|
+
"""
|
|
44
|
+
The attributes of a browser cookie, as the session's cookie jar takes them. ``secure`` is kept, so a cookie only
|
|
45
|
+
sent over ``https`` in the browser is only sent over ``https`` by the session too.
|
|
46
|
+
"""
|
|
47
|
+
expires = pw_cookie.get("expires", -1)
|
|
48
|
+
return {"domain": pw_cookie.get("domain"), "path": pw_cookie.get("path", "/"),
|
|
49
|
+
"secure": bool(pw_cookie.get("secure", False)),
|
|
50
|
+
"expires": int(expires) if expires and expires > 0 else None}
|
|
51
|
+
|
|
52
|
+
|
|
42
53
|
class PlaywrightBrowserLauncher:
|
|
43
54
|
"""
|
|
44
55
|
Launches the browser the config selects, from whatever Playwright supports. ``browser`` is either a browser that's
|
|
@@ -338,6 +349,8 @@ class PlaywrightAuthForm(AuthForm):
|
|
|
338
349
|
"value": cookie.value or "",
|
|
339
350
|
"domain": cookie.domain or domain,
|
|
340
351
|
"path": cookie.path or "/",
|
|
352
|
+
"secure": bool(cookie.secure),
|
|
353
|
+
"expires": cookie.expires if cookie.expires else -1,
|
|
341
354
|
})
|
|
342
355
|
if playwright_cookies:
|
|
343
356
|
context.add_cookies(playwright_cookies)
|
|
@@ -346,21 +359,18 @@ class PlaywrightAuthForm(AuthForm):
|
|
|
346
359
|
if not self.amazon_session:
|
|
347
360
|
return # pragma: no cover
|
|
348
361
|
for pw_cookie in context.cookies():
|
|
349
|
-
self.amazon_session.session.cookies.set(
|
|
350
|
-
|
|
351
|
-
pw_cookie["value"],
|
|
352
|
-
domain=pw_cookie.get("domain"),
|
|
353
|
-
path=pw_cookie.get("path", "/"),
|
|
354
|
-
)
|
|
362
|
+
self.amazon_session.session.cookies.set(pw_cookie["name"], pw_cookie["value"],
|
|
363
|
+
**_jar_cookie_attributes(pw_cookie))
|
|
355
364
|
|
|
356
365
|
def _save_debug_snapshot(self, page: Any, output_dir: Optional[str], name: str) -> None:
|
|
357
366
|
if not output_dir:
|
|
358
367
|
return
|
|
359
368
|
try:
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
369
|
+
make_private_dirs(output_dir)
|
|
370
|
+
screenshot_path = os.path.join(output_dir, f"{name}.png")
|
|
371
|
+
page.screenshot(path=screenshot_path)
|
|
372
|
+
os.chmod(screenshot_path, 0o600)
|
|
373
|
+
write_private_file(os.path.join(output_dir, f"{name}.html"), page.content())
|
|
364
374
|
logger.debug(f"Debug snapshot saved: {name} (url={page.url})")
|
|
365
375
|
except Exception:
|
|
366
376
|
logger.debug(f"Debug snapshot failed to save: {name}", exc_info=True)
|
|
@@ -975,11 +985,11 @@ class PlaywrightBrowserLogin:
|
|
|
975
985
|
cookie_jar = self.amazon_session.session.cookies
|
|
976
986
|
cookie_jar.clear()
|
|
977
987
|
for cookie in self._amazon_cookies(context.cookies()):
|
|
978
|
-
cookie_jar.set(cookie["name"], cookie["value"],
|
|
988
|
+
cookie_jar.set(cookie["name"], cookie["value"], **_jar_cookie_attributes(cookie))
|
|
979
989
|
|
|
980
990
|
def _verify_session(self) -> None:
|
|
981
991
|
try:
|
|
982
|
-
response = self.amazon_session.get(self.config.constants.
|
|
992
|
+
response = self.amazon_session.get(self.config.constants.SESSION_CHECK_URL, persist_cookies=True)
|
|
983
993
|
self.amazon_session.check_response(response)
|
|
984
994
|
except AmazonAuthRedirectError as e:
|
|
985
995
|
self.amazon_session.logout()
|
|
@@ -4,7 +4,6 @@ __license__ = "MIT"
|
|
|
4
4
|
import json
|
|
5
5
|
import logging
|
|
6
6
|
import os
|
|
7
|
-
import tempfile
|
|
8
7
|
import time
|
|
9
8
|
from typing import Any, Dict, List, Optional, Type, Union
|
|
10
9
|
from urllib.parse import urlparse
|
|
@@ -18,7 +17,7 @@ from amazonauth.conf import AmazonAuthConfig, cookies_file_lock, debug_output_fi
|
|
|
18
17
|
from amazonauth.exception import AmazonAuthSignInError, AmazonAuthError, AmazonAuthRedirectError
|
|
19
18
|
from amazonauth.forms import (AuthForm, AcicAuthBlocker, CaptchaForm, JSAuthBlocker, MfaDeviceSelectForm, MfaForm,
|
|
20
19
|
SignInForm, ClaimForm, IntentForm, PasskeyForm)
|
|
21
|
-
from amazonauth.util import AmazonSessionResponse, load_class, select_one
|
|
20
|
+
from amazonauth.util import AmazonSessionResponse, load_class, make_private_dirs, select_one, write_private_file
|
|
22
21
|
|
|
23
22
|
logger = logging.getLogger(__name__)
|
|
24
23
|
|
|
@@ -59,6 +58,38 @@ class IODefault:
|
|
|
59
58
|
return input(f"--> {msg}: ")
|
|
60
59
|
|
|
61
60
|
|
|
61
|
+
class RedirectGuardSession(Session):
|
|
62
|
+
"""
|
|
63
|
+
A :class:`requests.Session` that follows redirects only where it's safe to: never to ``http``, never re-sending
|
|
64
|
+
a request's data (like a sign-in form, with its password) to another site, and without the ``Origin`` and
|
|
65
|
+
``Referer`` that name the Amazon page it came from when it leaves the site.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def rebuild_auth(self,
|
|
69
|
+
prepared_request: requests.PreparedRequest,
|
|
70
|
+
response: Response) -> None:
|
|
71
|
+
super().rebuild_auth(prepared_request, response)
|
|
72
|
+
|
|
73
|
+
destination = urlparse(prepared_request.url)
|
|
74
|
+
if destination.scheme != "https":
|
|
75
|
+
raise AmazonAuthError(f"Refused to follow a redirect from {response.url} to {prepared_request.url}, "
|
|
76
|
+
"which isn't over https.")
|
|
77
|
+
|
|
78
|
+
if not self._is_same_site(urlparse(response.url).hostname, destination.hostname):
|
|
79
|
+
if prepared_request.body is not None:
|
|
80
|
+
raise AmazonAuthError(f"Refused to follow a redirect from {response.url} to {prepared_request.url}, "
|
|
81
|
+
"which would send the request's data to another site.")
|
|
82
|
+
for header in ("Origin", "Referer"):
|
|
83
|
+
prepared_request.headers.pop(header, None)
|
|
84
|
+
|
|
85
|
+
@staticmethod
|
|
86
|
+
def _is_same_site(origin_host: Optional[str],
|
|
87
|
+
destination_host: Optional[str]) -> bool:
|
|
88
|
+
site = (origin_host or "").lower().removeprefix("www.")
|
|
89
|
+
host = (destination_host or "").lower()
|
|
90
|
+
return bool(site) and (host == site or host.endswith(f".{site}"))
|
|
91
|
+
|
|
92
|
+
|
|
62
93
|
class AmazonSession:
|
|
63
94
|
"""
|
|
64
95
|
An interface for interacting with Amazon and authenticating an underlying :class:`requests.Session`. Utilizing
|
|
@@ -143,7 +174,7 @@ class AmazonSession:
|
|
|
143
174
|
self._cookie_jar_mtime: Optional[float] = None
|
|
144
175
|
|
|
145
176
|
with cookies_file_lock:
|
|
146
|
-
|
|
177
|
+
make_private_dirs(os.path.dirname(self.config.cookie_jar_path))
|
|
147
178
|
|
|
148
179
|
if os.path.exists(self.config.cookie_jar_path):
|
|
149
180
|
with open(self.config.cookie_jar_path, "r", encoding="utf-8") as f:
|
|
@@ -248,13 +279,12 @@ class AmazonSession:
|
|
|
248
279
|
logger.debug(f"Response: {amazon_session_response.response.status_code}{url_str}")
|
|
249
280
|
|
|
250
281
|
if not binary:
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
html_file.write(amazon_session_response.response.text)
|
|
282
|
+
make_private_dirs(self.config.output_dir)
|
|
283
|
+
page_path = os.path.join(self.config.output_dir,
|
|
284
|
+
self._get_page_from_url(self.config.output_dir,
|
|
285
|
+
amazon_session_response.response.url))
|
|
286
|
+
write_private_file(page_path, amazon_session_response.response.text)
|
|
287
|
+
logger.debug(f"Response written to file: {page_path}")
|
|
258
288
|
|
|
259
289
|
return amazon_session_response
|
|
260
290
|
|
|
@@ -446,16 +476,7 @@ class AmazonSession:
|
|
|
446
476
|
return domain == self.config.site or domain.endswith(f".{self.config.site}")
|
|
447
477
|
|
|
448
478
|
def _write_cookie_jar(self) -> None:
|
|
449
|
-
|
|
450
|
-
prefix=".cookies-", suffix=".tmp")
|
|
451
|
-
try:
|
|
452
|
-
with os.fdopen(file_descriptor, "w", encoding="utf-8") as f:
|
|
453
|
-
f.write(json.dumps(self._cookie_jar_data()))
|
|
454
|
-
os.chmod(temp_path, 0o600)
|
|
455
|
-
os.replace(temp_path, self.config.cookie_jar_path)
|
|
456
|
-
except BaseException:
|
|
457
|
-
os.remove(temp_path)
|
|
458
|
-
raise
|
|
479
|
+
write_private_file(self.config.cookie_jar_path, json.dumps(self._cookie_jar_data()))
|
|
459
480
|
self._cookie_jar_mtime = self._read_cookie_jar_mtime()
|
|
460
481
|
|
|
461
482
|
def _read_cookie_jar_mtime(self) -> Optional[float]:
|
|
@@ -538,7 +559,7 @@ class AmazonSession:
|
|
|
538
559
|
raise AmazonAuthSignInError(error_msg)
|
|
539
560
|
|
|
540
561
|
def _create_session(self) -> Session:
|
|
541
|
-
session =
|
|
562
|
+
session = RedirectGuardSession()
|
|
542
563
|
adapter = requests.adapters.HTTPAdapter(pool_connections=self.config.connection_pool_size,
|
|
543
564
|
pool_maxsize=self.config.connection_pool_size)
|
|
544
565
|
session.mount('https://', adapter)
|
|
@@ -6,6 +6,7 @@ import logging
|
|
|
6
6
|
import os
|
|
7
7
|
import re
|
|
8
8
|
import sys
|
|
9
|
+
import tempfile
|
|
9
10
|
from typing import List, Union, Optional, Callable, Any
|
|
10
11
|
|
|
11
12
|
from bs4 import Tag, BeautifulSoup
|
|
@@ -144,3 +145,33 @@ def cleanup_html_text(text: str) -> str:
|
|
|
144
145
|
if not text.endswith("."):
|
|
145
146
|
text += "."
|
|
146
147
|
return text
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def write_private_file(path: str,
|
|
151
|
+
content: str) -> None:
|
|
152
|
+
"""
|
|
153
|
+
Write a file only the current user can read, since what this package writes holds a session, credentials, or
|
|
154
|
+
account data.
|
|
155
|
+
|
|
156
|
+
:param path: The file to write.
|
|
157
|
+
:param content: The text to write.
|
|
158
|
+
"""
|
|
159
|
+
file_descriptor, temp_path = tempfile.mkstemp(dir=os.path.dirname(path) or ".",
|
|
160
|
+
prefix=f".{os.path.basename(path)}-", suffix=".tmp")
|
|
161
|
+
try:
|
|
162
|
+
with os.fdopen(file_descriptor, "w", encoding="utf-8") as f:
|
|
163
|
+
f.write(content)
|
|
164
|
+
os.chmod(temp_path, 0o600)
|
|
165
|
+
os.replace(temp_path, path)
|
|
166
|
+
except BaseException:
|
|
167
|
+
os.remove(temp_path)
|
|
168
|
+
raise
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def make_private_dirs(path: str) -> None:
|
|
172
|
+
"""
|
|
173
|
+
Create a directory, and any missing parents, that only the current user can access.
|
|
174
|
+
|
|
175
|
+
:param path: The directory to create.
|
|
176
|
+
"""
|
|
177
|
+
os.makedirs(path, mode=0o700, exist_ok=True)
|
|
@@ -3,13 +3,17 @@ __license__ = "MIT"
|
|
|
3
3
|
|
|
4
4
|
import os
|
|
5
5
|
import pickle
|
|
6
|
+
import sys
|
|
7
|
+
import unittest
|
|
6
8
|
from unittest.mock import patch
|
|
7
9
|
|
|
8
10
|
import yaml
|
|
9
11
|
|
|
10
12
|
from amazonauth import conf
|
|
11
13
|
from amazonauth.conf import AmazonAuthConfig
|
|
14
|
+
from amazonauth.constants import AuthConstants
|
|
12
15
|
from amazonauth.exception import AmazonAuthError
|
|
16
|
+
from amazonauth.selectors import AuthSelectors
|
|
13
17
|
from tests.unittestcase import UnitTestCase
|
|
14
18
|
|
|
15
19
|
|
|
@@ -119,6 +123,71 @@ some_custom_config: {custom_config}
|
|
|
119
123
|
self.assertEqual("html.parser", config.bs4_parser)
|
|
120
124
|
self.assertTrue(any("this-parser-does-not-exist" in m for m in logs.output))
|
|
121
125
|
|
|
126
|
+
def test_class_whose_package_is_not_installed_falls_back_to_default(self):
|
|
127
|
+
# GIVEN
|
|
128
|
+
config_path = self.given_config_file("constants_class: some_uninstalled_package.constants.Constants\n"
|
|
129
|
+
"selectors_class: some_uninstalled_package.selectors.Selectors\n")
|
|
130
|
+
|
|
131
|
+
# WHEN
|
|
132
|
+
with self.assertLogs("amazonauth.conf", level="WARNING") as logs:
|
|
133
|
+
config = AmazonAuthConfig(config_path=config_path)
|
|
134
|
+
config.set_domain("amazon.de")
|
|
135
|
+
|
|
136
|
+
# THEN
|
|
137
|
+
self.assertIs(AuthConstants, type(config.constants))
|
|
138
|
+
self.assertIs(AuthSelectors, type(config.selectors))
|
|
139
|
+
self.assertEqual(2, len(logs.output))
|
|
140
|
+
self.assertIn("constants_class 'some_uninstalled_package.constants.Constants' is unavailable", logs.output[0])
|
|
141
|
+
self.assertIn("selectors_class 'some_uninstalled_package.selectors.Selectors' is unavailable", logs.output[1])
|
|
142
|
+
self.assertEqual("some_uninstalled_package.constants.Constants", config.constants_class)
|
|
143
|
+
self.assertIs(AuthConstants, type(pickle.loads(pickle.dumps(config)).constants))
|
|
144
|
+
|
|
145
|
+
def test_class_missing_from_installed_module_raises(self):
|
|
146
|
+
# GIVEN
|
|
147
|
+
config_path = self.given_config_file("constants_class: amazonauth.constants.NoSuchConstants\n")
|
|
148
|
+
|
|
149
|
+
# WHEN / THEN
|
|
150
|
+
with self.assertRaises(AttributeError):
|
|
151
|
+
AmazonAuthConfig(config_path=config_path)
|
|
152
|
+
|
|
153
|
+
def test_class_whose_own_import_fails_raises(self):
|
|
154
|
+
# GIVEN
|
|
155
|
+
config_path = self.given_config_file("constants_class: constants_needing_uninstalled_package.Constants\n")
|
|
156
|
+
dependency_error = ModuleNotFoundError("No module named 'some_uninstalled_dependency'",
|
|
157
|
+
name="some_uninstalled_dependency")
|
|
158
|
+
|
|
159
|
+
# WHEN / THEN
|
|
160
|
+
with patch("amazonauth.util.importlib.import_module", side_effect=dependency_error), \
|
|
161
|
+
self.assertRaises(ModuleNotFoundError) as cm:
|
|
162
|
+
AmazonAuthConfig(config_path=config_path)
|
|
163
|
+
self.assertEqual("some_uninstalled_dependency", cm.exception.name)
|
|
164
|
+
|
|
165
|
+
def test_update_config_with_class_whose_package_is_not_installed_raises(self):
|
|
166
|
+
# GIVEN
|
|
167
|
+
config = AmazonAuthConfig()
|
|
168
|
+
|
|
169
|
+
# WHEN
|
|
170
|
+
with self.assertRaises(ModuleNotFoundError):
|
|
171
|
+
config.update_config("constants_class", "some_uninstalled_package.constants.Constants")
|
|
172
|
+
|
|
173
|
+
# THEN
|
|
174
|
+
self.assertEqual("amazonauth.constants.AuthConstants", config.constants_class)
|
|
175
|
+
self.assertIs(AuthConstants, type(config.constants))
|
|
176
|
+
|
|
177
|
+
@unittest.skipIf(sys.platform == "win32", reason="Windows does not support POSIX file permissions")
|
|
178
|
+
def test_saved_config_is_owner_only(self):
|
|
179
|
+
# GIVEN
|
|
180
|
+
config_path = self.given_config_file("max_auth_attempts: 3\n")
|
|
181
|
+
os.chmod(config_path, 0o644)
|
|
182
|
+
config = AmazonAuthConfig(config_path=config_path)
|
|
183
|
+
|
|
184
|
+
# WHEN
|
|
185
|
+
config.update_config("otp_secret_key", "test-otp-secret-key")
|
|
186
|
+
|
|
187
|
+
# THEN
|
|
188
|
+
self.assertEqual(0o600, os.stat(config_path).st_mode & 0o777)
|
|
189
|
+
self.assertEqual([], [name for name in os.listdir(os.path.dirname(config_path)) if name.endswith(".tmp")])
|
|
190
|
+
|
|
122
191
|
def test_update_config(self):
|
|
123
192
|
# GIVEN
|
|
124
193
|
config = AmazonAuthConfig(data={
|
|
@@ -6,6 +6,7 @@ from unittest.mock import patch
|
|
|
6
6
|
|
|
7
7
|
from amazonauth.conf import AmazonAuthConfig
|
|
8
8
|
from amazonauth.constants import AuthConstants
|
|
9
|
+
from amazonauth.exception import AmazonAuthError
|
|
9
10
|
from amazonauth.region_data import REGION_SITES
|
|
10
11
|
from tests.unittestcase import UnitTestCase
|
|
11
12
|
|
|
@@ -169,14 +170,44 @@ class TestConstants(UnitTestCase):
|
|
|
169
170
|
self.assertEqual(AuthConstants.BASE_HEADERS["Referer"], config.constants.BASE_HEADERS["Referer"])
|
|
170
171
|
self.assertEqual(["x-main"], config.constants.COOKIES_SET_WHEN_AUTHENTICATED)
|
|
171
172
|
|
|
172
|
-
def
|
|
173
|
-
|
|
174
|
-
|
|
173
|
+
def test_domain_that_is_not_an_amazon_site_raises(self):
|
|
174
|
+
for domain in ["amazon.example", "amzon.de", "evil.example", "smile.amazon.com", "amazon.de.evil.example",
|
|
175
|
+
"https://amazon.com.evil.example", "http://www.amazon.de", "https://www.amazon.de/path",
|
|
176
|
+
"https://www.amazon.de:8443", "https://user:password@www.amazon.de"]:
|
|
177
|
+
with self.subTest(domain=domain):
|
|
178
|
+
# WHEN
|
|
179
|
+
with self.assertRaises(AmazonAuthError) as cm:
|
|
180
|
+
AmazonAuthConfig(data={"domain": domain})
|
|
181
|
+
|
|
182
|
+
# THEN
|
|
183
|
+
self.assertIn(f"The domain \"{domain}\" isn't an Amazon site.", str(cm.exception))
|
|
184
|
+
self.assertIn("amazon.co.uk", str(cm.exception))
|
|
185
|
+
|
|
186
|
+
def test_domain_forms_of_an_amazon_site_are_accepted(self):
|
|
187
|
+
for domain, base_url in [("amazon.de", "https://www.amazon.de"), ("www.amazon.de", "https://www.amazon.de"),
|
|
188
|
+
("https://www.amazon.co.uk/", "https://www.amazon.co.uk"),
|
|
189
|
+
("https://amazon.com.au", "https://amazon.com.au")]:
|
|
190
|
+
with self.subTest(domain=domain):
|
|
191
|
+
# WHEN
|
|
192
|
+
config = AmazonAuthConfig(data={"domain": domain})
|
|
193
|
+
|
|
194
|
+
# THEN
|
|
195
|
+
self.assertEqual(base_url, config.constants.BASE_URL)
|
|
196
|
+
|
|
197
|
+
def test_update_config_with_domain_that_is_not_an_amazon_site_raises_and_keeps_previous(self):
|
|
198
|
+
# GIVEN
|
|
199
|
+
config = AmazonAuthConfig(data={"domain": "amazon.de"})
|
|
200
|
+
config.save()
|
|
201
|
+
|
|
202
|
+
# WHEN
|
|
203
|
+
with self.assertRaises(AmazonAuthError):
|
|
204
|
+
config.update_config("domain", "amazon.de.evil.example")
|
|
175
205
|
|
|
176
206
|
# THEN
|
|
177
|
-
self.assertEqual("
|
|
178
|
-
self.assertEqual(
|
|
179
|
-
|
|
207
|
+
self.assertEqual("amazon.de", config.domain)
|
|
208
|
+
self.assertEqual("https://www.amazon.de", config.constants.BASE_URL)
|
|
209
|
+
with open(config.config_path, "r") as f:
|
|
210
|
+
self.assertNotIn("evil", f.read())
|
|
180
211
|
|
|
181
212
|
def test_domain_sets_region_language_cookie(self):
|
|
182
213
|
for tld, site in REGION_SITES.items():
|
|
@@ -494,6 +494,91 @@ class TestSession(UnitTestCase):
|
|
|
494
494
|
self.assertEqual([], [name for name in os.listdir(os.path.dirname(self.test_config.cookie_jar_path))
|
|
495
495
|
if name.endswith(".tmp")])
|
|
496
496
|
|
|
497
|
+
@unittest.skipIf(sys.platform == "win32", reason="Windows does not support POSIX file permissions")
|
|
498
|
+
@responses.activate
|
|
499
|
+
def test_debug_page_and_output_dir_are_owner_only(self):
|
|
500
|
+
# GIVEN
|
|
501
|
+
amazon_session = AmazonSession("some-username@gmail.com", "some-password", debug=True,
|
|
502
|
+
config=self.test_config)
|
|
503
|
+
responses.add(responses.GET, f"{self.test_config.constants.BASE_URL}/some/page",
|
|
504
|
+
body="<html><body>debug page</body></html>", status=200)
|
|
505
|
+
|
|
506
|
+
# WHEN
|
|
507
|
+
amazon_session.get(f"{self.test_config.constants.BASE_URL}/some/page")
|
|
508
|
+
|
|
509
|
+
# THEN
|
|
510
|
+
self.assertEqual(0o700, os.stat(self.test_output_dir).st_mode & 0o777)
|
|
511
|
+
page_name = os.listdir(self.test_output_dir)[0]
|
|
512
|
+
self.assertEqual(0o600, os.stat(os.path.join(self.test_output_dir, page_name)).st_mode & 0o777)
|
|
513
|
+
|
|
514
|
+
@responses.activate
|
|
515
|
+
def test_redirect_to_http_is_refused(self):
|
|
516
|
+
# GIVEN
|
|
517
|
+
amazon_session = AmazonSession(config=self.test_config)
|
|
518
|
+
amazon_session.session.cookies.set("at-main", "auth-token-value", domain=".amazon.com", path="/")
|
|
519
|
+
responses.add(responses.GET, "https://www.amazon.com/some/page", status=302,
|
|
520
|
+
headers={"Location": "http://www.amazon.com/other/page"})
|
|
521
|
+
insecure_response = responses.add(responses.GET, "http://www.amazon.com/other/page", body="insecure")
|
|
522
|
+
|
|
523
|
+
# WHEN
|
|
524
|
+
with self.assertRaises(AmazonAuthError) as cm:
|
|
525
|
+
amazon_session.get("https://www.amazon.com/some/page")
|
|
526
|
+
|
|
527
|
+
# THEN
|
|
528
|
+
self.assertIn("which isn't over https", str(cm.exception))
|
|
529
|
+
self.assertEqual(0, insecure_response.call_count)
|
|
530
|
+
|
|
531
|
+
@responses.activate
|
|
532
|
+
def test_redirect_resending_data_to_another_site_is_refused(self):
|
|
533
|
+
# GIVEN
|
|
534
|
+
amazon_session = AmazonSession(config=self.test_config)
|
|
535
|
+
responses.add(responses.POST, "https://www.amazon.com/ap/signin", status=307,
|
|
536
|
+
headers={"Location": "https://other.example/collect"})
|
|
537
|
+
other_site_response = responses.add(responses.POST, "https://other.example/collect", body="collected")
|
|
538
|
+
|
|
539
|
+
# WHEN
|
|
540
|
+
with self.assertRaises(AmazonAuthError) as cm:
|
|
541
|
+
amazon_session.post("https://www.amazon.com/ap/signin", data={"password": "some-password"})
|
|
542
|
+
|
|
543
|
+
# THEN
|
|
544
|
+
self.assertIn("would send the request's data to another site", str(cm.exception))
|
|
545
|
+
self.assertEqual(0, other_site_response.call_count)
|
|
546
|
+
|
|
547
|
+
@responses.activate
|
|
548
|
+
def test_redirect_to_another_site_drops_origin_referer_and_cookies(self):
|
|
549
|
+
# GIVEN
|
|
550
|
+
amazon_session = AmazonSession(config=self.test_config)
|
|
551
|
+
amazon_session.session.cookies.set("at-main", "auth-token-value", domain=".amazon.com", path="/")
|
|
552
|
+
responses.add(responses.GET, "https://www.amazon.com/some/invoice", status=302,
|
|
553
|
+
headers={"Location": "https://files.example/invoice.pdf"})
|
|
554
|
+
other_site_response = responses.add(responses.GET, "https://files.example/invoice.pdf", body=b"%PDF")
|
|
555
|
+
|
|
556
|
+
# WHEN
|
|
557
|
+
amazon_session.get("https://www.amazon.com/some/invoice", binary=True)
|
|
558
|
+
|
|
559
|
+
# THEN
|
|
560
|
+
request = other_site_response.calls[0].request
|
|
561
|
+
self.assertNotIn("Origin", request.headers)
|
|
562
|
+
self.assertNotIn("Referer", request.headers)
|
|
563
|
+
self.assertNotIn("auth-token-value", request.headers.get("Cookie", ""))
|
|
564
|
+
|
|
565
|
+
@responses.activate
|
|
566
|
+
def test_redirect_within_the_site_keeps_data_and_headers(self):
|
|
567
|
+
# GIVEN
|
|
568
|
+
amazon_session = AmazonSession(config=self.test_config)
|
|
569
|
+
responses.add(responses.POST, "https://www.amazon.com/ap/signin", status=307,
|
|
570
|
+
headers={"Location": "https://na.account.amazon.com/ap/signin"})
|
|
571
|
+
same_site_response = responses.add(responses.POST, "https://na.account.amazon.com/ap/signin", body="ok")
|
|
572
|
+
|
|
573
|
+
# WHEN
|
|
574
|
+
amazon_session.post("https://www.amazon.com/ap/signin", data={"email": "some-username@gmail.com"})
|
|
575
|
+
|
|
576
|
+
# THEN
|
|
577
|
+
request = same_site_response.calls[0].request
|
|
578
|
+
self.assertEqual("email=some-username%40gmail.com", request.body)
|
|
579
|
+
self.assertIn("Origin", request.headers)
|
|
580
|
+
self.assertIn("Referer", request.headers)
|
|
581
|
+
|
|
497
582
|
@unittest.skipIf(sys.platform == "win32", reason="Windows does not support POSIX file permissions")
|
|
498
583
|
@responses.activate
|
|
499
584
|
def test_persisted_cookie_jar_is_owner_only(self):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|