Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,33 @@ The package provides a synchronous client, `PriceCharting`, and an asynchronous
The client is under development: the clients can be created and used as context managers, but
their API methods are not implemented yet.

## Authentication

Set your token in the `PRICECHARTING_TOKEN` environment variable and create a client without
arguments:

```python
from pypricecharting import PriceCharting

with PriceCharting() as client:
...
```

You can also pass the token directly:

```python
with PriceCharting("your-40-character-token") as client:
...
```

The environment variable is recommended, because it keeps the token out of your code. Both
clients raise `ValueError` if no token is found or the token is not 40 characters.

## Security

The PriceCharting API requires the token in the query string of `GET` requests, so it is part of
the request URL. The clients redact it from the `httpx2` request log, which shows `t=REDACTED`
instead. Anything outside this library that records URLs can still see the token, such as
proxies or your own logging of requests.

See the [API Reference](api/clients.md) for the classes and types in the package.
57 changes: 57 additions & 0 deletions src/pypricecharting/_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import logging
import re
from collections.abc import Generator
from urllib.parse import urlencode

from httpx2 import Auth, Request, Response
from pydantic import SecretStr

_TOKEN_PARAM = re.compile(r"([?&]t=)[^&\s\"']+")


class _TokenAuth(Auth):
"""Add the PriceCharting token as `t` in the query string (GET) or form body (POST)."""

requires_request_body = True

def __init__(self, token: SecretStr):
self._token = token

def auth_flow(self, request: Request) -> Generator[Request, Response]:
"""Attach the token to the outgoing request."""
token = self._token.get_secret_value()

if request.method == "GET":
request.url = request.url.copy_set_param("t", token)
yield request
return

param = urlencode({"t": token}).encode()
body = request.content + b"&" + param if request.content else param
headers = request.headers.copy()
headers.pop("Content-Length", None) # forces httpx2 to recalculate length
headers["Content-Type"] = "application/x-www-form-urlencoded"

yield Request(
request.method,
request.url,
headers=headers,
content=body,
extensions=request.extensions,
)


class _RedactTokenFilter(logging.Filter):
"""Replace the `t` query parameter in httpx2 log records with `REDACTED`."""

def filter(self, record: logging.LogRecord) -> bool:
"""Redact the token in place and always let the record through."""
message = record.getMessage()
redacted = _TOKEN_PARAM.sub(r"\1REDACTED", message)
if redacted != message:
record.msg = redacted
record.args = None
return True


_REDACT_FILTER = _RedactTokenFilter()
38 changes: 34 additions & 4 deletions src/pypricecharting/asyncpricecharting.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,46 @@
import logging
import os
from types import TracebackType
from typing import Self

from httpx2 import AsyncClient
from pydantic import SecretStr

from pypricecharting._auth import _REDACT_FILTER, _TokenAuth


class AsyncPriceCharting:
"""Asynchronous PriceCharting API client."""

def __init__(self, credential: str):
"""Create a client authenticated with a PriceCharting API token."""
self.credential = credential
self.client = AsyncClient()
TOKEN_KEY = "PRICECHARTING_TOKEN"

def __init__(self, token: str | None = None):
"""Create a client authenticated with a PriceCharting API token.

The client adds a logging filter to the `httpx2` logger that replaces the token in
request URLs with `REDACTED`.

Args:
token: The 40-character PriceCharting API token. If omitted, it is read from the
`PRICECHARTING_TOKEN` environment variable.

Raises:
ValueError: If no token is passed or set in the environment, or the token is not
40 characters.

"""
if token is not None and len(token) != 40:
raise ValueError("PriceCharting API token is not 40 characters")
token = token or os.environ.get(self.TOKEN_KEY)

if token is None:
raise ValueError("PriceCharting API token not found")
if len(token) != 40:
raise ValueError("PriceCharting API token is not 40 characters")

self._token = SecretStr(token)
self.client = AsyncClient(auth=_TokenAuth(self._token))
logging.getLogger("httpx2").addFilter(_REDACT_FILTER)

async def aclose(self):
"""Close the underlying HTTP client."""
Expand Down
39 changes: 35 additions & 4 deletions src/pypricecharting/pricecharting.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,47 @@
import logging
import os
from types import TracebackType
from typing import Self

from httpx2 import Client
from pydantic import SecretStr

from pypricecharting._auth import _REDACT_FILTER, _TokenAuth


class PriceCharting:
"""Synchronous PriceCharting API client."""

def __init__(self, credential: str):
"""Create a client authenticated with a PriceCharting API token."""
self.credential = credential
self.client = Client()
TOKEN_KEY = "PRICECHARTING_TOKEN"

def __init__(self, token: str | None = None):
"""Create a client authenticated with a PriceCharting API token.

The client adds a logging filter to the `httpx2` logger that replaces the token in
request URLs with `REDACTED`.

Args:
token: The 40-character PriceCharting API token. If omitted, it is read from the
`PRICECHARTING_TOKEN` environment variable.

Raises:
ValueError: If no token is passed or set in the environment, or the token is not
40 characters.

"""
if token is not None and len(token) != 40:
raise ValueError("PriceCharting API token is not 40 characters")

token = token or os.environ.get(self.TOKEN_KEY)

if token is None:
raise ValueError("PriceCharting API token not found")
elif len(token) != 40:
raise ValueError("PriceCharting API token is not 40 characters")

self._token = SecretStr(token)
self.client = Client(auth=_TokenAuth(self._token))
logging.getLogger("httpx2").addFilter(_REDACT_FILTER)

def close(self):
"""Close the underlying HTTP client."""
Expand Down
38 changes: 36 additions & 2 deletions tests/test_asyncpricecharting.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,49 @@
# Template tests: the API methods are placeholders, so these only check they can be called.
# Replace the `is None` assertions once each method is implemented.

TOKEN = "test-token"
TOKEN = "test-token-12345678901234567890123456789"


def test_token_constant():
assert AsyncPriceCharting.TOKEN_KEY == "PRICECHARTING_TOKEN"


async def test_init_stores_credential():
client = AsyncPriceCharting(TOKEN)
assert client.credential == TOKEN
assert client._token.get_secret_value() == TOKEN
await client.aclose()


async def test_init_raises_on_empty_token():
with pytest.raises(ValueError, match="PriceCharting API token is not 40 characters"):
AsyncPriceCharting("")


async def test_init_raises_on_incorrect_length_token():
with pytest.raises(ValueError, match="PriceCharting API token is not 40 characters"):
AsyncPriceCharting("a")


async def test_init_raises_on_missing_token():
with pytest.raises(ValueError, match="PriceCharting API token not found"):
AsyncPriceCharting()


async def test_init_reads_env_variable(monkeypatch):
monkeypatch.setenv(AsyncPriceCharting.TOKEN_KEY, TOKEN)

client = AsyncPriceCharting()
assert client._token.get_secret_value() == TOKEN
await client.aclose()


async def test_init_raises_on_incorrect_env_variable(monkeypatch):
monkeypatch.setenv(AsyncPriceCharting.TOKEN_KEY, "test")

with pytest.raises(ValueError, match="PriceCharting API token is not 40 characters"):
AsyncPriceCharting()


async def test_init_creates_http_client():
client = AsyncPriceCharting(TOKEN)
assert isinstance(client.client, AsyncClient)
Expand Down
Loading
Loading