amazon-auth 0.2.4__tar.gz → 0.2.6__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.4 → amazon_auth-0.2.6}/PKG-INFO +8 -2
  2. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/README.md +7 -1
  3. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazon_auth.egg-info/PKG-INFO +8 -2
  4. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/__init__.py +1 -1
  5. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/conf.py +25 -5
  6. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/constants.py +24 -12
  7. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/browser/playwright.py +116 -60
  8. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/waf/anticaptcha.py +3 -5
  9. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/waf/base.py +18 -11
  10. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/waf/capsolver.py +5 -8
  11. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/waf/twocaptcha.py +3 -6
  12. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/exception.py +10 -1
  13. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/session.py +15 -3
  14. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/tests/test_conf.py +25 -0
  15. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/tests/test_constants.py +20 -1
  16. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/tests/test_session.py +64 -2
  17. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/LICENSE +0 -0
  18. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazon_auth.egg-info/SOURCES.txt +0 -0
  19. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazon_auth.egg-info/dependency_links.txt +0 -0
  20. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazon_auth.egg-info/requires.txt +0 -0
  21. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazon_auth.egg-info/top_level.txt +0 -0
  22. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/cli.py +0 -0
  23. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/__init__.py +0 -0
  24. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/browser/__init__.py +0 -0
  25. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/contrib/waf/__init__.py +0 -0
  26. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/forms.py +0 -0
  27. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/py.typed +0 -0
  28. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/region_data.py +0 -0
  29. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/selectors.py +0 -0
  30. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/amazonauth/util.py +0 -0
  31. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/pyproject.toml +0 -0
  32. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/setup.cfg +0 -0
  33. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/tests/test_cli.py +0 -0
  34. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/tests/test_package.py +0 -0
  35. {amazon_auth-0.2.4 → amazon_auth-0.2.6}/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.4
3
+ Version: 0.2.6
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>
@@ -79,7 +79,7 @@ Dynamic: license-file
79
79
 
80
80
  `amazon-auth` is an unofficial library that signs in to Amazon's consumer website (amazon.com and other Amazon sites)
81
81
  and persists the session, so it can be reused from Python. It handles sign-in, OTP and MFA, challenges, and browser
82
- sign-in. [`amazon-orders`](https://github.com/alexdlaird/amazon-orders) is built on it.
82
+ sign-in.
83
83
 
84
84
  > **Note:** This package works by parsing Amazon's consumer-facing website. As Amazon provides no official API to use,
85
85
  > older versions of this package may break at any time, so it's recommended that you use the latest version.
@@ -126,6 +126,12 @@ PlaywrightBrowserLogin(amazon_session).login()
126
126
 
127
127
  The session is persisted, so `AmazonSession().login()` reuses it without credentials.
128
128
 
129
+ ### Building on `amazon-auth`
130
+
131
+ `amazon-auth` is meant to be built on: packages that read more of Amazon's website, like
132
+ [`amazon-orders`](https://amazon-orders.readthedocs.io), subclass its config, session, constants and selectors, and
133
+ register its CLI commands. See [Building on `amazon-auth`](https://amazon-auth.readthedocs.io/downstream.html).
134
+
129
135
  ## Documentation
130
136
 
131
137
  For more advanced usage, `amazon-auth`'s official documentation is available
@@ -9,7 +9,7 @@
9
9
 
10
10
  `amazon-auth` is an unofficial library that signs in to Amazon's consumer website (amazon.com and other Amazon sites)
11
11
  and persists the session, so it can be reused from Python. It handles sign-in, OTP and MFA, challenges, and browser
12
- sign-in. [`amazon-orders`](https://github.com/alexdlaird/amazon-orders) is built on it.
12
+ sign-in.
13
13
 
14
14
  > **Note:** This package works by parsing Amazon's consumer-facing website. As Amazon provides no official API to use,
15
15
  > older versions of this package may break at any time, so it's recommended that you use the latest version.
@@ -56,6 +56,12 @@ PlaywrightBrowserLogin(amazon_session).login()
56
56
 
57
57
  The session is persisted, so `AmazonSession().login()` reuses it without credentials.
58
58
 
59
+ ### Building on `amazon-auth`
60
+
61
+ `amazon-auth` is meant to be built on: packages that read more of Amazon's website, like
62
+ [`amazon-orders`](https://amazon-orders.readthedocs.io), subclass its config, session, constants and selectors, and
63
+ register its CLI commands. See [Building on `amazon-auth`](https://amazon-auth.readthedocs.io/downstream.html).
64
+
59
65
  ## Documentation
60
66
 
61
67
  For more advanced usage, `amazon-auth`'s official documentation is available
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: amazon-auth
3
- Version: 0.2.4
3
+ Version: 0.2.6
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>
@@ -79,7 +79,7 @@ Dynamic: license-file
79
79
 
80
80
  `amazon-auth` is an unofficial library that signs in to Amazon's consumer website (amazon.com and other Amazon sites)
81
81
  and persists the session, so it can be reused from Python. It handles sign-in, OTP and MFA, challenges, and browser
82
- sign-in. [`amazon-orders`](https://github.com/alexdlaird/amazon-orders) is built on it.
82
+ sign-in.
83
83
 
84
84
  > **Note:** This package works by parsing Amazon's consumer-facing website. As Amazon provides no official API to use,
85
85
  > older versions of this package may break at any time, so it's recommended that you use the latest version.
@@ -126,6 +126,12 @@ PlaywrightBrowserLogin(amazon_session).login()
126
126
 
127
127
  The session is persisted, so `AmazonSession().login()` reuses it without credentials.
128
128
 
129
+ ### Building on `amazon-auth`
130
+
131
+ `amazon-auth` is meant to be built on: packages that read more of Amazon's website, like
132
+ [`amazon-orders`](https://amazon-orders.readthedocs.io), subclass its config, session, constants and selectors, and
133
+ register its CLI commands. See [Building on `amazon-auth`](https://amazon-auth.readthedocs.io/downstream.html).
134
+
129
135
  ## Documentation
130
136
 
131
137
  For more advanced usage, `amazon-auth`'s official documentation is available
@@ -1,4 +1,4 @@
1
1
  __copyright__ = "Copyright (c) 2026 Alex Laird"
2
2
  __license__ = "MIT"
3
- __version__ = "0.2.4"
3
+ __version__ = "0.2.6"
4
4
  __muppets__ = "no strings attached"
@@ -5,6 +5,7 @@ import inspect
5
5
  import logging
6
6
  import os
7
7
  import threading
8
+ import warnings
8
9
  from typing import Any, Dict, Optional, Set, Union
9
10
  from urllib.parse import urlparse
10
11
 
@@ -48,6 +49,9 @@ class AmazonAuthConfig:
48
49
  other source, then values passed in code, then the config file, then the defaults. The
49
50
  value of a key with a default is read as YAML, as it would be in the config file, and any other value is used
50
51
  as-is. Environment variables are never persisted to the config file.
52
+
53
+ Its default values can be found
54
+ `here <https://amazon-auth.readthedocs.io/_modules/amazonauth/conf.html#AmazonAuthConfig>`_.
51
55
  """
52
56
 
53
57
  #: The package named in messages that suggest installing something, e.g. ``pip install amazon-auth[lxml]``.
@@ -63,7 +67,7 @@ class AmazonAuthConfig:
63
67
  #: The path to use for the config file.
64
68
  self.config_path: str = os.path.join(DEFAULT_CONFIG_DIR, "config.yml") if config_path is None else config_path
65
69
 
66
- self._data: Dict[str, Any] = self._default_data()
70
+ self._data: Dict[str, Any] = self._defaults()
67
71
  self._environment: Dict[str, Any] = self.read_environment()
68
72
  self._resolved_classes: Dict[str, Any] = {}
69
73
  self._assigned_classes: Dict[str, Any] = {}
@@ -97,7 +101,7 @@ class AmazonAuthConfig:
97
101
  :return: The config values set in the environment, by config key.
98
102
  :raises AmazonAuthError: If the value of a key with a default is not valid YAML.
99
103
  """
100
- default_data = cls._default_data()
104
+ default_data = cls._defaults()
101
105
  environment = {}
102
106
  for name, value in os.environ.items():
103
107
  if not name.startswith(ENVIRONMENT_VARIABLE_PREFIX) or not value:
@@ -133,9 +137,10 @@ class AmazonAuthConfig:
133
137
  return self._data.get(key)
134
138
 
135
139
  @staticmethod
136
- def _default_data() -> Dict[str, Any]:
140
+ def default_data() -> Dict[str, Any]:
137
141
  """
138
- Provision the default config values.
142
+ Provision the default config values. A subclass with config keys of its own adds them here, on top of
143
+ ``AmazonAuthConfig.default_data()``.
139
144
 
140
145
  :return: The default config values.
141
146
  """
@@ -166,6 +171,21 @@ class AmazonAuthConfig:
166
171
  "max_auth_retries": 1
167
172
  }
168
173
 
174
+ @staticmethod
175
+ def _default_data() -> Dict[str, Any]:
176
+ """
177
+ Deprecated, use :func:`default_data` instead. To be removed in 1.0.
178
+ """
179
+ warnings.warn("_default_data() is deprecated and will be removed in 1.0. Override default_data() instead.",
180
+ DeprecationWarning, stacklevel=2)
181
+ return AmazonAuthConfig.default_data()
182
+
183
+ @classmethod
184
+ def _defaults(cls) -> Dict[str, Any]:
185
+ if cls._default_data is not AmazonAuthConfig._default_data:
186
+ return cls._default_data()
187
+ return cls.default_data()
188
+
169
189
  @staticmethod
170
190
  def _default_cookie_jar_path() -> str:
171
191
  return os.path.join(DEFAULT_CONFIG_DIR, "cookies.json")
@@ -193,7 +213,7 @@ class AmazonAuthConfig:
193
213
  try:
194
214
  return util.load_class(module_path.split("."), class_name)
195
215
  except ModuleNotFoundError as e:
196
- default_class_path = self._default_data()[key]
216
+ default_class_path = self._defaults()[key]
197
217
  if (class_path == default_class_path or not e.name or
198
218
  not (module_path == e.name or module_path.startswith(f"{e.name}."))):
199
219
  raise
@@ -2,6 +2,7 @@ __copyright__ = "Copyright (c) 2024-2025 Alex Laird"
2
2
  __license__ = "MIT"
3
3
 
4
4
  import logging
5
+ import warnings
5
6
  from typing import Dict, Optional
6
7
  from urllib.parse import urlencode, urlparse
7
8
 
@@ -120,6 +121,7 @@ class AuthConstants:
120
121
 
121
122
  def __init__(self,
122
123
  config: Optional[AmazonAuthConfig] = None) -> None:
124
+ self._docs_url = config.DOCS_URL if config is not None else AmazonAuthConfig.DOCS_URL
123
125
  if config is not None:
124
126
  domain, browser = config.domain, config.browser
125
127
  else:
@@ -128,7 +130,10 @@ class AuthConstants:
128
130
  if browser:
129
131
  self._apply_browser(browser)
130
132
  if domain:
131
- self._apply_domain(domain)
133
+ if type(self)._apply_domain is not AuthConstants._apply_domain:
134
+ self._apply_domain(domain)
135
+ else:
136
+ self.apply_domain(domain)
132
137
  self._apply_language_cookie(self._tld(self.BASE_URL))
133
138
 
134
139
  @classmethod
@@ -168,13 +173,13 @@ class AuthConstants:
168
173
  headers[key] = value
169
174
  self.BASE_HEADERS = headers
170
175
 
171
- def _apply_domain(self,
172
- domain: str) -> None:
176
+ def apply_domain(self,
177
+ domain: str) -> None:
173
178
  """
174
179
  Override the URL-derived attributes for the given Amazon domain, and the values that depend on which Amazon
175
- site it is, from its region data: the sign-in ``openid.assoc_handle`` (Amazon rejects a sign-in, with HTTP 404,
176
- whose handle doesn't match the site), ``Accept-Language``, and
177
- ``COOKIES_SET_WHEN_AUTHENTICATED``. Each is applied only when a subclass hasn't overridden it.
180
+ site it is, from its region data: the sign-in ``openid.assoc_handle``, ``Accept-Language``, and
181
+ ``COOKIES_SET_WHEN_AUTHENTICATED``. Each is applied only when a subclass hasn't overridden it. A subclass with
182
+ URLs of its own that depend on the site sets them here, after calling ``super().apply_domain(domain)``.
178
183
 
179
184
  :param domain: The Amazon domain (e.g. ``amazon.com.au``) or full URL (e.g. ``https://www.amazon.com.au``).
180
185
  :raises AmazonAuthError: If the domain isn't an Amazon site in the region data, over ``https``.
@@ -212,6 +217,15 @@ class AuthConstants:
212
217
  if auth_cookie and type(self).COOKIES_SET_WHEN_AUTHENTICATED == AuthConstants.COOKIES_SET_WHEN_AUTHENTICATED:
213
218
  self.COOKIES_SET_WHEN_AUTHENTICATED = [auth_cookie]
214
219
 
220
+ def _apply_domain(self,
221
+ domain: str) -> None:
222
+ """
223
+ Deprecated, use :func:`apply_domain` instead. To be removed in 1.0.
224
+ """
225
+ warnings.warn("_apply_domain() is deprecated and will be removed in 1.0. Override apply_domain() instead.",
226
+ DeprecationWarning, stacklevel=2)
227
+ self.apply_domain(domain)
228
+
215
229
  def _apply_language_cookie(self,
216
230
  tld: str) -> None:
217
231
  """
@@ -245,8 +259,7 @@ class AuthConstants:
245
259
  host = host[len("www."):]
246
260
  return host[len("amazon."):] if host.startswith("amazon.") else ""
247
261
 
248
- @classmethod
249
- def _normalize_base_url(cls,
262
+ def _normalize_base_url(self,
250
263
  domain: str) -> str:
251
264
  """
252
265
  The base URL for an Amazon domain or full URL. Only Amazon's own sites, in the region data and over ``https``,
@@ -267,11 +280,10 @@ class AuthConstants:
267
280
 
268
281
  parsed = urlparse(base_url)
269
282
  host = (parsed.hostname or "").removeprefix("www.")
270
- if (parsed.scheme == "https" and host.startswith("amazon.") and cls._tld(base_url) in REGION_SITES and
283
+ if (parsed.scheme == "https" and host.startswith("amazon.") and self._tld(base_url) in REGION_SITES and
271
284
  not (parsed.port or parsed.username or parsed.password or parsed.path or parsed.params or
272
285
  parsed.query or parsed.fragment)):
273
286
  return base_url
274
287
 
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>.")
288
+ raise AmazonAuthError(f"The domain \"{domain}\" isn't an Amazon site. Use one of the sites at "
289
+ f"{self._docs_url}/#sites, as amazon.<site> or https://www.amazon.<site>.")
@@ -18,6 +18,7 @@ from requests import Response
18
18
 
19
19
  from amazonauth.conf import AmazonAuthConfig
20
20
  from amazonauth.exception import (
21
+ AmazonAuthChallengeUnsolvedError,
21
22
  AmazonAuthSignInError,
22
23
  AmazonAuthRedirectError,
23
24
  AmazonAuthBrowserNotInstalledError,
@@ -210,9 +211,8 @@ class PlaywrightBrowserLauncher:
210
211
 
211
212
  class PlaywrightAuthForm(AuthForm):
212
213
  """
213
- Shared base for Playwright-based JavaScript challenge solvers. Subclasses implement
214
- :func:`~amazonauth.forms.AuthForm.select_form` to detect the challenge page and :func:`_is_challenge_url` to
215
- signal when navigation has completed.
214
+ Shared base for Playwright-based JavaScript challenge solvers. Subclasses detect the challenge page with
215
+ :func:`~amazonauth.forms.AuthForm.select_form`, and say when the browser has navigated past it.
216
216
 
217
217
  This base class handles the Playwright browser lifecycle, bidirectional cookie bridging
218
218
  between :mod:`requests` and the Playwright browser context, and re-fetching the final
@@ -238,6 +238,15 @@ class PlaywrightAuthForm(AuthForm):
238
238
  """JavaScript challenge pages have no ``<form>`` to populate; no-op override."""
239
239
  pass
240
240
 
241
+ def check_available(self) -> None:
242
+ """
243
+ Check that this form can handle a challenge here. Every form can, unless it needs something this machine
244
+ doesn't have.
245
+
246
+ :raises AmazonAuthChallengeUnsolvedError: if it can't.
247
+ """
248
+ pass
249
+
241
250
  def submit(self,
242
251
  last_response: Response) -> AmazonSessionResponse:
243
252
  """
@@ -251,12 +260,16 @@ class PlaywrightAuthForm(AuthForm):
251
260
  :raises AmazonAuthError: if the ``playwright`` package is not installed, if
252
261
  :func:`~amazonauth.forms.AuthForm.select_form` was not called first, or if the challenge does not resolve
253
262
  within the timeout.
263
+ :raises AmazonAuthChallengeUnsolvedError: if this form can't handle the challenge here (see
264
+ :func:`check_available`).
254
265
  """
255
266
  if not self.amazon_session:
256
267
  raise AmazonAuthError(
257
268
  "Call PlaywrightAuthForm.select_form() first."
258
269
  ) # pragma: no cover
259
270
 
271
+ self.check_available()
272
+
260
273
  try:
261
274
  from playwright.sync_api import ( # type: ignore[import-not-found]
262
275
  sync_playwright,
@@ -380,14 +393,10 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
380
393
  """
381
394
  Handles Amazon's ACIC (Amazon Challenge and Identity Component) JavaScript challenge
382
395
  by running it in a headless browser. If an embedded AWS WAF challenge or visual grid
383
- Puzzle is present on the ACIC page, it will be solved automatically using the first
384
- :class:`~amazonauth.contrib.waf.base.AwsWafForm` found in ``auth_forms_classes``.
385
-
386
- If no automated solver is registered but a manual solver
387
- (:class:`~amazonauth.contrib.browser.playwright.PlaywrightManualWafForm`) is, a
388
- **visible** browser window is opened instead so the user can solve the embedded
389
- challenge themselves, for free. An automated solver takes precedence when both are
390
- registered.
396
+ Puzzle is present on the ACIC page, it's passed to the solvers registered in ``auth_forms_classes``, in the order
397
+ they're listed: a :class:`~amazonauth.contrib.waf.base.AwsWafForm`, or
398
+ :class:`~amazonauth.contrib.browser.playwright.PlaywrightManualWafForm`, which opens a **visible** browser window
399
+ so the user can solve it themselves. If one can't, the next one is tried.
391
400
 
392
401
  Detects the challenge via the ``#aa-challenge-page-captcha-container`` element and
393
402
  waits for navigation away from ``/ax/aaut/verify/ap/challenge``.
@@ -396,6 +405,12 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
396
405
  :class:`~amazonauth.conf.AmazonAuthConfig`.
397
406
  """
398
407
 
408
+ def __init__(self,
409
+ config: AmazonAuthConfig) -> None:
410
+ super().__init__(config)
411
+ self._solver: Optional[AuthForm] = None
412
+ self._fallback_remains: bool = False
413
+
399
414
  def select_form(self,
400
415
  amazon_session: "AmazonSession",
401
416
  parsed: Tag) -> bool:
@@ -408,41 +423,67 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
408
423
  :return: ``True`` if an ACIC challenge was detected, ``False`` otherwise.
409
424
  """
410
425
  self.amazon_session = amazon_session
411
- detected = bool(parsed.select_one(self.config.selectors.ACIC_CHALLENGE_SELECTOR))
412
- if detected:
413
- self.headless = not self._manual_mode()
414
- return detected
426
+ return bool(parsed.select_one(self.config.selectors.ACIC_CHALLENGE_SELECTOR))
415
427
 
416
- def _manual_mode(self) -> bool:
428
+ def submit(self,
429
+ last_response: Response) -> AmazonSessionResponse:
417
430
  """
418
- Return ``True`` if the embedded challenge should be handed off to a human in a
419
- visible browser window rather than an automated solver. This is the case when a
420
- manual solver form is registered and no automated :class:`~amazonauth.contrib.waf.base.AwsWafForm` is; an
421
- automated solver takes precedence when both are present, since it is
422
- non-interactive.
431
+ Pass the ACIC challenge to each registered solver in turn, in the order they're listed, until one handles it,
432
+ as :func:`PlaywrightAuthForm.submit` does with one.
433
+
434
+ :param last_response: The response that returned the ACIC challenge page.
435
+ :return: The :class:`~amazonauth.util.AmazonSessionResponse` from re-fetching the URL after the challenge
436
+ resolves.
437
+ :raises AmazonAuthError: if the ``playwright`` package is not installed, or if the challenge does not
438
+ resolve within the timeout.
439
+ :raises AmazonAuthChallengeUnsolvedError: if the last solver can't solve it.
423
440
  """
424
- return self._find_manual_solver() is not None and self._find_waf_solver() is None
441
+ solvers = self._available_solvers()
442
+ for index, solver in enumerate(solvers):
443
+ self._solver = solver
444
+ self._fallback_remains = index < len(solvers) - 1
445
+ self.headless = not isinstance(solver, PlaywrightAuthForm)
446
+ try:
447
+ return super().submit(last_response)
448
+ except AmazonAuthChallengeUnsolvedError as e:
449
+ if not self._fallback_remains:
450
+ raise
451
+ logger.debug(f"{type(solver).__name__} couldn't solve the ACIC challenge, trying the next solver: {e}")
452
+
453
+ self._solver = None
454
+ self.headless = True
455
+ return super().submit(last_response)
425
456
 
426
- def _find_waf_solver(self) -> Optional["AwsWafForm"]:
457
+ def _available_solvers(self) -> List[AuthForm]:
427
458
  if not self.amazon_session:
428
- return None # pragma: no cover
459
+ return [] # pragma: no cover
429
460
  from amazonauth.contrib.waf.base import AwsWafForm
430
- return next(
431
- (f for f in self.amazon_session.auth_forms if isinstance(f, AwsWafForm)),
432
- None,
433
- )
434
461
 
435
- def _find_manual_solver(self) -> Optional["PlaywrightAuthForm"]:
436
- if not self.amazon_session:
437
- return None # pragma: no cover
438
- return next(
439
- (f for f in self.amazon_session.auth_forms
440
- if isinstance(f, PlaywrightAuthForm) and f.manual),
441
- None,
442
- )
462
+ solvers: List[AuthForm] = []
463
+ for form in self.amazon_session.auth_forms:
464
+ if not (isinstance(form, AwsWafForm) or (isinstance(form, PlaywrightAuthForm) and form.manual)):
465
+ continue
466
+ try:
467
+ form.check_available()
468
+ solvers.append(form)
469
+ except AmazonAuthChallengeUnsolvedError as e:
470
+ logger.debug(f"{type(form).__name__} can't solve the ACIC challenge here: {e}")
471
+
472
+ return solvers
473
+
474
+ def _unsolved_if_fallback_remains(self,
475
+ error: Exception) -> None:
476
+ if self._fallback_remains:
477
+ raise AmazonAuthChallengeUnsolvedError(str(error), meta=getattr(error, "meta", None)) from error
443
478
 
444
479
  def _on_challenge_page(self, page: Any, context: Any, output_dir: Optional[str]) -> None:
445
- if self._manual_mode():
480
+ from amazonauth.contrib.waf.base import AwsWafForm
481
+
482
+ solver = self._solver
483
+ if solver is None:
484
+ return
485
+
486
+ if not isinstance(solver, AwsWafForm):
446
487
  message = (
447
488
  "Info: A browser window has opened — solve the challenge, then return "
448
489
  "here when done."
@@ -457,25 +498,30 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
457
498
  while solves < max_solves:
458
499
  if not self._is_challenge_url(page.url, page.url):
459
500
  break
460
- if self._try_solve_embedded_waf(page, context, output_dir):
501
+ if self._try_solve_embedded_waf(solver, page, context, output_dir):
461
502
  solves += 1
462
- elif self._try_solve_visual_captcha(page, context, output_dir):
503
+ elif self._try_solve_visual_captcha(solver, page, context, output_dir):
463
504
  solves += 1
464
505
  else:
465
506
  break
466
507
 
467
- def _try_solve_embedded_waf(self, page: Any, context: Any, output_dir: Optional[str]) -> bool:
508
+ def _try_solve_embedded_waf(self,
509
+ waf_form: "AwsWafForm",
510
+ page: Any,
511
+ context: Any,
512
+ output_dir: Optional[str]) -> bool:
468
513
  """
469
- If the ACIC challenge page contains an embedded AWS WAF challenge, solve it
470
- using the first :class:`~amazonauth.contrib.waf.base.AwsWafForm` found in
471
- ``amazon_session.auth_forms``, inject the resulting ``aws-waf-token`` cookie
514
+ If the ACIC challenge page contains an embedded AWS WAF challenge, pass it to the current
515
+ :class:`~amazonauth.contrib.waf.base.AwsWafForm` solver, inject the resulting ``aws-waf-token`` cookie
472
516
  into the browser context, and reload the page.
473
517
 
518
+ :param waf_form: The solver to pass the challenge to.
474
519
  :param page: The Playwright ``Page`` on the ACIC challenge URL.
475
520
  :param context: The Playwright ``BrowserContext``.
476
521
  :param output_dir: Directory for debug snapshots, or ``None``.
477
522
  :return: ``True`` if a WAF token was obtained and injected, ``False`` otherwise.
478
- :raises AmazonAuthWafSolverError: If the WAF solver fails.
523
+ :raises AmazonAuthChallengeUnsolvedError: if the solver fails, or can't solve it and another solver is
524
+ registered after it.
479
525
  """
480
526
  try:
481
527
  from playwright.sync_api import TimeoutError as PlaywrightTimeoutError # type: ignore[import-not-found]
@@ -507,16 +553,12 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
507
553
  if not self.amazon_session:
508
554
  return False # pragma: no cover
509
555
 
510
- waf_form = self._find_waf_solver()
511
- if not waf_form:
512
- logger.debug("No AwsWafForm configured, skipping WAF challenge.")
513
- return False
514
-
515
556
  try:
516
557
  token = waf_form.solve_token(page.url, goku, challenge_script)
517
558
  except AmazonAuthWafSolverError:
518
559
  raise
519
- except Exception:
560
+ except Exception as e:
561
+ self._unsolved_if_fallback_remains(e)
520
562
  logger.info("WAF solver failed to solve embedded WAF challenge.", exc_info=True)
521
563
  return False
522
564
 
@@ -535,18 +577,24 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
535
577
  self._save_debug_snapshot(page, output_dir, "browser-waf-injected")
536
578
  return True
537
579
 
538
- def _try_solve_visual_captcha(self, page: Any, context: Any, output_dir: Optional[str]) -> bool:
580
+ def _try_solve_visual_captcha(self,
581
+ waf_form: "AwsWafForm",
582
+ page: Any,
583
+ context: Any,
584
+ output_dir: Optional[str]) -> bool:
539
585
  """
540
586
  If the ACIC challenge page contains a visual grid Puzzle rendered by
541
587
  ``CaptchaScript.renderCaptcha``, extract the challenge images and question,
542
- solve it via the configured :class:`~amazonauth.contrib.waf.base.AwsWafForm`,
588
+ pass it to the current :class:`~amazonauth.contrib.waf.base.AwsWafForm` solver,
543
589
  and submit the answer.
544
590
 
591
+ :param waf_form: The solver to pass the Puzzle to.
545
592
  :param page: The Playwright ``Page`` on the ACIC challenge URL.
546
593
  :param context: The Playwright ``BrowserContext``.
547
594
  :param output_dir: Directory for debug snapshots, or ``None``.
548
595
  :return: ``True`` if the Puzzle was solved and submitted, ``False`` otherwise.
549
- :raises AmazonAuthWafSolverError: If the WAF solver fails.
596
+ :raises AmazonAuthChallengeUnsolvedError: if the solver fails, or can't solve it and another solver is
597
+ registered after it.
550
598
  """
551
599
  try:
552
600
  from playwright.sync_api import TimeoutError as PlaywrightTimeoutError # type: ignore[import-not-found]
@@ -564,11 +612,6 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
564
612
  if not self.amazon_session:
565
613
  return False # pragma: no cover
566
614
 
567
- waf_form = self._find_waf_solver()
568
- if not waf_form:
569
- logger.debug("No AwsWafForm configured, skipping Puzzle.")
570
- return False
571
-
572
615
  question_selector = self.config.selectors.ACIC_VISUAL_CAPTCHA_QUESTION_SELECTOR
573
616
  try:
574
617
  canvas_locator = page.locator(canvas_selector).first
@@ -603,12 +646,15 @@ class PlaywrightAcicForm(PlaywrightAuthForm):
603
646
  answer = waf_form.solve_visual_captcha(page.url, challenge_images, question)
604
647
  except AmazonAuthWafSolverError:
605
648
  raise
606
- except Exception:
649
+ except Exception as e:
650
+ self._unsolved_if_fallback_remains(e)
607
651
  logger.info("WAF solver failed to solve Puzzle.", exc_info=True)
608
652
  return False
609
653
 
610
654
  if answer is None:
611
- logger.info(f"{waf_form.PROVIDER_NAME} does not support Puzzle solving.")
655
+ message = f"{waf_form.PROVIDER_NAME} does not support Puzzle solving."
656
+ self._unsolved_if_fallback_remains(AmazonAuthError(message))
657
+ logger.info(message)
612
658
  return False
613
659
 
614
660
  message = f"Info: Puzzle answered via {waf_form.PROVIDER_NAME}."
@@ -756,6 +802,16 @@ class PlaywrightManualWafForm(PlaywrightAuthForm):
756
802
  self.headless = False
757
803
  self.manual = True
758
804
 
805
+ def check_available(self) -> None:
806
+ """
807
+ Check that a browser window can be opened here, as solving a challenge with this form needs.
808
+
809
+ :raises AmazonAuthChallengeUnsolvedError: if this machine doesn't have a display.
810
+ """
811
+ if not has_display():
812
+ raise AmazonAuthChallengeUnsolvedError(f"{type(self).__name__} requires a display to open a browser "
813
+ f"window, and this machine doesn't have one.")
814
+
759
815
  def select_form(self,
760
816
  amazon_session: "AmazonSession",
761
817
  parsed: Tag) -> bool:
@@ -9,10 +9,9 @@ from amazonauth.exception import AmazonAuthError, AmazonAuthWafSolverError
9
9
 
10
10
  class AntiCaptchaWafForm(AwsWafForm):
11
11
  """
12
- Solves AWS WAF JavaScript challenges via `Anti-Captcha
13
- <https://anti-captcha.com>`_'s ``AmazonTaskProxyless`` task.
12
+ Passes AWS WAF JavaScript challenges to `Anti-Captcha <https://anti-captcha.com>`_.
14
13
 
15
- Reads the API key from the ``ANTICAPTCHA_API_KEY`` environment variable.
14
+ Its API key is ``ANTICAPTCHA_API_KEY`` (see :attr:`~amazonauth.contrib.waf.base.AwsWafForm.api_key`).
16
15
  Requires the ``anticaptchaofficial`` Python package:
17
16
  ``pip install amazon-auth[anticaptcha]``.
18
17
  """
@@ -25,8 +24,7 @@ class AntiCaptchaWafForm(AwsWafForm):
25
24
  goku: Dict[str, Any],
26
25
  challenge_script: str) -> str:
27
26
  """
28
- Solve the AWS WAF challenge via Anti-Captcha's ``AmazonTaskProxyless``
29
- task type and return the ``aws-waf-token`` cookie value.
27
+ Solve the AWS WAF challenge with Anti-Captcha and return the ``aws-waf-token`` cookie value.
30
28
 
31
29
  :param url: The URL of the WAF-challenged page.
32
30
  :param goku: The parsed ``window.gokuProps`` payload.
@@ -12,7 +12,7 @@ from bs4 import Tag
12
12
  from requests import Response
13
13
 
14
14
  from amazonauth.conf import AmazonAuthConfig
15
- from amazonauth.exception import AmazonAuthError
15
+ from amazonauth.exception import AmazonAuthChallengeUnsolvedError, AmazonAuthError
16
16
  from amazonauth.forms import AuthForm
17
17
  from amazonauth.util import AmazonSessionResponse
18
18
 
@@ -58,17 +58,23 @@ class AwsWafForm(AuthForm):
58
58
  :class:`~amazonauth.conf.AmazonAuthConfig`. It's only required to solve a challenge, so a solver configured
59
59
  without one doesn't keep a session from being created.
60
60
 
61
- :raises AmazonAuthError: if neither is set.
61
+ :raises AmazonAuthChallengeUnsolvedError: if neither is set.
62
62
  """
63
- if not self._api_key:
64
- config_key = self.API_KEY_ENV_VAR.lower()
65
- raise AmazonAuthError(
66
- f"{type(self).__name__} requires the {self.API_KEY_ENV_VAR} "
67
- f"environment variable, or the {config_key} config key, to be set."
68
- )
63
+ self.check_available()
69
64
 
70
65
  return self._api_key
71
66
 
67
+ def check_available(self) -> None:
68
+ """
69
+ Check that this solver can solve a challenge here, which needs its :attr:`api_key`.
70
+
71
+ :raises AmazonAuthChallengeUnsolvedError: if its API key isn't set.
72
+ """
73
+ if not self._api_key:
74
+ raise AmazonAuthChallengeUnsolvedError(f"{type(self).__name__} requires the {self.API_KEY_ENV_VAR} "
75
+ f"environment variable, or the {self.API_KEY_ENV_VAR.lower()} "
76
+ f"config key, to be set.")
77
+
72
78
  def select_form(self,
73
79
  amazon_session: "AmazonSession",
74
80
  parsed: Tag) -> bool:
@@ -117,12 +123,14 @@ class AwsWafForm(AuthForm):
117
123
  :return: The :class:`~amazonauth.util.AmazonSessionResponse` from
118
124
  re-fetching the URL after the cookie is set.
119
125
  :raises AmazonAuthError: if :func:`~amazonauth.forms.AuthForm.select_form` was not called first.
126
+ :raises AmazonAuthChallengeUnsolvedError: if its API key isn't set, or the solver fails.
120
127
  """
121
128
  if not self.amazon_session or self._goku is None or self._challenge_script is None:
122
129
  raise AmazonAuthError(
123
130
  "Call AwsWafForm.select_form() first."
124
131
  ) # pragma: no cover
125
132
 
133
+ self.check_available()
126
134
  token = self.solve_token(last_response.url, self._goku, self._challenge_script)
127
135
 
128
136
  # Always surface that a paid third-party service was used, regardless of debug mode.
@@ -147,8 +155,7 @@ class AwsWafForm(AuthForm):
147
155
  set on the session.
148
156
 
149
157
  :param url: The URL of the WAF-challenged page.
150
- :param goku: The parsed ``window.gokuProps`` payload (typically contains
151
- ``key``, ``iv``, and ``context``).
158
+ :param goku: The parsed ``window.gokuProps`` payload.
152
159
  :param challenge_script: The ``src`` of the AWS WAF ``challenge.js``
153
160
  script tag from the challenge page.
154
161
  :return: The ``aws-waf-token`` cookie value.
@@ -165,7 +172,7 @@ class AwsWafForm(AuthForm):
165
172
  and return the indices of the correct grid cells.
166
173
 
167
174
  :param url: The URL of the page containing the Puzzle.
168
- :param image_data: List of base64-encoded data URLs, one per grid tile.
175
+ :param image_data: The Puzzle's grid tiles, as base64-encoded images.
169
176
  :param question: The object to identify (e.g. ``"the buckets"``).
170
177
  :return: A list of zero-based grid cell indices to select, or ``None`` if
171
178
  this solver does not support Puzzle classification.
@@ -9,10 +9,9 @@ from amazonauth.exception import AmazonAuthError, AmazonAuthWafSolverError
9
9
 
10
10
  class CapSolverWafForm(AwsWafForm):
11
11
  """
12
- Solves AWS WAF JavaScript challenges via `CapSolver
13
- <https://capsolver.com>`_'s ``AntiAwsWafTaskProxyLess`` task.
12
+ Passes AWS WAF JavaScript challenges to `CapSolver <https://capsolver.com>`_.
14
13
 
15
- Reads the API key from the ``CAPSOLVER_API_KEY`` environment variable.
14
+ Its API key is ``CAPSOLVER_API_KEY`` (see :attr:`~amazonauth.contrib.waf.base.AwsWafForm.api_key`).
16
15
  Requires the ``capsolver`` Python package: ``pip install amazon-auth[capsolver]``.
17
16
  """
18
17
 
@@ -24,8 +23,7 @@ class CapSolverWafForm(AwsWafForm):
24
23
  goku: Dict[str, Any],
25
24
  challenge_script: str) -> str:
26
25
  """
27
- Solve the AWS WAF challenge via CapSolver's ``AntiAwsWafTaskProxyLess``
28
- task type and return the ``aws-waf-token`` cookie value.
26
+ Solve the AWS WAF challenge with CapSolver and return the ``aws-waf-token`` cookie value.
29
27
 
30
28
  :param url: The URL of the WAF-challenged page.
31
29
  :param goku: The parsed ``window.gokuProps`` payload.
@@ -73,11 +71,10 @@ class CapSolverWafForm(AwsWafForm):
73
71
  image_data: List[str],
74
72
  question: str) -> Optional[List[int]]:
75
73
  """
76
- Solve a visual grid Puzzle via CapSolver's ``AwsWafClassification`` task
77
- type and return the indices of the correct grid cells.
74
+ Solve a visual grid Puzzle with CapSolver and return the indices of the correct grid cells.
78
75
 
79
76
  :param url: The URL of the page containing the Puzzle.
80
- :param image_data: List of base64-encoded data URLs, one per grid tile.
77
+ :param image_data: The Puzzle's grid tiles, as base64-encoded images.
81
78
  :param question: The object to identify (e.g. ``"the buckets"``).
82
79
  :return: A list of zero-based grid cell indices to select.
83
80
  :raises AmazonAuthError: if the ``capsolver`` package is not installed.
@@ -10,10 +10,9 @@ from amazonauth.exception import AmazonAuthError, AmazonAuthWafSolverError
10
10
 
11
11
  class TwoCaptchaWafForm(AwsWafForm):
12
12
  """
13
- Solves AWS WAF JavaScript challenges via `2Captcha <https://2captcha.com>`_'s
14
- ``amazon_waf`` solver method.
13
+ Passes AWS WAF JavaScript challenges to `2Captcha <https://2captcha.com>`_.
15
14
 
16
- Reads the API key from the ``TWOCAPTCHA_API_KEY`` environment variable.
15
+ Its API key is ``TWOCAPTCHA_API_KEY`` (see :attr:`~amazonauth.contrib.waf.base.AwsWafForm.api_key`).
17
16
  Requires the ``2captcha-python`` Python package:
18
17
  ``pip install amazon-auth[2captcha]``.
19
18
  """
@@ -26,9 +25,7 @@ class TwoCaptchaWafForm(AwsWafForm):
26
25
  goku: Dict[str, Any],
27
26
  challenge_script: str) -> str:
28
27
  """
29
- Solve the AWS WAF challenge via 2Captcha's ``amazon_waf`` method and
30
- return the ``aws-waf-token`` cookie value (extracted from the
31
- ``existing_token`` field in 2Captcha's response).
28
+ Solve the AWS WAF challenge with 2Captcha and return the ``aws-waf-token`` cookie value.
32
29
 
33
30
  :param url: The URL of the WAF-challenged page.
34
31
  :param goku: The parsed ``window.gokuProps`` payload.
@@ -33,7 +33,16 @@ class AmazonAuthRedirectError(AmazonAuthSignInError):
33
33
  pass
34
34
 
35
35
 
36
- class AmazonAuthWafSolverError(AmazonAuthError):
36
+ class AmazonAuthChallengeUnsolvedError(AmazonAuthError):
37
+ """
38
+ Raised when a sign-in challenge form can't handle the challenge it was given (e.g. a solver without its API key,
39
+ or one that opens a browser window without a display), so the next form registered for the challenge is tried.
40
+ If none can, the error is raised.
41
+ """
42
+ pass
43
+
44
+
45
+ class AmazonAuthWafSolverError(AmazonAuthChallengeUnsolvedError):
37
46
  """
38
47
  Raised when a third-party WAF solver fails (e.g. its balance ran out, its API key was rejected, or the service
39
48
  is down), rather than Amazon rejecting a solved challenge. ``meta["provider"]`` is the solver's name, and
@@ -14,7 +14,8 @@ from requests import Response, Session
14
14
  from requests.utils import dict_from_cookiejar
15
15
 
16
16
  from amazonauth.conf import AmazonAuthConfig, cookies_file_lock, debug_output_file_lock
17
- from amazonauth.exception import AmazonAuthSignInError, AmazonAuthError, AmazonAuthRedirectError
17
+ from amazonauth.exception import (AmazonAuthSignInError, AmazonAuthError, AmazonAuthRedirectError,
18
+ AmazonAuthChallengeUnsolvedError)
18
19
  from amazonauth.forms import (AuthForm, AcicAuthBlocker, CaptchaForm, JSAuthBlocker, MfaDeviceSelectForm, MfaForm,
19
20
  SignInForm, ClaimForm, IntentForm, PasskeyForm)
20
21
  from amazonauth.util import AmazonSessionResponse, load_class, make_private_dirs, select_one, write_private_file
@@ -567,10 +568,21 @@ class AmazonSession:
567
568
 
568
569
  def _process_forms(self,
569
570
  last_response: AmazonSessionResponse) -> Optional[AmazonSessionResponse]:
571
+ unsolved: Optional[AmazonAuthChallengeUnsolvedError] = None
570
572
  for form in self.auth_forms:
573
+ # Once a form couldn't solve the challenge, its error is the one to raise, not a blocker's generic one
574
+ if unsolved and isinstance(form, (AcicAuthBlocker, JSAuthBlocker)):
575
+ continue
571
576
  if form.select_form(self, last_response.parsed):
572
- form.fill_form()
573
- return form.submit(last_response.response)
577
+ try:
578
+ form.fill_form()
579
+ return form.submit(last_response.response)
580
+ except AmazonAuthChallengeUnsolvedError as e:
581
+ logger.debug(f"{type(form).__name__} couldn't solve the challenge, trying the next form: {e}")
582
+ unsolved = e
583
+
584
+ if unsolved:
585
+ raise unsolved
574
586
 
575
587
  return None
576
588
 
@@ -389,3 +389,28 @@ some_custom_config: {custom_config}
389
389
 
390
390
  # THEN
391
391
  self.assertEqual("/some/cookies.json", config.cookie_jar_path)
392
+
393
+ def test_downstream_config_adds_its_own_defaults(self):
394
+ # WHEN
395
+ config = DownstreamConfig(data={})
396
+
397
+ # THEN
398
+ self.assertEqual(20, config.page_size)
399
+ self.assertEqual(AmazonAuthConfig.default_data()["max_auth_attempts"], config.max_auth_attempts)
400
+
401
+ def test_downstream_config_reads_its_own_default_key_from_the_environment_as_yaml(self):
402
+ # WHEN
403
+ with patch.dict(os.environ, {"AMAZON_PAGE_SIZE": "30"}):
404
+ config = DownstreamConfig(data={})
405
+
406
+ # THEN
407
+ self.assertEqual(30, config.page_size)
408
+
409
+
410
+ class DownstreamConfig(AmazonAuthConfig):
411
+ @staticmethod
412
+ def default_data():
413
+ return {
414
+ **AmazonAuthConfig.default_data(),
415
+ "page_size": 20,
416
+ }
@@ -181,7 +181,7 @@ class TestConstants(UnitTestCase):
181
181
 
182
182
  # THEN
183
183
  self.assertIn(f"The domain \"{domain}\" isn't an Amazon site.", str(cm.exception))
184
- self.assertIn("amazon.co.uk", str(cm.exception))
184
+ self.assertIn(f"{AmazonAuthConfig.DOCS_URL}/#sites", str(cm.exception))
185
185
 
186
186
  def test_domain_forms_of_an_amazon_site_are_accepted(self):
187
187
  for domain, base_url in [("amazon.de", "https://www.amazon.de"), ("www.amazon.de", "https://www.amazon.de"),
@@ -266,6 +266,17 @@ class TestConstants(UnitTestCase):
266
266
  self.assertEqual("https://www.amazon.co.uk/?ref_=nav_custrec_signin",
267
267
  config.constants.SIGN_IN_QUERY_PARAMS["openid.return_to"])
268
268
 
269
+ def test_domain_applied_by_downstream_constants(self):
270
+ # WHEN
271
+ config = AmazonAuthConfig(data={
272
+ "constants_class": "tests.test_constants.DownstreamConstants",
273
+ "domain": "amazon.co.uk",
274
+ })
275
+
276
+ # THEN
277
+ self.assertEqual("https://www.amazon.co.uk/subscriptions", config.constants.SUBSCRIPTIONS_URL)
278
+ self.assertEqual("https://www.amazon.co.uk", config.constants.BASE_URL)
279
+
269
280
 
270
281
  class RegionOverrideConstants(AuthConstants):
271
282
  SIGN_IN_QUERY_PARAMS = dict(AuthConstants.SIGN_IN_QUERY_PARAMS, **{"openid.assoc_handle": "customflex"})
@@ -274,3 +285,11 @@ class RegionOverrideConstants(AuthConstants):
274
285
 
275
286
  class RequestCookiesOverrideConstants(AuthConstants):
276
287
  REQUEST_COOKIES = {"lc-acbfr": "fr_FR"}
288
+
289
+
290
+ class DownstreamConstants(AuthConstants):
291
+ SUBSCRIPTIONS_URL = f"{AuthConstants.BASE_URL}/subscriptions"
292
+
293
+ def apply_domain(self, domain):
294
+ super().apply_domain(domain)
295
+ self.SUBSCRIPTIONS_URL = f"{self.BASE_URL}/subscriptions"
@@ -14,9 +14,11 @@ from responses.matchers import query_string_matcher, urlencoded_params_matcher
14
14
 
15
15
  from amazonauth.conf import AmazonAuthConfig
16
16
  from amazonauth.constants import AuthConstants
17
- from amazonauth.exception import AmazonAuthSignInError, AmazonAuthRedirectError, AmazonAuthError
18
- from amazonauth.forms import JSAuthBlocker, MfaDeviceSelectForm
17
+ from amazonauth.exception import (AmazonAuthSignInError, AmazonAuthRedirectError, AmazonAuthError,
18
+ AmazonAuthWafSolverError)
19
+ from amazonauth.forms import AcicAuthBlocker, AuthForm, JSAuthBlocker, MfaDeviceSelectForm
19
20
  from amazonauth.session import AmazonSession, IODefault
21
+ from amazonauth.util import AmazonSessionResponse
20
22
  from tests._auth_form_stubs import OtherStubAuthForm, StubAuthForm
21
23
  from tests.unittestcase import UnitTestCase
22
24
 
@@ -1596,6 +1598,66 @@ class TestSession(UnitTestCase):
1596
1598
  self.assertEqual(1, history_response.call_count)
1597
1599
 
1598
1600
 
1601
+ class TestChallengeFormOrder(UnitTestCase):
1602
+ def setUp(self):
1603
+ super().setUp()
1604
+
1605
+ with open(os.path.join(self.RESOURCES_DIR, "auth", "waf-challenge.html"), "r", encoding="utf-8") as f:
1606
+ response = MagicMock()
1607
+ response.text = f.read()
1608
+ self.challenge_page = AmazonSessionResponse(response, self.test_config.bs4_parser)
1609
+
1610
+ def given_challenge_form(self, submit_result=None, error=None):
1611
+ form = MagicMock(spec=AuthForm)
1612
+ form.select_form.return_value = True
1613
+ form.submit.return_value = submit_result
1614
+ form.submit.side_effect = error
1615
+ return form
1616
+
1617
+ def given_session(self, *forms):
1618
+ blockers = [AcicAuthBlocker(self.test_config),
1619
+ JSAuthBlocker(self.test_config, self.test_config.constants.JS_ROBOT_TEXT_REGEX)]
1620
+ return AmazonSession(config=self.test_config, auth_forms=[*forms, *blockers])
1621
+
1622
+ def test_first_form_that_handles_a_challenge_is_used(self):
1623
+ # GIVEN
1624
+ first = self.given_challenge_form(submit_result="first")
1625
+ second = self.given_challenge_form(submit_result="second")
1626
+ amazon_session = self.given_session(first, second)
1627
+
1628
+ # WHEN
1629
+ result = amazon_session._process_forms(self.challenge_page)
1630
+
1631
+ # THEN
1632
+ self.assertEqual("first", result)
1633
+ second.submit.assert_not_called()
1634
+
1635
+ def test_unsolved_challenge_falls_back_to_the_next_form(self):
1636
+ # GIVEN
1637
+ unsolved = self.given_challenge_form(error=AmazonAuthWafSolverError("TestSolver is out of credit"))
1638
+ fallback = self.given_challenge_form(submit_result="fallback")
1639
+ amazon_session = self.given_session(unsolved, fallback)
1640
+
1641
+ # WHEN
1642
+ result = amazon_session._process_forms(self.challenge_page)
1643
+
1644
+ # THEN
1645
+ self.assertEqual("fallback", result)
1646
+ unsolved.submit.assert_called_once()
1647
+
1648
+ def test_unsolved_challenge_raises_its_own_error_when_no_form_solves_it(self):
1649
+ # GIVEN
1650
+ error = AmazonAuthWafSolverError("TestSolver is out of credit", meta={"provider": "TestSolver"})
1651
+ amazon_session = self.given_session(self.given_challenge_form(error=error))
1652
+
1653
+ # WHEN
1654
+ with self.assertRaises(AmazonAuthWafSolverError) as cm:
1655
+ amazon_session._process_forms(self.challenge_page)
1656
+
1657
+ # THEN
1658
+ self.assertIs(error, cm.exception)
1659
+
1660
+
1599
1661
  class RecordingIO(IODefault):
1600
1662
  def __init__(self, prompt_response):
1601
1663
  self.prompt_response = prompt_response
File without changes
File without changes
File without changes