amazon-auth 0.2.1__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.
Files changed (35) hide show
  1. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/PKG-INFO +2 -2
  2. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/README.md +1 -1
  3. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazon_auth.egg-info/PKG-INFO +2 -2
  4. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/__init__.py +1 -1
  5. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/conf.py +3 -5
  6. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/constants.py +32 -9
  7. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/browser/playwright.py +22 -12
  8. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/session.py +42 -21
  9. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/util.py +31 -0
  10. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/tests/test_conf.py +16 -0
  11. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/tests/test_constants.py +37 -6
  12. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/tests/test_session.py +85 -0
  13. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/LICENSE +0 -0
  14. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazon_auth.egg-info/SOURCES.txt +0 -0
  15. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazon_auth.egg-info/dependency_links.txt +0 -0
  16. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazon_auth.egg-info/requires.txt +0 -0
  17. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazon_auth.egg-info/top_level.txt +0 -0
  18. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/cli.py +0 -0
  19. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/__init__.py +0 -0
  20. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/browser/__init__.py +0 -0
  21. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/waf/__init__.py +0 -0
  22. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/waf/anticaptcha.py +0 -0
  23. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/waf/base.py +0 -0
  24. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/waf/capsolver.py +0 -0
  25. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/contrib/waf/twocaptcha.py +0 -0
  26. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/exception.py +0 -0
  27. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/forms.py +0 -0
  28. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/py.typed +0 -0
  29. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/region_data.py +0 -0
  30. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/amazonauth/selectors.py +0 -0
  31. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/pyproject.toml +0 -0
  32. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/setup.cfg +0 -0
  33. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/tests/test_cli.py +0 -0
  34. {amazon_auth-0.2.1 → amazon_auth-0.2.2}/tests/test_package.py +0 -0
  35. {amazon_auth-0.2.1 → 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.1
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
- # amazon-auth
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
  [![Version](https://img.shields.io/pypi/v/amazon-auth)](https://pypi.org/project/amazon-auth)
74
74
  [![Python Versions](https://img.shields.io/pypi/pyversions/amazon-auth.svg)](https://pypi.org/project/amazon-auth)
@@ -1,4 +1,4 @@
1
- # amazon-auth
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
  [![Version](https://img.shields.io/pypi/v/amazon-auth)](https://pypi.org/project/amazon-auth)
4
4
  [![Python Versions](https://img.shields.io/pypi/pyversions/amazon-auth.svg)](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.1
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
- # amazon-auth
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
  [![Version](https://img.shields.io/pypi/v/amazon-auth)](https://pypi.org/project/amazon-auth)
74
74
  [![Python Versions](https://img.shields.io/pypi/pyversions/amazon-auth.svg)](https://pypi.org/project/amazon-auth)
@@ -1,4 +1,4 @@
1
1
  __copyright__ = "Copyright (c) 2026 Alex Laird"
2
2
  __license__ = "MIT"
3
- __version__ = "0.2.1"
3
+ __version__ = "0.2.2"
4
4
  __muppets__ = "no strings attached"
@@ -348,9 +348,7 @@ class AmazonAuthConfig:
348
348
  Persist the current state of this config object to the config file.
349
349
  """
350
350
  with config_file_lock:
351
- os.makedirs(os.path.dirname(self.config_path), exist_ok=True)
351
+ util.make_private_dirs(os.path.dirname(self.config_path))
352
352
 
353
- with open(self.config_path, "w") as config_file:
354
- logger.debug(f"Saving config to {self.config_path} ...")
355
-
356
- yaml.dump(self._data, config_file)
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, and a site that
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
- @staticmethod
248
- def _normalize_base_url(value: str) -> str:
249
- value = value.strip().rstrip("/")
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
- return value
252
- if value.startswith("www."):
253
- return f"https://{value}"
254
- return f"https://www.{value}"
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
- pw_cookie["name"],
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
- os.makedirs(output_dir, exist_ok=True)
361
- page.screenshot(path=os.path.join(output_dir, f"{name}.png"))
362
- with open(os.path.join(output_dir, f"{name}.html"), "w", encoding="utf-8") as f:
363
- f.write(page.content())
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,7 +985,7 @@ 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"], domain=cookie["domain"], path=cookie.get("path", "/"))
988
+ cookie_jar.set(cookie["name"], cookie["value"], **_jar_cookie_attributes(cookie))
979
989
 
980
990
  def _verify_session(self) -> None:
981
991
  try:
@@ -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
- os.makedirs(os.path.dirname(self.config.cookie_jar_path), exist_ok=True)
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
- os.makedirs(self.config.output_dir, exist_ok=True)
252
- page_name = self._get_page_from_url(self.config.output_dir, amazon_session_response.response.url)
253
- with open(os.path.join(self.config.output_dir, page_name), "w",
254
- encoding="utf-8") as html_file:
255
- logger.debug(
256
- f"Response written to file: {html_file.name}")
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
- file_descriptor, temp_path = tempfile.mkstemp(dir=os.path.dirname(self.config.cookie_jar_path),
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 = 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,6 +3,8 @@ __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
@@ -172,6 +174,20 @@ some_custom_config: {custom_config}
172
174
  self.assertEqual("amazonauth.constants.AuthConstants", config.constants_class)
173
175
  self.assertIs(AuthConstants, type(config.constants))
174
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
+
175
191
  def test_update_config(self):
176
192
  # GIVEN
177
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 test_domain_unknown_tld_keeps_default_sign_in_and_session_values(self):
173
- # GIVEN / WHEN
174
- config = AmazonAuthConfig(data={"domain": "amazon.example"})
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("usflex", config.constants.SIGN_IN_QUERY_PARAMS["openid.assoc_handle"])
178
- self.assertEqual(["x-main"], config.constants.COOKIES_SET_WHEN_AUTHENTICATED)
179
- self.assertEqual({}, config.constants.REQUEST_COOKIES)
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