Skip to content

Refactor OAuth2 settings and improve client validation - #157

Merged
sergioteula merged 1 commit into
masterfrom
claude/code-analysis-improvements-3uh3nc
Sep 4, 2026
Merged

Refactor OAuth2 settings and improve client validation#157
sergioteula merged 1 commit into
masterfrom
claude/code-analysis-improvements-3uh3nc

Conversation

@sergioteula

Copy link
Copy Markdown
Owner

Summary

This PR refactors OAuth2 configuration into a shared module, improves input validation for both sync and async clients, adds context manager support, and enhances error handling for edge cases.

Key Changes

OAuth2 Configuration Refactoring

  • Created new amazon_creatorsapi/core/oauth.py module to centralize OAuth2 constants and logic shared between sync and async clients
  • Moved VERSION_ENDPOINTS, COGNITO_SCOPE, LWA_SCOPE, GRANT_TYPE, TOKEN_EXPIRATION_BUFFER, and DEFAULT_EXPIRATION to the shared module
  • Extracted helper functions: is_lwa(), get_scope(), and get_auth_endpoint() to eliminate duplication
  • Both AmazonCreatorsApi and AsyncAmazonCreatorsApi now use get_auth_endpoint() for consistent version validation

Input Validation Improvements

  • Added validate_throttling() function to validate wait time between API calls (must be a number ≥ 0)
  • Enhanced validate_timeout() and validate_retries() to properly handle non-numeric inputs with clear error messages
  • Both sync and async clients now validate throttling at initialization time
  • Custom auth_endpoint parameter now makes any API version valid, allowing forward compatibility

Client Lifecycle Management

  • Added __enter__() and __exit__() methods to AmazonCreatorsApi for context manager support
  • Added close() method to release connection pools
  • Updated docstrings to document the context manager pattern and connection pool management

Token Manager Improvements

  • Added thread-safe token caching in TimeoutOAuth2TokenManager using a lock to prevent multiple threads from requesting tokens simultaneously
  • Enhanced async token manager to parse token responses with proper error handling for invalid JSON
  • Both managers now use constants from the shared OAuth2 module

Error Handling Enhancements

  • handle_api_error() now accepts and reports the reason field from API exceptions when response body is empty
  • Added get_seconds_until() function to parse HTTP date headers in Retry-After responses
  • Improved retry logic to handle both numeric and date-based retry delays

Test Coverage

  • Added comprehensive tests for OAuth2 helper functions
  • Added tests for custom endpoint validation and version support
  • Added tests for throttling and timeout validation with non-numeric inputs
  • Added tests for context manager and connection pool cleanup
  • Added tests for thread-safe token caching
  • Added tests for date-based retry headers and edge cases
  • Enhanced existing tests with proper ASIN values in mock responses

Documentation

  • Updated README with context manager usage example
  • Updated CHANGELOG with new features and improvements

https://claude.ai/code/session_01KN1v6C671EcHw5Vur9rC3y

Both clients drifted apart on the auth endpoint, the errors they raise and
the values they accept, so this brings them back together and covers the
cases that failed silently.

- The async client rejected a version out of its list even when a custom
  auth_endpoint was given, which is what that parameter is for. Both clients
  now resolve the endpoint with the same list, so a version only has to be
  added once and the SDK list is no longer a second source of truth.
- A token response that is not JSON escaped from the async client as the
  error of the JSON parser, while the sync one already reported it as an
  AuthenticationError.
- Errors reported by the transport, such as an invalid certificate, arrive
  without a body and were reported as "Request failed with status 0",
  dropping the only useful part of the failure.
- An ASIN was matched without a boundary, so a longer identifier in a URL
  was trimmed to ten characters and a different item was requested.
- get_items only checked the items returned by Amazon, not the ones that
  matched the request, so a response holding other items returned an empty
  list instead of raising.
- throttling was the only option without validation, accepting a negative
  value and failing with a TypeError for anything that is not a number.
- The token manager of the sync client had no lock, so every thread asked
  for its own token as soon as the cached one expired.
- Retry-After is also read when Amazon sends it as a date.
- AmazonCreatorsApi can be closed, releasing the pool of connections that
  it keeps open, which only the async client could do.
- mypy was configured for a version it no longer supports, so the whole
  check was running against its default instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KN1v6C671EcHw5Vur9rC3y
@sergioteula
sergioteula merged commit 9c1094d into master Sep 4, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants