diff --git a/plistsync/cli/config.py b/plistsync/cli/config.py index 2b861409..f1470ede 100644 --- a/plistsync/cli/config.py +++ b/plistsync/cli/config.py @@ -1,10 +1,4 @@ -"""YAML configuration management for the plistsync CLI. - -Uses the ``eyconf`` library to load and validate the configuration file. The -plain dataclasses live in :mod:`plistsync.core.config` and -:mod:`plistsync.logger`; this module owns everything that is specific to the -CLI: file locations and the disk-backed loading. -""" +"""CLI-side configuration: file locations, loading and token persistence.""" from __future__ import annotations @@ -12,13 +6,14 @@ from dataclasses import dataclass, field, make_dataclass from functools import cache from pathlib import Path -from typing import Annotated, TypeVar +from typing import Annotated, Any, TypeVar, get_args, get_origin, get_type_hints from eyconf import EYConf from eyconf.decorators import allow_additional from platformdirs import user_config_dir -from plistsync.core.config import ServiceConfig +from plistsync.core import Token +from plistsync.core.config import ConfigIO, DataIO, JsonFileIO, ServiceConfig from plistsync.logger import LoggingConfig, log from plistsync.services import ServiceLoader @@ -175,8 +170,19 @@ def get_config_for(self, config_cls: type[C]) -> C: If the config class is not registered. """ for service_name, config_classes in ServiceConfig.registry().items(): - if config_cls in config_classes: - return self.get_service_config(service_name) # type: ignore[return-value] + if config_cls not in config_classes: + continue + + service_config = self.get_service_config(service_name) + if isinstance(service_config, config_cls): + return service_config + + # The service was registered only after this instance built its + # schema, so its config section is still raw "extra data". Rebuild + # the schema (now including the service) and reload. + self._schema = self._build_schema() + self.reload() + return self.get_service_config(service_name) # type: ignore[return-value] raise ValueError(f"Service config {config_cls.__name__} is not registered.") @@ -201,9 +207,8 @@ def get_service_config(self, service_name: str) -> ServiceConfig: Raises ------ ValueError - If the service is not registered or has no config schema. - ConfigurationError - If the service is not enabled in the configuration. + If the service is not registered, has no config schema, or the + config instance cannot be resolved. """ # Already in the schema: fast return if service_config := self.data.services.get(service_name): @@ -243,7 +248,49 @@ def default_yaml(self): return super().default_yaml() +def _dataio_token_type(annotation: Any) -> type[Token] | None: + """Return ``D`` if ``annotation`` contains a ``DataIO[D]``, else ``None``.""" + for candidate in (annotation, *get_args(annotation)): + if get_origin(candidate) is DataIO: + args = get_args(candidate) + if args and isinstance(args[0], type) and issubclass(args[0], Token): + return args[0] + return None + + +@dataclass +class UserDirConfigIO(ConfigIO): + """Wrapper around EYCONF.""" + + config: Config = field(default_factory=Config) + directory: Path = field(default_factory=Config.get_dir) + + def load(self, service_config_cls: type[C]) -> C: + # TODO: Re-evaluate. For now we only allow the special-case DataIO[Token] + # We should move the DataIO serialization logic into eyconf at some point + service_config = self.config.get_config_for(service_config_cls) + service_name = service_config_cls.service() + + hints = get_type_hints( + service_config_cls, include_extras=True, localns={"DataIO": DataIO} + ) + for name, annotation in hints.items(): + token_type = _dataio_token_type(annotation) + if token_type is None: + continue + path = self.directory / f"{service_name}_{name}.json" + setattr(service_config, name, JsonFileIO[token_type](path)) # type: ignore[valid-type] + + return service_config + + def save(self, service_config: ServiceConfig) -> None: + # Currently only saves tokens via dataio + # See eyconf issue: #31 + pass + + __all__ = [ "BaseConfigSchema", "Config", + "UserDirConfigIO", ] diff --git a/plistsync/cli/context.py b/plistsync/cli/context.py index b653a099..834d93ee 100644 --- a/plistsync/cli/context.py +++ b/plistsync/cli/context.py @@ -23,8 +23,6 @@ class ServiceContext: @cached_property def library(self) -> Library | None: """Instantiate the service's library, if it supports one.""" - from plistsync.cli.config import Config - library_cls = self.service.library() if library_cls is None: return None @@ -36,10 +34,12 @@ def library(self) -> Library | None: @cached_property def config(self) -> ServiceConfig | None: """Resolve the service's config, if it supports one.""" - from plistsync.cli.config import Config + from plistsync.cli.config import UserDirConfigIO config_cls = self.service.config() - return Config().get_config_for(config_cls) if config_cls is not None else None + if config_cls is None: + return None + return UserDirConfigIO().load(config_cls) @property def name(self) -> str: diff --git a/plistsync/cli/service_commands/auth.py b/plistsync/cli/service_commands/auth.py index eb4616a9..13304c57 100644 --- a/plistsync/cli/service_commands/auth.py +++ b/plistsync/cli/service_commands/auth.py @@ -13,6 +13,7 @@ from plistsync.cli.context import ( ServiceCommandContext, # noqa: TC001 (typer resolves it at runtime) ) +from plistsync.core.config import DataIO from plistsync.errors import AuthenticationError, HowTheForkDidYouEndUpHereError from plistsync.logger import log from plistsync.utils.auth import safe_webbrowser_open @@ -133,11 +134,15 @@ def auth( return token: Token = auth_provider(config).authenticate(CLIInteraction(mode=mode)) - token.file_path = config.token_path - token.save() - typer.echo( - f"Authentication successful! Token saved to {str(token.file_path)!r}." - ) + + # The token field must be a DataIO so that the assignment below persists + # it (ServiceConfig.__setattr__ routes DataIO fields through __set__). + if not isinstance(vars(config).get("token"), DataIO): + raise HowTheForkDidYouEndUpHereError( + f"{type(config).__name__} has no DataIO for 'token'. Cannot persist it!" + ) + setattr(config, "token", token) + typer.echo("Authentication successful! Token saved.") auth.__doc__ = ( f"Authenticate with {auth_provider.service()} or check the" diff --git a/plistsync/core/__init__.py b/plistsync/core/__init__.py index 4453e97a..c19d49f6 100644 --- a/plistsync/core/__init__.py +++ b/plistsync/core/__init__.py @@ -6,9 +6,9 @@ and path rewriting. """ -from .auth import AuthProvider, Interaction +from .auth import AuthProvider, Interaction, Token from .collection import Collection, Library -from .config import ServiceConfig +from .config import ConfigIO, ServiceConfig from .ids import PlaylistID, TrackID from .matching import Matches from .playlist import Playlist, ServicePlaylist @@ -18,6 +18,7 @@ __all__ = [ "AuthProvider", "Collection", + "ConfigIO", "Interaction", "Library", "Matches", @@ -26,6 +27,7 @@ "PlaylistID", "ServiceConfig", "ServicePlaylist", + "Token", "Track", "TrackID", "TrackInfo", diff --git a/plistsync/core/auth.py b/plistsync/core/auth.py index 70610a5a..2d96c53f 100644 --- a/plistsync/core/auth.py +++ b/plistsync/core/auth.py @@ -2,26 +2,14 @@ from __future__ import annotations -import base64 -import hashlib import inspect -import secrets from abc import ABC, abstractmethod -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, ClassVar, Generic, Protocol, TypeVar -from urllib.parse import parse_qs, urlencode, urlparse +from typing import TYPE_CHECKING, Generic, Protocol, TypeVar -import requests -from requests_oauth2client import OAuth2Client - -from plistsync.errors import AuthenticationError -from plistsync.logger import log from plistsync.services.registry import Registry -from plistsync.utils.auth.bearer_token import InvalidTokenError, Oauth2Token -from plistsync.utils.session import PlistsyncSession if TYPE_CHECKING: - from pathlib import Path + import requests from plistsync.core.config import ServiceConfig @@ -50,19 +38,23 @@ def capture_redirect(self, redirect_uri: str) -> str | None: ... -class Token(Protocol): - file_path: Path | None +class Token(ABC): + """Abstract base for a service token that can authenticate requests.""" - def save(self) -> None: - """Persist the token to disk. + @property + def is_expired(self) -> bool: + """Whether the token should be refreshed before use.""" + return False - Path is configured using the config when a token is created. - """ + @abstractmethod + def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest: + """Prepare the request to use the authentication.""" + ... +T = TypeVar("T", bound=Token) Req = TypeVar("Req") Res = TypeVar("Res") -T = TypeVar("T", bound=Token) class AuthProvider(ABC, Registry, Generic[Req, Res, T]): @@ -109,159 +101,3 @@ def obtain_token(self, request: Req, response: Res) -> T: @abstractmethod def check_auth(self) -> bool: """Check the current authentication status without user interaction.""" - - -# ---------------------------------- OAuth2 ---------------------------------- # -# TODO: We should move this into its own lazily loaded file, since it imports some deps -# that are not needed for most providers. - - -@dataclass(kw_only=True, frozen=True) -class OAuth2Request: - """Flow state for an OAuth2 authorization-code exchange.""" - - url: str - """Authorization URL to open in the browser by the user.""" - - redirect_uri: str - """Redirect URI to capture the callback on.""" - - state: str - """Random string to prevent CSRF attacks.""" - - code_verifier: str - """PKCE (S256) verifier for the token exchange.""" - - -class OAuth2Provider(AuthProvider[OAuth2Request, str | None, Oauth2Token], ABC): - """Authenticate via OAuth2 authorization code flow with PKCE. - - To use this provider, implement the abstract methods and classvars. - """ - - authorize_endpoint: ClassVar[str] - """OAuth2 authorization endpoint, e.g. ``https://accounts.spotify.com/authorize``.""" - - token_endpoint: ClassVar[str] - """OAuth2 token endpoint used to exchange the callback code for a token.""" - - scopes: ClassVar[str] - """Scopes to request for the service.""" - - @abstractmethod - def client_id(self) -> str: - """Client ID for the service.""" - - @abstractmethod - def redirect_uri(self) -> str: - """Redirect URI to capture the callback on.""" - - @property - def extra_authorize_params(self) -> dict[str, str]: - """Additional query parameters for the authorization URL.""" - return {} - - def build_request(self) -> OAuth2Request: - """Build the authorization URL with a fresh PKCE verifier.""" - code_verifier, code_challenge = self._generate_pkce() - state = secrets.token_urlsafe(32) - redirect_uri = self.redirect_uri() - params = { - "response_type": "code", - "client_id": self.client_id(), - "redirect_uri": redirect_uri, - "scope": self.scopes, - "state": state, - "code_challenge": code_challenge, - "code_challenge_method": "S256", - **self.extra_authorize_params, - } - return OAuth2Request( - url=f"{self.authorize_endpoint}?{urlencode(params)}", - redirect_uri=redirect_uri, - state=state, - code_verifier=code_verifier, - ) - - def collect_response( - self, interaction: Interaction, request: OAuth2Request - ) -> str | None: - """Open the URL and serve the redirect.""" - interaction.open_url(request.url) - return interaction.capture_redirect(request.redirect_uri) - - def obtain_token(self, request: OAuth2Request, response: str | None) -> Oauth2Token: - """Exchange the callback code for a token.""" - if not response: - raise AuthenticationError("No callback received.") - - query = parse_qs(urlparse(response).query) - - error = query.get("error", [None])[0] - if error: - description = query.get("error_description", [error])[0] or error - raise AuthenticationError(description) - - code = query.get("code", [None])[0] - state = query.get("state", [None])[0] - if not code or not state: - raise AuthenticationError("Missing 'code' or 'state' in callback URL.") - if state != request.state: - raise AuthenticationError("OAuth state mismatch; aborting authentication.") - - token_data = self._exchange_code( - code, request.redirect_uri, request.code_verifier - ) - return Oauth2Token.from_dict(token_data) - - def check_auth(self) -> bool: - """Non-interactively check the current authentication status. - - Loads the persisted token and refreshes it if it has expired. A token - that cannot be loaded or refreshed is considered not authenticated. - """ - try: - token = Oauth2Token.from_file(self.config.token_path) - if token.is_expired: - token.refresh( - OAuth2Client( - token_endpoint=self.token_endpoint, - client_id=self.client_id(), - ) - ) - except InvalidTokenError as e: - log.debug("Authentication check failed for %s: %s", type(self).__name__, e) - return False - - return True - - def _exchange_code( - self, code: str, redirect_uri: str, code_verifier: str - ) -> dict[str, Any]: - """Exchange an authorization code for a token payload.""" - try: - response = PlistsyncSession().post( - self.token_endpoint, - data={ - "grant_type": "authorization_code", - "client_id": self.client_id(), - "code": code, - "redirect_uri": redirect_uri, - "code_verifier": code_verifier, - }, - timeout=30, - ) - except requests.RequestException as e: - raise AuthenticationError(f"Failed to obtain token: {e}") from e - return response.json() - - @staticmethod - def _generate_pkce() -> tuple[str, str]: - """Generate a PKCE code verifier and its S256 challenge.""" - verifier = secrets.token_urlsafe(32) - challenge = ( - base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) - .rstrip(b"=") - .decode() - ) - return verifier, challenge diff --git a/plistsync/core/config.py b/plistsync/core/config.py index 31aba10a..2bf72d89 100644 --- a/plistsync/core/config.py +++ b/plistsync/core/config.py @@ -1,38 +1,150 @@ """Service configuration base classes. -Defines :class:`ServiceConfig`, the dataclass base that services subclass to -declare their settings. Library consumers construct these in code; the CLI -loads them from the YAML configuration file (see :mod:`plistsync.cli.config`). +Defines :class:`ServiceConfig`, the dataclass base services subclass to declare +their settings, and :class:`ConfigLoader`, which loads those settings and +persists their authentication tokens. """ from __future__ import annotations -from abc import ABC +import json +from abc import ABC, abstractmethod from dataclasses import dataclass -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar +from pydantic import BaseModel + +from plistsync.logger import log from plistsync.services.registry import Registry if TYPE_CHECKING: from pathlib import Path +T = TypeVar("T", bound="ServiceConfig") +D = TypeVar("D") +M = TypeVar("M", bound=BaseModel) + + +class DataIO(ABC, Generic[D]): + """Abstract base class for data input/output operations. + + Used for generalized loading and saving of data, such as authentication tokens or + potential other lazy loaded configurations fields. + """ + + # Think wrapper around data + _data: D | None = None + + @abstractmethod + def load(self) -> D: + """Load the data from the source.""" + + @abstractmethod + def save(self) -> None: + """Save the data to the source.""" + + def __set__(self, obj: object, value: D) -> None: + """Set the data and save it to the source.""" + self._data = value + self.save() + + def __get__(self, obj: object | None, objtype: type | None = None) -> D: + """Get the cached data, if any or loaded.""" + if self._data is not None: + return self._data + self._data = self.load() + return self._data + + @classmethod + def __get_pydantic_core_schema__(cls, source_type: Any, handler: Any) -> Any: + """Treat :class:`DataIO` fields as opaque for pydantic validation.""" + from pydantic_core import core_schema + + return core_schema.any_schema() + + +@dataclass +class JsonFileIO(DataIO[M | None], Generic[M]): + """JSON-file backed :class:`DataIO` for pydantic-style models. + + The model class is taken from the generic subscription, so construct it as + ``JsonFileIO[SomeModel](path)``. + """ + + path: Path + + if TYPE_CHECKING: + # Set by the typing machinery when instantiated via ``FileIO[X](...)``. + __orig_class__: ClassVar[Any] + + def _model_type(self) -> type[M]: + """Model class carried by the generic subscription.""" + try: + return self.__orig_class__.__args__[0] + except AttributeError: + raise TypeError( + f"{type(self).__name__} must be parameterized with a model class, " + "e.g. JsonFileIO[SomeModel](path)." + ) from None + + def load(self) -> M | None: + """Load the model from the JSON file, or ``None`` if it is unusable.""" + if not self.path.exists(): + log.debug("File %s does not exist; returning None.", self.path) + return None + + try: + with self.path.open("r", encoding="utf-8") as f: + data = json.load(f) + log.debug("Loaded from %s", self.path) + return self._model_type().model_validate(data) + except (OSError, ValueError) as e: + log.warning("Could not read %s: %s", self.path, e) + return None + + def save(self) -> None: + """Write the cached model to the JSON file.""" + if self._data is None: + raise ValueError("No data to save.") + payload = self._data.model_dump(mode="json") + with self.path.open("w", encoding="utf-8") as f: + json.dump(payload, f, indent=4) + log.debug("Saved to %s", self.path) + + +class ConfigIO(ABC): + """Loads service configs. + + Used for generalized loading and saving of service configurations. + """ + + @abstractmethod + def load(self, service_config_cls: type[T]) -> T: + """Load ``service_config_cls`` and attach this loader to it.""" + + @abstractmethod + def save(self, service_config: ServiceConfig) -> None: + """Save the authentication token of ``service_config``.""" + @dataclass class ServiceConfig(ABC, Registry): """Base class for service configurations. - Classes that inherit from this class will automatically be included in the - CLI config schema and can be validated/used. - """ + Subclasses declare their settings as dataclass fields and are automatically + registered for inclusion in the configuration schema. - @property - def token_path(self) -> Path: - """Path to the stored authentication token for this service. + Fields holding a :class:`DataIO` (e.g. a token) are transparent: reading the + attribute returns the loaded data, assigning to it stores and persists it. + """ - Token storage is a plistsync-wide convention, but the config directory - itself is resolved by the CLI, which is why the import is lazy. A bit - inconsistent but the best I could come up with right now! - """ - from plistsync.cli.config import Config + def __getattribute__(self, name: str) -> Any: + value = object.__getattribute__(self, name) + return value.__get__(self) if isinstance(value, DataIO) else value - return Config.get_dir() / f"{self.service().lower()}_token.json" + def __setattr__(self, name: str, value: Any) -> None: + current = self.__dict__.get(name) + if isinstance(current, DataIO) and not isinstance(value, DataIO): + current.__set__(self, value) + else: + object.__setattr__(self, name, value) diff --git a/plistsync/errors.py b/plistsync/errors.py index 46dfbe15..b49f4984 100644 --- a/plistsync/errors.py +++ b/plistsync/errors.py @@ -4,6 +4,7 @@ "AuthenticationError", "DependencyError", "HowTheForkDidYouEndUpHereError", + "InvalidTokenError", ] @@ -36,6 +37,17 @@ class AuthenticationError(Exception): pass +class InvalidTokenError(Exception): + """Raised when a token is missing, expired, or rejected.""" + + def __init__(self, token: object | None = None): + if token is not None: + self.message = f"Invalid token: {token}" + else: + self.message = "Token not found. Have you created a token?" + super().__init__(self.message) + + class HowTheForkDidYouEndUpHereError(Exception): """Raised when something unexpected happens. diff --git a/plistsync/services/plex/api.py b/plistsync/services/plex/api.py index cdc5c670..10cd6254 100644 --- a/plistsync/services/plex/api.py +++ b/plistsync/services/plex/api.py @@ -14,10 +14,12 @@ from urllib.parse import quote import requests +from pydantic import BaseModel, ConfigDict, Field, SecretStr, field_serializer +from plistsync.core.auth import Token +from plistsync.errors import InvalidTokenError from plistsync.logger import log -from plistsync.utils.auth.bearer_token import InvalidTokenError, Token, TokenSession -from plistsync.utils.session import PlistsyncSession +from plistsync.utils.session import PlistsyncSession, TokenSession from .api_types import ( PlexMediaTypes, @@ -37,31 +39,34 @@ from .config import PlexConfig -class PlexToken(Token): - x_plex_token: str - validated: bool +class PlexToken(BaseModel, Token): + """A Plex auth token, usable as a ``requests`` auth object.""" + + model_config = ConfigDict(hide_input_in_errors=True) + + x_plex_token: SecretStr + validated: bool = Field(default=False, exclude=True) + """Whether the token was validated against plex.tv (transient, not persisted).""" validation_endpoint: ClassVar[str] = "https://plex.tv/api/v2/user" """Endpoint used to validate the token.""" - def __init__(self, x_plex_token: str, file_path: Path | None): - super().__init__(file_path) - self.x_plex_token = x_plex_token - self.validated = False - - def as_dict(self) -> dict[str, Any]: - return {"X-Plex-Token": self.x_plex_token} + @field_serializer("x_plex_token", when_used="always") + def _reveal_token(self, value: SecretStr) -> str: + """Expose the plaintext on serialization so the token can be persisted.""" + return value.get_secret_value() - @classmethod - def from_dict(cls, token_dict): - return cls(token_dict["X-Plex-Token"], None) + @property + def is_expired(self) -> bool: + """Plex tokens cannot be refreshed, so they never expire locally.""" + return False def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest: """Prepare the request to use the authentication.""" - request.headers["X-Plex-Token"] = self.x_plex_token + request.headers["X-Plex-Token"] = self.x_plex_token.get_secret_value() return request - def validate(self, headers: Mapping[str, str | bytes] | None = None) -> None: + def validate_remote(self, headers: Mapping[str, str | bytes] | None = None) -> None: """Check the token against plex.tv. Plex tokens cannot be refreshed, so this only verifies that plex.tv @@ -116,6 +121,9 @@ def from_config(cls, config: PlexConfig) -> Self: Loads the stored token unless one is passed in, and resolves the server URL from `server_url` or by looking up `server_name`. """ + token = config.token + if not isinstance(token, PlexToken): + raise InvalidTokenError(None) def _resolve_server_name(server_name: str): # we need a temporary session for plex.tv, but later want one that uses the @@ -128,7 +136,7 @@ def _resolve_server_name(server_name: str): config.app_name, config.client_identifier, "https://plex.tv", - PlexToken.from_file(config.token_path), + token, ) conns = PlexApi.get_server_connections_for_name(temp_session, server_name) @@ -145,7 +153,7 @@ def _resolve_server_name(server_name: str): config.app_name, config.client_identifier, server_url, - PlexToken.from_file(config.token_path), + token, ) def _validate_token(self) -> None: @@ -155,7 +163,7 @@ def _validate_token(self) -> None: to refresh with the current flow. """ try: - self.token.validate(headers=self.headers) + self.token.validate_remote(headers=self.headers) except requests.exceptions.RequestException as e: raise ValueError( f"Plex token validation failed due to network error: {e!s}" diff --git a/plistsync/services/plex/auth.py b/plistsync/services/plex/auth.py index 06971333..66135378 100644 --- a/plistsync/services/plex/auth.py +++ b/plistsync/services/plex/auth.py @@ -8,9 +8,8 @@ import requests from plistsync.core.auth import AuthProvider -from plistsync.errors import AuthenticationError +from plistsync.errors import AuthenticationError, InvalidTokenError from plistsync.logger import log -from plistsync.utils.auth.bearer_token import InvalidTokenError from plistsync.utils.session import PlistsyncSession from .api import PlexToken @@ -106,7 +105,7 @@ def obtain_token(self, request: PlexAuthRequest, response: str | None) -> PlexTo while True: auth_token = self._fetch_auth_token(request.pin_id) if auth_token: - return PlexToken(auth_token, None) + return PlexToken(x_plex_token=auth_token) if time.monotonic() >= deadline: raise AuthenticationError( "Timed out waiting for Plex authentication. Please try again." @@ -118,9 +117,11 @@ def check_auth(self) -> bool: Loads the persisted token and verifies it against plex.tv. """ + token = self.config.token + if not isinstance(token, PlexToken): + return False try: - token = PlexToken.from_file(self.config.token_path) - token.validate(headers=self._headers()) + token.validate_remote(headers=self._headers()) except (InvalidTokenError, requests.RequestException) as e: log.debug("Plex authentication check failed: %s", e) return False diff --git a/plistsync/services/plex/config.py b/plistsync/services/plex/config.py index 5a510f06..2c898b68 100644 --- a/plistsync/services/plex/config.py +++ b/plistsync/services/plex/config.py @@ -3,7 +3,14 @@ from dataclasses import dataclass, field from typing import Annotated -from plistsync.core.config import ServiceConfig +from pydantic import SecretStr + +from plistsync.core.config import DataIO, ServiceConfig + +from .api import PlexToken + +_DEFAULT_SECTION = "Music" +_DEFAULT_REDIRECT_PORT = 20556 @dataclass @@ -26,12 +33,14 @@ class PlexConfig(ServiceConfig): section_name_or_id: Annotated[ str | int, "The name or ID of the Plex library section to use by default.", - ] = field(default="Music") + ] = field(default=_DEFAULT_SECTION) redirect_port: Annotated[ int, "The port to use for the local redirect server when authenticating.", - ] = field(default=20556) + ] = field(default=_DEFAULT_REDIRECT_PORT) + + token: DataIO[PlexToken] | PlexToken | None = field(default=None) @property def app_name(self) -> str: @@ -43,3 +52,26 @@ def client_identifier(self) -> str: # user but it is not strictly necessary and one global # id might allow us profiling across installs in the future. return "510457cfb15e4bf48d34563d0e4f1de1" + + def __init__( + self, + server_url: str | None = None, + server_name: str | None = None, + section_name_or_id: str | int = _DEFAULT_SECTION, + redirect_port: int = _DEFAULT_REDIRECT_PORT, + token: DataIO[PlexToken] | PlexToken | str | None = None, + ) -> None: + """Initialize the config, normalizing the token. + + ``token`` may be a ``str`` (parsed into a :class:`PlexToken`), a + :class:`DataIO` (used as the token source), or a :class:`PlexToken`. + """ + self.server_url = server_url + self.server_name = server_name + self.section_name_or_id = section_name_or_id + self.redirect_port = redirect_port + if isinstance(token, str): + token = PlexToken(x_plex_token=SecretStr(token)) + # Set the raw field: a DataIO is kept as-is instead of being routed + # through DataIO.__set__ (which would treat it as token data). + object.__setattr__(self, "token", token) diff --git a/plistsync/services/spotify/__init__.py b/plistsync/services/spotify/__init__.py index 2539cc6f..dfe02926 100644 --- a/plistsync/services/spotify/__init__.py +++ b/plistsync/services/spotify/__init__.py @@ -1,11 +1,5 @@ -from plistsync.errors import check_imports from plistsync.services import Service -check_imports( - service="spotify", - required_packages=["requests_oauth2client"], -) - from . import api from .auth import SpotifyAuth from .config import SpotifyConfig diff --git a/plistsync/services/spotify/api.py b/plistsync/services/spotify/api.py index 7cae564a..b4cf720c 100644 --- a/plistsync/services/spotify/api.py +++ b/plistsync/services/spotify/api.py @@ -5,18 +5,13 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literal, overload from urllib.parse import urlencode -import requests - from plistsync.logger import log from plistsync.utils import chunk_list -from plistsync.utils.auth.bearer_token import ( - InvalidTokenError, - Oauth2Token, - TokenSession, -) -from plistsync.utils.session import PlistsyncSession +from plistsync.utils.auth.oauth2 import OAuth2Token +from plistsync.utils.session import PlistsyncSession, TokenSession if TYPE_CHECKING: + import requests from requests.structures import CaseInsensitiveDict from .api_types import ( @@ -29,14 +24,13 @@ ) -class SpotifyApiSession(PlistsyncSession, TokenSession[Oauth2Token]): +class SpotifyApiSession(PlistsyncSession, TokenSession[OAuth2Token]): """A requests Session configured for Spotify. Automatically attaches the auth token and refreshes it as needed. Use for making multiple requests to the API. """ - # Used in BearerTokenSession status_codes_expired: ClassVar[list[int]] = [401] status_codes_rate_limit: ClassVar[list[int]] = [429] @@ -47,35 +41,19 @@ class SpotifyApiSession(PlistsyncSession, TokenSession[Oauth2Token]): def __init__( self, client_id: str, - token: Oauth2Token, + token: OAuth2Token, ): super().__init__(token=token) self.client_id = client_id self.headers["Accept"] = "application/json" def _refresh_token(self) -> None: - """Validate the spotify token by making a test request. - - According to API docs, one should use the /api/v2/user endpoint - to validate tokens. - """ + """Refresh the Spotify access token in place.""" log.debug("Refreshing expired Spotify token...") - res = requests.post( - "https://accounts.spotify.com/api/token", - data={ - "grant_type": "refresh_token", - "client_id": self.client_id, - "refresh_token": self.token.as_dict()["refresh_token"], - }, + self.token.refresh( + token_endpoint="https://accounts.spotify.com/api/token", + client_id=self.client_id, ) - try: - res.raise_for_status() - except requests.HTTPError as e: - log.error(res.text, stack_info=False) - raise InvalidTokenError(self.token) from e - - token_data = res.json() - self.token.update(token_data) def _handle_rate_limit(self, headers: CaseInsensitiveDict) -> None: remaining = int(headers.get("Retry-After", 0)) diff --git a/plistsync/services/spotify/auth.py b/plistsync/services/spotify/auth.py index 51195cba..45819882 100644 --- a/plistsync/services/spotify/auth.py +++ b/plistsync/services/spotify/auth.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING -from plistsync.core.auth import OAuth2Provider +from plistsync.utils.auth.oauth2 import OAuth2Provider if TYPE_CHECKING: from .config import SpotifyConfig diff --git a/plistsync/services/spotify/config.py b/plistsync/services/spotify/config.py index 8e2865cb..43a52112 100644 --- a/plistsync/services/spotify/config.py +++ b/plistsync/services/spotify/config.py @@ -1,10 +1,18 @@ +from __future__ import annotations + from dataclasses import dataclass, field from typing import Annotated -from plistsync.core.config import ServiceConfig +from pydantic import SecretStr + +from plistsync.core.config import DataIO, ServiceConfig +from plistsync.utils.auth.oauth2 import OAuth2Token + +_DEFAULT_CLIENT_ID = "3b408bca2c3344dfa1cda1c7fa9adde4" +_DEFAULT_REDIRECT_PORT = 20556 -@dataclass +@dataclass(init=False) class SpotifyConfig(ServiceConfig): """Configuration for the Spotify service.""" @@ -12,11 +20,27 @@ class SpotifyConfig(ServiceConfig): str, "The client ID for talking to the Spotify API. You can use the buildin one or" " obtain a new client ID by registering an Devleloper application.", - ] = field(default="3b408bca2c3344dfa1cda1c7fa9adde4") + ] = field(default=_DEFAULT_CLIENT_ID) redirect_port: Annotated[ int, "The port to use for the local redirect server when authenticating. If using " "the default Spotify client ID, this must be 20556, as is the port whitelisted" "by the app.", - ] = field(default=20556) + ] = field(default=_DEFAULT_REDIRECT_PORT) + + token: DataIO[OAuth2Token] | OAuth2Token | None = field(default=None) + + def __init__( + self, + client_id: str = _DEFAULT_CLIENT_ID, + redirect_port: int = _DEFAULT_REDIRECT_PORT, + token: DataIO[OAuth2Token] | OAuth2Token | str | None = None, + ) -> None: + """Initialize the config, normalizing the token.""" + self.client_id = client_id + self.redirect_port = redirect_port + if isinstance(token, str): + token = OAuth2Token(access_token=SecretStr(token)) + # Store the raw field: a DataIO is kept as-is instead of using token.__set__ + object.__setattr__(self, "token", token) diff --git a/plistsync/services/spotify/library.py b/plistsync/services/spotify/library.py index ec7fb4d3..5fdccf5b 100644 --- a/plistsync/services/spotify/library.py +++ b/plistsync/services/spotify/library.py @@ -10,8 +10,9 @@ Library, ) from plistsync.core.ids import ISRC, PlaylistID +from plistsync.errors import InvalidTokenError from plistsync.logger import log -from plistsync.utils.auth.bearer_token import Oauth2Token +from plistsync.utils.auth.oauth2 import OAuth2Token from .api import SpotifyApi, SpotifyApiSession from .config import SpotifyConfig @@ -44,15 +45,14 @@ def __init__(self, api: SpotifyApi) -> None: @classmethod def from_config(cls, config: SpotifyConfig) -> Self: """Construct a Spotify library from a service config.""" - - return cls( - SpotifyApi( - SpotifyApiSession( - client_id=config.client_id, - token=Oauth2Token.from_file(config.token_path), - ) - ) - ) + token = config.token + if not isinstance(token, OAuth2Token): + raise InvalidTokenError(None) + + session = SpotifyApiSession(client_id=config.client_id, token=token) + # Persist refreshed tokens back through the config's token DataIO. + session.on_refresh = lambda refreshed: setattr(config, "token", refreshed) + return cls(SpotifyApi(session)) # ------------------------ LibraryCollection protocol ------------------------ # diff --git a/plistsync/services/tidal/__init__.py b/plistsync/services/tidal/__init__.py index b8d62c80..68819b77 100644 --- a/plistsync/services/tidal/__init__.py +++ b/plistsync/services/tidal/__init__.py @@ -1,11 +1,5 @@ -from plistsync.errors import check_imports from plistsync.services import Service -check_imports( - service="tidal", - required_packages=["requests_oauth2client"], -) - from . import api from .auth import TidalAuth from .config import TidalConfig diff --git a/plistsync/services/tidal/api.py b/plistsync/services/tidal/api.py index 7ba12ad7..8b52498e 100644 --- a/plistsync/services/tidal/api.py +++ b/plistsync/services/tidal/api.py @@ -3,22 +3,17 @@ import time from typing import TYPE_CHECKING, Any, ClassVar, Literal, cast -import requests - from plistsync.logger import log from plistsync.utils import chunk_list -from plistsync.utils.auth.bearer_token import ( - InvalidTokenError, - Oauth2Token, - TokenSession, -) -from plistsync.utils.session import PlistsyncSession +from plistsync.utils.auth.oauth2 import OAuth2Token +from plistsync.utils.session import PlistsyncSession, TokenSession from .api_types import ( T_Included, ) if TYPE_CHECKING: + import requests from requests.structures import CaseInsensitiveDict from .api_types import ( @@ -49,14 +44,13 @@ MAX_FILTER_SIZE = 20 # Tidal limits 20 elements per request -class TidalApiSession(PlistsyncSession, TokenSession[Oauth2Token]): +class TidalApiSession(PlistsyncSession, TokenSession[OAuth2Token]): """A request Session configured for Tidal. Automatically attaches the auth token and refreshes it as needed. Use for making multiple requests to the API. """ - # Used in BearerTokenSession status_codes_expired: ClassVar[list[int]] = [401] status_codes_rate_limit: ClassVar[list[int]] = [429] @@ -67,7 +61,7 @@ class TidalApiSession(PlistsyncSession, TokenSession[Oauth2Token]): def __init__( self, client_id: str, - token: Oauth2Token, + token: OAuth2Token, ): super().__init__( rate_limit=0.25, # Tidal allows 4 requests per second @@ -76,30 +70,12 @@ def __init__( self.client_id = client_id def _refresh_token(self) -> None: - """Refresh the Tidal token. - - This function will refresh the Tidal token using the refresh token. - It will update the token in place. - """ + """Refresh the Tidal token in place using the refresh token.""" log.debug("Refreshing expired Tidal token...") - res = requests.Session.request( - self, - "POST", - "https://auth.tidal.com/v1/oauth2/token", - data={ - "grant_type": "refresh_token", - "client_id": self.client_id, - "refresh_token": self.token.as_dict()["refresh_token"], - }, + self.token.refresh( + token_endpoint="https://auth.tidal.com/v1/oauth2/token", + client_id=self.client_id, ) - try: - res.raise_for_status() - except requests.HTTPError as e: - log.error(res.text, stack_info=False) - raise InvalidTokenError(self.token) from e - - token_data = res.json() - self.token.update(token_data) def _handle_rate_limit(self, headers: CaseInsensitiveDict) -> None: remaining = int(headers.get("Retry-After", 0)) diff --git a/plistsync/services/tidal/auth.py b/plistsync/services/tidal/auth.py index 97c232ab..1908c25f 100644 --- a/plistsync/services/tidal/auth.py +++ b/plistsync/services/tidal/auth.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING -from plistsync.core.auth import OAuth2Provider +from plistsync.utils.auth.oauth2 import OAuth2Provider if TYPE_CHECKING: from .config import TidalConfig diff --git a/plistsync/services/tidal/config.py b/plistsync/services/tidal/config.py index 56f9486f..02e0adf3 100644 --- a/plistsync/services/tidal/config.py +++ b/plistsync/services/tidal/config.py @@ -1,7 +1,14 @@ from dataclasses import dataclass, field from typing import Annotated -from plistsync.core.config import ServiceConfig +from pydantic import SecretStr + +from plistsync.core.config import DataIO, ServiceConfig +from plistsync.utils.auth.oauth2 import OAuth2Token + +_DEFAULT_CLIENT_ID = "XhEgdcjkjfqTqw1y" +_DEFAULT_REDIRECT_PORT = 20556 +_DEFAULT_COUNTRY_CODE = "US" @dataclass @@ -10,17 +17,35 @@ class TidalConfig(ServiceConfig): str, "The client ID for talking to the Tidal API. You can use the buildin one or" "obtain a new client ID by registering an Devleloper application.", - ] = field(default="XhEgdcjkjfqTqw1y") + ] = field(default=_DEFAULT_CLIENT_ID) redirect_port: Annotated[ int, "The port to use for the local redirect server when authenticating. If using " "the default Tidal client ID, this must be 20556, as is the port whitelisted by" "our public client.", - ] = field(default=20556) + ] = field(default=_DEFAULT_REDIRECT_PORT) country_code: Annotated[ str, "The country code for the Tidal API. This is required for some endpoints. It" "influences track availability slightly.", - ] = field(default="US") + ] = field(default=_DEFAULT_COUNTRY_CODE) + + token: DataIO[OAuth2Token] | OAuth2Token | None = field(default=None) + + def __init__( + self, + client_id: str = _DEFAULT_CLIENT_ID, + redirect_port: int = _DEFAULT_REDIRECT_PORT, + country_code: str = _DEFAULT_COUNTRY_CODE, + token: DataIO[OAuth2Token] | OAuth2Token | str | None = None, + ) -> None: + """Initialize the config, normalizing the token.""" + self.client_id = client_id + self.redirect_port = redirect_port + self.country_code = country_code + if isinstance(token, str): + token = OAuth2Token(access_token=SecretStr(token)) + # Store the raw field: a DataIO is kept as-is instead of using token.__set__ + object.__setattr__(self, "token", token) diff --git a/plistsync/services/tidal/library.py b/plistsync/services/tidal/library.py index 82cd96cf..8c875f33 100644 --- a/plistsync/services/tidal/library.py +++ b/plistsync/services/tidal/library.py @@ -9,8 +9,9 @@ Library, ) from plistsync.core.ids import ISRC, PlaylistID +from plistsync.errors import InvalidTokenError from plistsync.logger import log -from plistsync.utils.auth.bearer_token import Oauth2Token +from plistsync.utils.auth.oauth2 import OAuth2Token from .api import TidalApi, TidalApiSession from .config import TidalConfig @@ -38,14 +39,14 @@ def __init__(self, api: TidalApi) -> None: @classmethod def from_config(cls, config: TidalConfig) -> Self: """Construct a Tidal library from a service config.""" - return cls( - TidalApi( - TidalApiSession( - client_id=config.client_id, - token=Oauth2Token.from_file(config.token_path), - ) - ) - ) + token = config.token + if not isinstance(token, OAuth2Token): + raise InvalidTokenError(None) + + session = TidalApiSession(client_id=config.client_id, token=token) + # Persist refreshed tokens back through the config's token DataIO. + session.on_refresh = lambda refreshed: setattr(config, "token", refreshed) + return cls(TidalApi(session)) # ------------------------ LibraryCollection protocol ------------------------ # diff --git a/plistsync/utils/auth/bearer_token.py b/plistsync/utils/auth/bearer_token.py deleted file mode 100644 index 3577d0ee..00000000 --- a/plistsync/utils/auth/bearer_token.py +++ /dev/null @@ -1,267 +0,0 @@ -"""Bearer token handling. - -This module provides functionality to manage Bearer tokens, including loading, saving to -json. -""" - -from __future__ import annotations - -import json -from abc import ABC, abstractmethod -from datetime import datetime -from pathlib import Path -from typing import ( - TYPE_CHECKING, - Any, - ClassVar, - Generic, - Self, - TypeVar, -) - -import requests -from requests_oauth2client import BearerToken as BearerTokenOauth2Client -from requests_oauth2client import MissingRefreshToken, OAuth2Error -from requests_oauth2client.tokens import ExpiredAccessToken - -if TYPE_CHECKING: - from requests.structures import CaseInsensitiveDict - from requests_oauth2client import OAuth2Client - - -class Token(ABC): - """Abstract base class for bearer tokens. - - Structurally satisfies the :class:`plistsync.core.auth.Token` protocol. - Inheriting that protocol explicitly would create an import cycle, since - ``core.auth`` uses :class:`Oauth2Token` to parameterize its providers. - -> TODO: This needs a bigger refactor! - """ - - file_path: Path | None - """Path where the token should be persisted. None for memory-only tokens.""" - - def __init__(self, file_path: Path | None) -> None: - self.file_path = file_path - - @abstractmethod - def as_dict(self) -> dict[str, Any]: - """Get the token data as a dictionary.""" - ... - - @classmethod - @abstractmethod - def from_dict(cls, token_dict: dict[str, Any]) -> Self: - """Create token from dict.""" - ... - - @abstractmethod - def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest: - """Prepare the request to use the authentication.""" - ... - - @property - def is_expired(self) -> bool: - """Check if the token is expired.""" - return False - - @classmethod - def from_file(cls, file_path: str | Path) -> Self: - """Create token instance from file.""" - try: - with open(file_path) as f: - token_dict = json.load(f) - token = cls.from_dict(token_dict) - token.file_path = Path(file_path) - return token - except Exception as e: - raise InvalidTokenError(None) from e - - def save(self) -> None: - """Persist token to :attr:`file_path`. Raises if file_path is None.""" - if self.file_path is None: - raise ValueError("Cannot save token: file_path is None") - with open(self.file_path, "w") as f: - json.dump(self.as_dict(), f) - - -class Oauth2Token(Token): - """Handles serialization and deserialization of token data.""" - - client: BearerTokenOauth2Client - - def __init__( - self, - client: BearerTokenOauth2Client, - file_path: Path | None, - ) -> None: - super().__init__(file_path) - self.client = client - - @staticmethod - def deserialize_dict(token_dict: dict[str, Any]) -> dict[str, Any]: - if "expires_at" in token_dict: - expires_at = token_dict.pop("expires_at") - # Convert to datetime if it's a string - if isinstance(expires_at, str): - expires_at = datetime.fromisoformat(expires_at) - token_dict["expires_at"] = expires_at - return token_dict - - def as_dict(self) -> dict[str, Any]: - """Get the token data as a dictionary.""" - d = self.client.as_dict() - if self.client.expires_at is not None: - d["expires_at"] = self.client.expires_at.isoformat() - d.pop("expires_in", None) - return d - - @classmethod - def from_dict(cls, token_dict: dict[str, Any]) -> Self: - """Create a BearerToken instance from a dictionary.""" - return cls(BearerTokenOauth2Client(**cls.deserialize_dict(token_dict)), None) - - def update(self, token_data: dict[str, Any]) -> None: - """Update the token data in place.""" - self.client = BearerTokenOauth2Client(**{**self.client.as_dict(), **token_data}) - - def refresh(self, client: OAuth2Client) -> None: - """Refresh the access token using an OAuth2 client.""" - try: - refreshed = client.refresh_token(self.client) - except (OAuth2Error, MissingRefreshToken, requests.RequestException) as e: - raise InvalidTokenError(self) from e - - self.update(refreshed.as_dict()) - if self.file_path is not None: - self.save() - - def __call__(self, *args, **kwargs): - return self.client(*args, **kwargs) - - def __repr__(self): - def mask(k: str, v: Any): - if not k.endswith("_token"): - return v - try: - v_str = str(v) - if len(v_str) < 9: - return "***" - return f"{v_str[:3]}...{v_str[-3:]}" - except Exception: - return v - - res = "BearerToken(" - res += ", ".join([f"{k}={mask(k, v)}" for k, v in self.as_dict().items()]) - return res + ")" - - @property - def is_expired(self) -> bool: - """Check if the token is expired.""" - return bool(self.client.is_expired()) - - -class InvalidTokenError(Exception): - def __init__(self, token: Token | None): - if token: - self.message = f"Invalid token: {token}" - else: - self.message = "Token not found. Have you created a token?" - super().__init__(self.message) - - -T = TypeVar("T", bound=Token) - - -class TokenSession(Generic[T], requests.Session, ABC): - """A request session configured to use a bearer token. - - This session manages authentication for API requests by automatically - attaching bearer tokens to outgoing requests and handling token - refresh when expired or rejected by the server. - """ - - token: T - """The current token used for authentication.""" - - status_codes_expired: ClassVar[list[int]] = [] - """HTTP status codes indicating an expired/invalid token.""" - - status_codes_rate_limit: ClassVar[list[int]] = [] - """HTTP status codes indicating rate limiting.""" - - def __init__( - self, - token: T, - ) -> None: - """Initialize the session with a token or token file.""" - super().__init__() - - self.token = token - - def request( - self, method: str | bytes, url: str | bytes, *args, **kwargs - ) -> requests.Response: - """Send a request with token authentication. - - Automatically handles token expiration and server-side token - rejection by refreshing and retrying once per failure mode. - """ - - if self.token.is_expired: - self.refresh_token() - - # Always use token in auth - kwargs["auth"] = self.token - - # Calling requests again can in theory - # create a infinite recursion but - # should not happen in practice (fingers crossed) - # we can add some max retry logic if this ever - # is an issue - try: - res = super().request( - method, - url, - *args, - **kwargs, - ) - except ExpiredAccessToken: - self.refresh_token() - return self.request(method, url, *args, **kwargs) - - if res.status_code in self.status_codes_expired: - self.refresh_token() - return self.request(method, url, *args, **kwargs) - elif res.status_code in self.status_codes_rate_limit: - self._handle_rate_limit(res.headers) - return self.request(method, url, *args, **kwargs) - - return res - - @abstractmethod - def _handle_rate_limit(self, headers: CaseInsensitiveDict) -> None: - """Handle a rate limit response from the server.""" - ... - - @abstractmethod - def _refresh_token(self) -> None: - """Fetch a new token from the API. - - Implementations should update the token inplace. - """ - ... - - def refresh_token(self) -> None: - """Refresh the token and persist it.""" - self._refresh_token() - if self.token.file_path is not None: - self.token.save() - - -__all__ = [ - "InvalidTokenError", - "Oauth2Token", - "Token", - "TokenSession", -] diff --git a/plistsync/utils/auth/oauth2.py b/plistsync/utils/auth/oauth2.py new file mode 100644 index 00000000..fd9f5567 --- /dev/null +++ b/plistsync/utils/auth/oauth2.py @@ -0,0 +1,276 @@ +"""OAuth2 authorization-code flow with PKCE and the associated token type.""" + +from __future__ import annotations + +import base64 +import hashlib +import secrets +from abc import ABC, abstractmethod +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING, Any, ClassVar +from urllib.parse import parse_qs, urlencode, urlparse + +import requests +from pydantic import ( + BaseModel, + ConfigDict, + SecretStr, + field_serializer, + model_validator, +) + +from plistsync.core.auth import AuthProvider, Token +from plistsync.errors import AuthenticationError, InvalidTokenError +from plistsync.logger import log +from plistsync.utils.session import PlistsyncSession + +if TYPE_CHECKING: + from plistsync.core.auth import Interaction + + +@dataclass(kw_only=True, frozen=True) +class OAuth2Request: + """Flow state for an OAuth2 authorization-code exchange.""" + + url: str + """Authorization URL to open in the browser by the user.""" + + redirect_uri: str + """Redirect URI to capture the callback on.""" + + state: str + """Random string to prevent CSRF attacks.""" + + code_verifier: str + """PKCE (S256) verifier for the token exchange.""" + + +class OAuth2Token(BaseModel, Token): + """An OAuth2 access token with an optional refresh token and expiry.""" + + model_config = ConfigDict( + hide_input_in_errors=True, # Allows to hide secret strings in output + ) + + access_token: SecretStr + token_type: str = "Bearer" + refresh_token: SecretStr | None = None + expires_at: datetime | None = None + scope: str | None = None + + EXPIRY_LEEWAY: ClassVar[int] = 10 + """Seconds before the actual expiry at which the token is considered stale.""" + + @model_validator(mode="before") + @classmethod + def _apply_expires_in(cls, data: Any) -> Any: + """Translate a relative ``expires_in`` into an absolute ``expires_at``.""" + if isinstance(data, dict) and data.get("expires_in") is not None: + return { + **data, + "expires_at": datetime.now(UTC) + + timedelta(seconds=int(data["expires_in"])), + } + return data + + @field_serializer("access_token", "refresh_token", when_used="always") + def _reveal_secrets(self, value: SecretStr | None) -> str | None: + """Expose the plaintext on serialization so tokens can be persisted.""" + return value.get_secret_value() if value is not None else None + + @property + def is_expired(self) -> bool: + """Whether the access token is expired (with a small leeway).""" + if self.expires_at is None: + return False + return datetime.now(UTC) >= self.expires_at - timedelta( + seconds=self.EXPIRY_LEEWAY + ) + + def update(self, token_data: dict[str, Any]) -> None: + """Update this token in place from a token-endpoint response.""" + merged = { + **self.model_dump(mode="json", exclude_none=True), + **{key: value for key, value in token_data.items() if value is not None}, + } + refreshed = type(self).model_validate(merged) + for name in type(self).model_fields: + setattr(self, name, getattr(refreshed, name)) + + def refresh( + self, + *, + token_endpoint: str, + client_id: str, + session: requests.Session | None = None, + timeout: float = 30, + ) -> None: + """Exchange the refresh token for a fresh access token, in place.""" + if not self.refresh_token: + raise InvalidTokenError(self) + + session = session or PlistsyncSession() + try: + response = session.post( + token_endpoint, + data={ + "grant_type": "refresh_token", + "client_id": client_id, + "refresh_token": self.refresh_token.get_secret_value(), + }, + timeout=timeout, + ) + except requests.RequestException as e: + raise InvalidTokenError(self) from e + + self.update(response.json()) + + def __call__(self, request: requests.PreparedRequest) -> requests.PreparedRequest: + """Attach the access token as an ``Authorization`` header.""" + request.headers["Authorization"] = ( + f"{self.token_type} {self.access_token.get_secret_value()}" + ) + return request + + +class OAuth2Provider(AuthProvider[OAuth2Request, str | None, OAuth2Token], ABC): + """Authenticate via OAuth2 authorization code flow with PKCE. + + To use this provider, implement the abstract methods and classvars. + """ + + authorize_endpoint: ClassVar[str] + """OAuth2 authorization endpoint, e.g. ``https://accounts.spotify.com/authorize``.""" + + token_endpoint: ClassVar[str] + """OAuth2 token endpoint used to exchange the callback code for a token.""" + + scopes: ClassVar[str] + """Scopes to request for the service.""" + + @abstractmethod + def client_id(self) -> str: + """Client ID for the service.""" + + @abstractmethod + def redirect_uri(self) -> str: + """Redirect URI to capture the callback on.""" + + @property + def extra_authorize_params(self) -> dict[str, str]: + """Additional query parameters for the authorization URL.""" + return {} + + def build_request(self) -> OAuth2Request: + """Build the authorization URL with a fresh PKCE verifier.""" + code_verifier, code_challenge = self._generate_pkce() + state = secrets.token_urlsafe(32) + redirect_uri = self.redirect_uri() + params = { + "response_type": "code", + "client_id": self.client_id(), + "redirect_uri": redirect_uri, + "scope": self.scopes, + "state": state, + "code_challenge": code_challenge, + "code_challenge_method": "S256", + **self.extra_authorize_params, + } + return OAuth2Request( + url=f"{self.authorize_endpoint}?{urlencode(params)}", + redirect_uri=redirect_uri, + state=state, + code_verifier=code_verifier, + ) + + def collect_response( + self, interaction: Interaction, request: OAuth2Request + ) -> str | None: + """Open the URL and serve the redirect.""" + interaction.open_url(request.url) + return interaction.capture_redirect(request.redirect_uri) + + def obtain_token(self, request: OAuth2Request, response: str | None) -> OAuth2Token: + """Exchange the callback code for a token.""" + if not response: + raise AuthenticationError("No callback received.") + + query = parse_qs(urlparse(response).query) + + error = query.get("error", [None])[0] + if error: + description = query.get("error_description", [error])[0] or error + raise AuthenticationError(description) + + code = query.get("code", [None])[0] + state = query.get("state", [None])[0] + if not code or not state: + raise AuthenticationError("Missing 'code' or 'state' in callback URL.") + if state != request.state: + raise AuthenticationError("OAuth state mismatch; aborting authentication.") + + token_data = self._exchange_code( + code, request.redirect_uri, request.code_verifier + ) + return OAuth2Token.model_validate(token_data) + + def check_auth(self) -> bool: + """Non-interactively check the current authentication status. + + Loads the persisted token and refreshes it if it has expired. A token + that cannot be loaded or refreshed is considered not authenticated. + """ + try: + token = getattr(self.config, "token", None) + if not isinstance(token, OAuth2Token): + return False + if token.is_expired: + token.refresh( + token_endpoint=self.token_endpoint, + client_id=self.client_id(), + ) + setattr(self.config, "token", token) + except (InvalidTokenError, KeyError, TypeError, ValueError) as e: + log.debug("Authentication check failed for %s: %s", type(self).__name__, e) + return False + + return True + + def _exchange_code( + self, code: str, redirect_uri: str, code_verifier: str + ) -> dict[str, Any]: + """Exchange an authorization code for a token payload.""" + try: + response = PlistsyncSession().post( + self.token_endpoint, + data={ + "grant_type": "authorization_code", + "client_id": self.client_id(), + "code": code, + "redirect_uri": redirect_uri, + "code_verifier": code_verifier, + }, + timeout=30, + ) + except requests.RequestException as e: + raise AuthenticationError(f"Failed to obtain token: {e}") from e + return response.json() + + @staticmethod + def _generate_pkce() -> tuple[str, str]: + """Generate a PKCE code verifier and its S256 challenge.""" + verifier = secrets.token_urlsafe(32) + challenge = ( + base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()) + .rstrip(b"=") + .decode() + ) + return verifier, challenge + + +__all__ = [ + "OAuth2Provider", + "OAuth2Request", + "OAuth2Token", +] diff --git a/plistsync/utils/session.py b/plistsync/utils/session.py index 2a58c246..fe71de90 100644 --- a/plistsync/utils/session.py +++ b/plistsync/utils/session.py @@ -1,11 +1,22 @@ +from __future__ import annotations + import threading import time +from abc import ABC, abstractmethod from importlib.metadata import version +from typing import TYPE_CHECKING, Any, ClassVar, Generic, TypeVar import requests from requests.sessions import HTTPAdapter from urllib3.util.retry import Retry +from plistsync.core.auth import Token + +if TYPE_CHECKING: + from collections.abc import Callable + + from requests.structures import CaseInsensitiveDict + class RateLimitAdapter(HTTPAdapter): """HTTPAdapter with rate limiting + automatic retries for API clients. @@ -83,3 +94,95 @@ def request(self, *args, **kwargs): r = super().request(*args, **kwargs) r.raise_for_status() return r + + +T = TypeVar("T", bound=Token) + + +class TokenSession(Generic[T], requests.Session, ABC): + """A request session configured to use a bearer token. + + This session manages authentication for API requests by automatically + attaching bearer tokens to outgoing requests and handling token + refresh when expired or rejected by the server. + """ + + token: T + """The current token used for authentication.""" + + status_codes_expired: ClassVar[list[int]] = [] + """HTTP status codes indicating an expired/invalid token.""" + + status_codes_rate_limit: ClassVar[list[int]] = [] + """HTTP status codes indicating rate limiting.""" + + on_refresh: Callable[[T], None] | None = None + """Called with the token after a refresh, e.g. to persist it.""" + + def __init__(self, token: T, **kwargs: Any) -> None: + """Initialize the session with a token.""" + super().__init__(**kwargs) + + self.token = token + + def request( + self, method: str | bytes, url: str | bytes, *args, **kwargs + ) -> requests.Response: + """Send a request with token authentication. + + Automatically handles token expiration and server-side token + rejection by refreshing and retrying once per failure mode. + """ + + if self.token.is_expired: + self.refresh_token() + + # Always use token in auth + kwargs["auth"] = self.token + + # Calling requests again can in theory + # create a infinite recursion but + # should not happen in practice (fingers crossed) + # we can add some max retry logic if this ever + # is an issue + res = super().request( + method, + url, + *args, + **kwargs, + ) + + if res.status_code in self.status_codes_expired: + self.refresh_token() + return self.request(method, url, *args, **kwargs) + elif res.status_code in self.status_codes_rate_limit: + self._handle_rate_limit(res.headers) + return self.request(method, url, *args, **kwargs) + + return res + + @abstractmethod + def _handle_rate_limit(self, headers: CaseInsensitiveDict) -> None: + """Handle a rate limit response from the server.""" + ... + + @abstractmethod + def _refresh_token(self) -> None: + """Fetch a new token from the API. + + Implementations should update the token inplace. + """ + ... + + def refresh_token(self) -> None: + """Refresh the token and hand it to :attr:`on_refresh`.""" + self._refresh_token() + if self.on_refresh is not None: + self.on_refresh(self.token) + + +__all__ = [ + "PlistsyncSession", + "RateLimitAdapter", + "TokenSession", +] diff --git a/pyproject.toml b/pyproject.toml index 5ccae4b8..b3578945 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,6 +4,7 @@ version = "0.8.0" requires-python = ">=3.11" dependencies = [ "eyconf[pydantic,cli]>=0.8.0", + "pydantic>=2.0", "requests>=2.32.5", "levenshtein>=0.27.3", "typer>=0.21.1", @@ -35,8 +36,8 @@ Changelog = "https://github.com/metasauce/plistsync/blob/main/CHANGELOG.md" [project.optional-dependencies] traktor = ["lxml>=6.0.2"] -spotify = ["requests_oauth2client>=1.8.0"] -tidal = ["requests_oauth2client>=1.8.0"] +spotify = [] +tidal = [] local = ["tinytag>=2.2.0"] beets = ["sqlalchemy>=2.0.45"] plex = ["nest-asyncio>=1.6.0", "plistsync[local]"] @@ -78,9 +79,6 @@ typed = [ "types-requests>=2.32.4.20260107", "types-tqdm>=4.67.0.20250809", "types-pyyaml>=6.0.12.20260724", - # FIXME: maybe we can remove this somehow as this is needed to full - # run mypy on the src (optional dependencies need types) - "requests_oauth2client>=1.8.0", "tinytag>=2.2.0", ] @@ -143,6 +141,14 @@ ignore = [ ] fixable = ["ALL"] +[tool.ruff.lint.flake8-type-checking] +# Pydantic resolve (field) annotations at runtime, so those types must +# stay importable even though `from __future__ import annotations` makes them lazy. +runtime-evaluated-base-classes = [ + "pydantic.BaseModel", + "plistsync.core.config.ServiceConfig", +] + [tool.ruff.lint.per-file-ignores] "**/tests/**" = [ "D", @@ -179,6 +185,7 @@ exclude_lines = ["if TYPE_CHECKING"] exclude_also = ["raise NotImplementedError", "@(abc\\.)?abstractmethod"] [tool.mypy] +plugins = ["pydantic.mypy"] check_untyped_defs = true disallow_untyped_decorators = true allow_redefinition = true diff --git a/tests/cli/test_auth.py b/tests/cli/test_auth.py index 4fc8f840..c55fa639 100644 --- a/tests/cli/test_auth.py +++ b/tests/cli/test_auth.py @@ -5,20 +5,21 @@ import json from contextlib import contextmanager from dataclasses import dataclass +from functools import cache from typing import TYPE_CHECKING, ClassVar from unittest.mock import patch import pytest +from pydantic import BaseModel from typer._click._compat import strip_ansi from typer.main import get_group from plistsync.cli.config import Config from plistsync.cli.service_commands.auth import CLIInteraction, RawRedirectHandler -from plistsync.core.config import ServiceConfig -from plistsync.core.auth import AuthProvider +from plistsync.core.auth import AuthProvider, Token +from plistsync.core.config import DataIO, ServiceConfig from plistsync.errors import AuthenticationError, HowTheForkDidYouEndUpHereError from plistsync.services import Service, ServiceLoader -from plistsync.utils.auth.bearer_token import InvalidTokenError, Token if TYPE_CHECKING: from collections.abc import Callable, Iterator @@ -28,18 +29,10 @@ from typer.testing import CliRunner -class FakeToken(Token): +class FakeToken(BaseModel, Token): """Minimal persistable token for CLI tests.""" - def __init__(self, file_path: Path | None = None) -> None: - super().__init__(file_path) - - def as_dict(self) -> dict: - return {"token": "secret"} - - @classmethod - def from_dict(cls, token_dict: dict) -> FakeToken: - return cls() + token: str = "secret" def __call__(self, request): return request @@ -47,21 +40,19 @@ def __call__(self, request): @dataclass class FakeConfig(ServiceConfig, service="fake"): - """Config for the fake service. + """Config for the fake service, persisting its token as JSON. - ``service="fake"`` registers it without relying on the module path. The - module override below makes the service name -- and therefore the token - path -- resolve to ``fake``. The field keeps the generated default config - valid, since an empty service section is parsed as ``None``. + The ``fake_option`` field keeps the generated default config from being + empty, since an empty service section is parsed as ``None``. """ fake_option: str = "default" + token: DataIO[FakeToken] | None = None - -# ``__module__`` must be set after the class body: ``@dataclass`` resolves -# string annotations via ``sys.modules[cls.__module__]``, and no -# ``plistsync.services.fake`` module exists. -FakeConfig.__module__ = "plistsync.services.fake" + @classmethod + @cache + def service(cls) -> str: + return "fake" class FakeAuthProvider(AuthProvider[None, None, FakeToken]): @@ -82,15 +73,10 @@ def collect_response(self, interaction, request) -> None: return None def obtain_token(self, request, response) -> FakeToken: - # The command persists the token at the service config's token path. return FakeToken() def check_auth(self) -> bool: - try: - FakeToken.from_file(self.config.token_path) - except InvalidTokenError: - return False - return True + return isinstance(self.config.token, FakeToken) class FakeService(Service): @@ -187,7 +173,6 @@ def test_runs_provider_and_saves_token( assert result.exit_code == 0, result.output mock_interaction.assert_called_once_with(mode="forward") assert json.loads(fake_token_file.read_text()) == {"token": "secret"} - assert str(fake_token_file) in result.output def test_mode_option_is_forwarded_to_interaction( self, runner: CliRunner, cli_app: typer.Typer @@ -219,7 +204,7 @@ class TestAuthCheck: def test_authenticated_token_reports_success( self, runner: CliRunner, cli_app: typer.Typer, fake_token_file: Path ) -> None: - FakeToken(fake_token_file).save() + fake_token_file.write_text(json.dumps({"token": "secret"})) with ( _fake_service(), diff --git a/tests/core/mock_auth.py b/tests/core/mock_auth.py new file mode 100644 index 00000000..e93602be --- /dev/null +++ b/tests/core/mock_auth.py @@ -0,0 +1,44 @@ +"""In-memory fakes for auth provider tests.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable + + +class FakeInteraction: + """In-memory implementation of the auth interaction protocol. + + Parameters + ---------- + redirect: + Value returned by :meth:`capture_redirect`: a fixed callback URL, + ``None``, or a callable receiving this interaction and the redirect + URI (e.g. to echo the ``state`` from the URL a provider opened). + """ + + def __init__( + self, + redirect: str | None | Callable[[FakeInteraction, str], str | None] = None, + ) -> None: + self.redirect = redirect + self.opened_urls: list[str] = [] + self.captured_uris: list[str] = [] + self.messages: list[str] = [] + + def open_url(self, url: str) -> None: + self.opened_urls.append(url) + + def show(self, message: str) -> None: + self.messages.append(message) + + def ask(self, message: str) -> str: + return "" + + def capture_redirect(self, redirect_uri: str) -> str | None: + self.captured_uris.append(redirect_uri) + if callable(self.redirect): + return self.redirect(self, redirect_uri) + return self.redirect diff --git a/tests/core/test_auth.py b/tests/core/test_auth.py index 1b384d74..3eb3a241 100644 --- a/tests/core/test_auth.py +++ b/tests/core/test_auth.py @@ -4,6 +4,7 @@ import base64 import hashlib +import json from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING from unittest.mock import MagicMock @@ -11,15 +12,15 @@ import pytest import requests -from requests_oauth2client import BearerToken +from pydantic import ValidationError -from plistsync.core.config import ServiceConfig -from plistsync.core.auth import AuthProvider, OAuth2Provider +from plistsync.core.auth import AuthProvider, Token +from plistsync.core.config import JsonFileIO, ServiceConfig from plistsync.errors import AuthenticationError -from plistsync.utils.auth.bearer_token import Oauth2Token, Token +from plistsync.utils.auth.oauth2 import OAuth2Provider, OAuth2Token +from tests.core.mock_auth import FakeInteraction if TYPE_CHECKING: - from collections.abc import Callable from pathlib import Path from plistsync.core.auth import Interaction @@ -28,56 +29,10 @@ class FakeToken(Token): """Minimal token for testing the provider flow.""" - def __init__(self) -> None: - super().__init__(None) - - def as_dict(self) -> dict: - return {"token": "secret"} - - @classmethod - def from_dict(cls, token_dict: dict) -> FakeToken: - return cls() - def __call__(self, request): return request -class FakeInteraction: - """In-memory implementation of the auth interaction protocol. - - Parameters - ---------- - redirect: - Value returned by :meth:`capture_redirect`: a fixed callback URL, - ``None``, or a callable receiving this interaction and the redirect - URI (e.g. to echo the ``state`` from the URL a provider opened). - """ - - def __init__( - self, - redirect: str | None | Callable[[FakeInteraction, str], str | None] = None, - ) -> None: - self.redirect = redirect - self.opened_urls: list[str] = [] - self.captured_uris: list[str] = [] - self.messages: list[str] = [] - - def open_url(self, url: str) -> None: - self.opened_urls.append(url) - - def show(self, message: str) -> None: - self.messages.append(message) - - def ask(self, message: str) -> str: - return "" - - def capture_redirect(self, redirect_uri: str) -> str | None: - self.captured_uris.append(redirect_uri) - if callable(self.redirect): - return self.redirect(self, redirect_uri) - return self.redirect - - def _oauth2_callback(interaction: FakeInteraction, redirect_uri: str) -> str: """Echo the state from the last opened URL into the OAuth2 callback.""" state = parse_qs(urlparse(interaction.opened_urls[-1]).query)["state"][0] @@ -124,6 +79,16 @@ def redirect_uri(self) -> str: return "http://127.0.0.1:1234/callback" +@pytest.fixture +def oauth_session(monkeypatch: pytest.MonkeyPatch) -> MagicMock: + """Mock the HTTP session used by the provider and by token refresh.""" + session = MagicMock() + monkeypatch.setattr( + "plistsync.utils.auth.oauth2.PlistsyncSession", lambda *args, **kwargs: session + ) + return session + + def test_build_request_uses_configured_redirect_uri() -> None: provider = FakeOAuth2Provider(ServiceConfig()) @@ -168,42 +133,27 @@ def test_abstract_subclass_uses_auth_provider_registry(self) -> None: assert OAuth2Provider.registry() is AuthProvider.registry() -class TestInteraction: - """The Interaction protocol is structural: the four primitives suffice.""" - - def test_in_memory_interaction_satisfies_protocol(self) -> None: - interaction: Interaction = FakeInteraction() - - interaction.open_url("https://example.com") - - assert interaction.opened_urls == ["https://example.com"] - - class TestOAuth2Provider: """The PKCE authorization-code flow, end to end.""" def test_authenticate_exchanges_code_for_token( - self, monkeypatch: pytest.MonkeyPatch + self, oauth_session: MagicMock ) -> None: provider = FakeOAuth2Provider(ServiceConfig()) interaction = FakeInteraction(redirect=_oauth2_callback) - session = MagicMock() - session.post.return_value.json.return_value = { + oauth_session.post.return_value.json.return_value = { "access_token": "access", "refresh_token": "refresh", "token_type": "Bearer", "expires_in": 3600, } - monkeypatch.setattr( - "plistsync.core.auth.PlistsyncSession", lambda *args, **kwargs: session - ) token = provider.authenticate(interaction) - assert token.as_dict()["access_token"] == "access" + assert token.access_token.get_secret_value() == "access" - assert session.post.call_args.args[0] == provider.token_endpoint - data = session.post.call_args.kwargs["data"] + assert oauth_session.post.call_args.args[0] == provider.token_endpoint + data = oauth_session.post.call_args.kwargs["data"] assert data["grant_type"] == "authorization_code" assert data["client_id"] == "client-id" assert data["code"] == "auth-code" @@ -223,15 +173,9 @@ def test_authenticate_exchanges_code_for_token( ) assert challenge == expected_challenge - def test_authenticate_wraps_exchange_errors( - self, monkeypatch: pytest.MonkeyPatch - ) -> None: + def test_authenticate_wraps_exchange_errors(self, oauth_session: MagicMock) -> None: provider = FakeOAuth2Provider(ServiceConfig()) - session = MagicMock() - session.post.side_effect = requests.RequestException("boom") - monkeypatch.setattr( - "plistsync.core.auth.PlistsyncSession", lambda *args, **kwargs: session - ) + oauth_session.post.side_effect = requests.RequestException("boom") with pytest.raises(AuthenticationError, match="Failed to obtain token"): provider.authenticate(FakeInteraction(redirect=_oauth2_callback)) @@ -258,63 +202,88 @@ def test_obtain_token_rejects_bad_callbacks( provider.obtain_token(request, callback) -def _write_oauth2_token( - path: Path, *, expired: bool = False, refresh_token: str | None = None -) -> None: - """Write a real Oauth2Token with an expiry hint in the past or future.""" - expires_at = datetime.now(UTC) + timedelta(hours=-1 if expired else 1) - token = Oauth2Token( - BearerToken( - access_token="access", - expires_at=expires_at, - refresh_token=refresh_token, - ), - path, +def _oauth2_token( + *, expired: bool = False, refresh_token: str | None = None +) -> OAuth2Token: + """An OAuth2 token whose expiry lies in the past or the future.""" + return OAuth2Token( + access_token="access", + expires_at=datetime.now(UTC) + timedelta(hours=-1 if expired else 1), + refresh_token=refresh_token, ) - token.save() + + +def _config(tmp_path: Path, *, token: OAuth2Token | None = None) -> ServiceConfig: + """A config whose ``token`` field persists to ``tmp_path`` as JSON.""" + config = ServiceConfig() + config.token = JsonFileIO[OAuth2Token](tmp_path / "token.json") + if token is not None: + config.token = token + return config class TestAuthCheck: """Non-interactive authentication status checks.""" - @pytest.fixture - def token_path(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - path = tmp_path / "token.json" - monkeypatch.setattr(ServiceConfig, "token_path", property(lambda self: path)) - return path - - def test_missing_token(self, token_path: Path) -> None: - assert FakeOAuth2Provider(ServiceConfig()).check_auth() is False + def test_missing_token(self, tmp_path: Path) -> None: + assert FakeOAuth2Provider(_config(tmp_path)).check_auth() is False - def test_valid_token(self, token_path: Path) -> None: - _write_oauth2_token(token_path) + def test_valid_token(self, tmp_path: Path) -> None: + config = _config(tmp_path, token=_oauth2_token()) - assert FakeOAuth2Provider(ServiceConfig()).check_auth() is True + assert FakeOAuth2Provider(config).check_auth() is True def test_expired_token_is_refreshed( - self, token_path: Path, monkeypatch: pytest.MonkeyPatch + self, tmp_path: Path, oauth_session: MagicMock ) -> None: - _write_oauth2_token(token_path, expired=True, refresh_token="refresh") - oauth2_client = MagicMock() - oauth2_client.return_value.refresh_token.return_value = BearerToken( - access_token="new-access", - expires_at=datetime.now(UTC) + timedelta(hours=1), + config = _config( + tmp_path, token=_oauth2_token(expired=True, refresh_token="refresh") ) - monkeypatch.setattr("plistsync.core.auth.OAuth2Client", oauth2_client) + oauth_session.post.return_value.json.return_value = { + "access_token": "new-access", + "expires_in": 3600, + } - assert FakeOAuth2Provider(ServiceConfig()).check_auth() is True - assert Oauth2Token.from_file(token_path).as_dict()["access_token"] == ( + assert FakeOAuth2Provider(config).check_auth() is True + assert json.loads((tmp_path / "token.json").read_text())["access_token"] == ( "new-access" ) + assert oauth_session.post.call_args.args[0] == FakeOAuth2Provider.token_endpoint + assert ( + oauth_session.post.call_args.kwargs["data"]["grant_type"] == "refresh_token" + ) - def test_failed_refresh( - self, token_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - _write_oauth2_token(token_path, expired=True, refresh_token="refresh") - oauth2_client = MagicMock() - oauth2_client.return_value.refresh_token.side_effect = ( - requests.RequestException("boom") + def test_failed_refresh(self, tmp_path: Path, oauth_session: MagicMock) -> None: + config = _config( + tmp_path, token=_oauth2_token(expired=True, refresh_token="refresh") ) - monkeypatch.setattr("plistsync.core.auth.OAuth2Client", oauth2_client) + oauth_session.post.side_effect = requests.RequestException("boom") + + assert FakeOAuth2Provider(config).check_auth() is False + + +class TestOAuth2TokenSecrets: + """Secret fields are masked in repr/errors but revealed on serialization.""" + + @pytest.fixture + def token(self) -> OAuth2Token: + return OAuth2Token(access_token="secret-access", refresh_token="secret-refresh") + + def test_repr_masks_secrets(self, token: OAuth2Token) -> None: + rendered = repr(token) + + assert "secret-access" not in rendered + assert "secret-refresh" not in rendered + + def test_serialization_reveals_secrets(self, token: OAuth2Token) -> None: + payload = token.model_dump(mode="json") + + assert payload["access_token"] == "secret-access" + assert payload["refresh_token"] == "secret-refresh" + + def test_validation_error_does_not_leak_secret(self) -> None: + with pytest.raises(ValidationError) as excinfo: + OAuth2Token(access_token="secret-access", expires_at="not-a-date") - assert FakeOAuth2Provider(ServiceConfig()).check_auth() is False + assert "secret-access" not in str(excinfo.value) + assert "secret-access" not in excinfo.value.json() diff --git a/tests/services/plex/test_auth.py b/tests/services/plex/test_auth.py index 7da517d8..8a0fb546 100644 --- a/tests/services/plex/test_auth.py +++ b/tests/services/plex/test_auth.py @@ -1,7 +1,5 @@ from __future__ import annotations -import json -from typing import TYPE_CHECKING from unittest.mock import MagicMock from urllib.parse import parse_qs, urlparse @@ -12,46 +10,7 @@ from plistsync.services.plex.api import PlexToken from plistsync.services.plex.auth import PlexAuth, PlexAuthRequest from plistsync.services.plex.config import PlexConfig - -if TYPE_CHECKING: - from collections.abc import Callable - from pathlib import Path - - -class FakeInteraction: - """In-memory implementation of the auth interaction protocol. - - Parameters - ---------- - redirect: - Value returned by :meth:`capture_redirect`: a fixed callback URL, - ``None``, or a callable receiving this interaction and the redirect - URI (e.g. to echo the ``state`` from the URL a provider opened). - """ - - def __init__( - self, - redirect: str | None | Callable[[FakeInteraction, str], str | None] = None, - ) -> None: - self.redirect = redirect - self.opened_urls: list[str] = [] - self.captured_uris: list[str] = [] - self.messages: list[str] = [] - - def open_url(self, url: str) -> None: - self.opened_urls.append(url) - - def show(self, message: str) -> None: - self.messages.append(message) - - def ask(self, message: str) -> str: - return "" - - def capture_redirect(self, redirect_uri: str) -> str | None: - self.captured_uris.append(redirect_uri) - if callable(self.redirect): - return self.redirect(self, redirect_uri) - return self.redirect +from tests.core.mock_auth import FakeInteraction def _response(payload: dict) -> MagicMock: @@ -159,7 +118,7 @@ def test_obtain_token_polls_until_token_is_available( token = auth.obtain_token(auth_request, None) assert isinstance(token, PlexToken) - assert token.x_plex_token == "plex-auth-token" + assert token.x_plex_token.get_secret_value() == "plex-auth-token" assert session.get.call_count == 2 assert session.get.call_args.args[0] == f"{PlexAuth.pins_endpoint}/42" headers = session.get.call_args.kwargs["headers"] @@ -199,22 +158,15 @@ def test_authenticate_runs_the_full_flow( token = auth.authenticate(interaction) - assert token.x_plex_token == "plex-auth-token" + assert token.x_plex_token.get_secret_value() == "plex-auth-token" assert interaction.opened_urls != [] @pytest.mark.parametrize(("ok", "expected"), [(True, True), (False, False)]) def test_check_auth( - self, - auth: PlexAuth, - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - ok: bool, - expected: bool, + self, auth: PlexAuth, monkeypatch: pytest.MonkeyPatch, ok: bool, expected: bool ) -> None: - """Loads the persisted token and validates it against plex.tv.""" - token_file = tmp_path / "plex_token.json" - token_file.write_text(json.dumps({"X-Plex-Token": "plex-auth-token"})) - monkeypatch.setattr(PlexConfig, "token_path", property(lambda self: token_file)) + """Validates the config's token against plex.tv.""" + auth.config.token = PlexToken(x_plex_token="plex-auth-token") session = MagicMock() monkeypatch.setattr( "plistsync.services.plex.api.PlistsyncSession", @@ -223,3 +175,17 @@ def test_check_auth( session.get.return_value = MagicMock(ok=ok) assert auth.check_auth() is expected + + +class TestPlexTokenSecrets: + """The Plex token is masked in repr but revealed on serialization.""" + + def test_repr_masks_token(self) -> None: + token = PlexToken(x_plex_token="plex-secret-token") + + assert "plex-secret-token" not in repr(token) + + def test_serialization_reveals_token(self) -> None: + token = PlexToken(x_plex_token="plex-secret-token") + + assert token.model_dump(mode="json") == {"x_plex_token": "plex-secret-token"} diff --git a/uv.lock b/uv.lock index 61eaa13b..d0886263 100644 --- a/uv.lock +++ b/uv.lock @@ -140,18 +140,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/62/26/c459ae5217a69d1a2c83ddb80b61480764e990049b7d9f6a5b82660457f4/beets-2.5.1-py3-none-any.whl", hash = "sha256:3e58f33d898d007e6bfd385bd145d2c39325ef6b6f831f7269d037bbcb542bf7", size = 573677, upload-time = "2025-10-14T22:52:53.728Z" }, ] -[[package]] -name = "binapy" -version = "0.8.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/bb/12/64a6df32e9bf0eea5dd2a448d37bbfe49b4aae0acb20b46381bf76304a0a/binapy-0.8.0.tar.gz", hash = "sha256:570c5098d42f037ffb3d2e563998f3cff69ad25ca1f43f9c3815432dccd08233", size = 20315, upload-time = "2024-01-19T11:57:20.096Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/94/50/a2ca5609cffc918a339be4ec5070c6d1d9fab600e6d9164df18040137383/binapy-0.8.0-py3-none-any.whl", hash = "sha256:8af1e1e856900ef8b79ef32236e296127c9cf26414ec355982ff7ce5f173504d", size = 16993, upload-time = "2024-01-19T11:57:18.876Z" }, -] - [[package]] name = "bleach" version = "6.3.0" @@ -464,68 +452,6 @@ toml = [ { name = "tomli", marker = "python_full_version <= '3.11'" }, ] -[[package]] -name = "cryptography" -version = "46.0.3" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/9f/33/c00162f49c0e2fe8064a62cb92b93e50c74a72bc370ab92f86112b33ff62/cryptography-46.0.3.tar.gz", hash = "sha256:a8b17438104fed022ce745b362294d9ce35b4c2e45c1d958ad4a4b019285f4a1", size = 749258, upload-time = "2025-10-15T23:18:31.74Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/1d/42/9c391dd801d6cf0d561b5890549d4b27bafcc53b39c31a817e69d87c625b/cryptography-46.0.3-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:109d4ddfadf17e8e7779c39f9b18111a09efb969a301a31e987416a0191ed93a", size = 7225004, upload-time = "2025-10-15T23:16:52.239Z" }, - { url = "https://files.pythonhosted.org/packages/1c/67/38769ca6b65f07461eb200e85fc1639b438bdc667be02cf7f2cd6a64601c/cryptography-46.0.3-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:09859af8466b69bc3c27bdf4f5d84a665e0f7ab5088412e9e2ec49758eca5cbc", size = 4296667, upload-time = "2025-10-15T23:16:54.369Z" }, - { url = "https://files.pythonhosted.org/packages/5c/49/498c86566a1d80e978b42f0d702795f69887005548c041636df6ae1ca64c/cryptography-46.0.3-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:01ca9ff2885f3acc98c29f1860552e37f6d7c7d013d7334ff2a9de43a449315d", size = 4450807, upload-time = "2025-10-15T23:16:56.414Z" }, - { url = "https://files.pythonhosted.org/packages/4b/0a/863a3604112174c8624a2ac3c038662d9e59970c7f926acdcfaed8d61142/cryptography-46.0.3-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:6eae65d4c3d33da080cff9c4ab1f711b15c1d9760809dad6ea763f3812d254cb", size = 4299615, upload-time = "2025-10-15T23:16:58.442Z" }, - { url = "https://files.pythonhosted.org/packages/64/02/b73a533f6b64a69f3cd3872acb6ebc12aef924d8d103133bb3ea750dc703/cryptography-46.0.3-cp311-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:e5bf0ed4490068a2e72ac03d786693adeb909981cc596425d09032d372bcc849", size = 4016800, upload-time = "2025-10-15T23:17:00.378Z" }, - { url = "https://files.pythonhosted.org/packages/25/d5/16e41afbfa450cde85a3b7ec599bebefaef16b5c6ba4ec49a3532336ed72/cryptography-46.0.3-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:5ecfccd2329e37e9b7112a888e76d9feca2347f12f37918facbb893d7bb88ee8", size = 4984707, upload-time = "2025-10-15T23:17:01.98Z" }, - { url = "https://files.pythonhosted.org/packages/c9/56/e7e69b427c3878352c2fb9b450bd0e19ed552753491d39d7d0a2f5226d41/cryptography-46.0.3-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:a2c0cd47381a3229c403062f764160d57d4d175e022c1df84e168c6251a22eec", size = 4482541, upload-time = "2025-10-15T23:17:04.078Z" }, - { url = "https://files.pythonhosted.org/packages/78/f6/50736d40d97e8483172f1bb6e698895b92a223dba513b0ca6f06b2365339/cryptography-46.0.3-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:549e234ff32571b1f4076ac269fcce7a808d3bf98b76c8dd560e42dbc66d7d91", size = 4299464, upload-time = "2025-10-15T23:17:05.483Z" }, - { url = "https://files.pythonhosted.org/packages/00/de/d8e26b1a855f19d9994a19c702fa2e93b0456beccbcfe437eda00e0701f2/cryptography-46.0.3-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:c0a7bb1a68a5d3471880e264621346c48665b3bf1c3759d682fc0864c540bd9e", size = 4950838, upload-time = "2025-10-15T23:17:07.425Z" }, - { url = "https://files.pythonhosted.org/packages/8f/29/798fc4ec461a1c9e9f735f2fc58741b0daae30688f41b2497dcbc9ed1355/cryptography-46.0.3-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:10b01676fc208c3e6feeb25a8b83d81767e8059e1fe86e1dc62d10a3018fa926", size = 4481596, upload-time = "2025-10-15T23:17:09.343Z" }, - { url = "https://files.pythonhosted.org/packages/15/8d/03cd48b20a573adfff7652b76271078e3045b9f49387920e7f1f631d125e/cryptography-46.0.3-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:0abf1ffd6e57c67e92af68330d05760b7b7efb243aab8377e583284dbab72c71", size = 4426782, upload-time = "2025-10-15T23:17:11.22Z" }, - { url = "https://files.pythonhosted.org/packages/fa/b1/ebacbfe53317d55cf33165bda24c86523497a6881f339f9aae5c2e13e57b/cryptography-46.0.3-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a04bee9ab6a4da801eb9b51f1b708a1b5b5c9eb48c03f74198464c66f0d344ac", size = 4698381, upload-time = "2025-10-15T23:17:12.829Z" }, - { url = "https://files.pythonhosted.org/packages/96/92/8a6a9525893325fc057a01f654d7efc2c64b9de90413adcf605a85744ff4/cryptography-46.0.3-cp311-abi3-win32.whl", hash = "sha256:f260d0d41e9b4da1ed1e0f1ce571f97fe370b152ab18778e9e8f67d6af432018", size = 3055988, upload-time = "2025-10-15T23:17:14.65Z" }, - { url = "https://files.pythonhosted.org/packages/7e/bf/80fbf45253ea585a1e492a6a17efcb93467701fa79e71550a430c5e60df0/cryptography-46.0.3-cp311-abi3-win_amd64.whl", hash = "sha256:a9a3008438615669153eb86b26b61e09993921ebdd75385ddd748702c5adfddb", size = 3514451, upload-time = "2025-10-15T23:17:16.142Z" }, - { url = "https://files.pythonhosted.org/packages/2e/af/9b302da4c87b0beb9db4e756386a7c6c5b8003cd0e742277888d352ae91d/cryptography-46.0.3-cp311-abi3-win_arm64.whl", hash = "sha256:5d7f93296ee28f68447397bf5198428c9aeeab45705a55d53a6343455dcb2c3c", size = 2928007, upload-time = "2025-10-15T23:17:18.04Z" }, - { url = "https://files.pythonhosted.org/packages/f5/e2/a510aa736755bffa9d2f75029c229111a1d02f8ecd5de03078f4c18d91a3/cryptography-46.0.3-cp314-cp314t-macosx_10_9_universal2.whl", hash = "sha256:00a5e7e87938e5ff9ff5447ab086a5706a957137e6e433841e9d24f38a065217", size = 7158012, upload-time = "2025-10-15T23:17:19.982Z" }, - { url = "https://files.pythonhosted.org/packages/73/dc/9aa866fbdbb95b02e7f9d086f1fccfeebf8953509b87e3f28fff927ff8a0/cryptography-46.0.3-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c8daeb2d2174beb4575b77482320303f3d39b8e81153da4f0fb08eb5fe86a6c5", size = 4288728, upload-time = "2025-10-15T23:17:21.527Z" }, - { url = "https://files.pythonhosted.org/packages/c5/fd/bc1daf8230eaa075184cbbf5f8cd00ba9db4fd32d63fb83da4671b72ed8a/cryptography-46.0.3-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:39b6755623145ad5eff1dab323f4eae2a32a77a7abef2c5089a04a3d04366715", size = 4435078, upload-time = "2025-10-15T23:17:23.042Z" }, - { url = "https://files.pythonhosted.org/packages/82/98/d3bd5407ce4c60017f8ff9e63ffee4200ab3e23fe05b765cab805a7db008/cryptography-46.0.3-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:db391fa7c66df6762ee3f00c95a89e6d428f4d60e7abc8328f4fe155b5ac6e54", size = 4293460, upload-time = "2025-10-15T23:17:24.885Z" }, - { url = "https://files.pythonhosted.org/packages/26/e9/e23e7900983c2b8af7a08098db406cf989d7f09caea7897e347598d4cd5b/cryptography-46.0.3-cp314-cp314t-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:78a97cf6a8839a48c49271cdcbd5cf37ca2c1d6b7fdd86cc864f302b5e9bf459", size = 3995237, upload-time = "2025-10-15T23:17:26.449Z" }, - { url = "https://files.pythonhosted.org/packages/91/15/af68c509d4a138cfe299d0d7ddb14afba15233223ebd933b4bbdbc7155d3/cryptography-46.0.3-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:dfb781ff7eaa91a6f7fd41776ec37c5853c795d3b358d4896fdbb5df168af422", size = 4967344, upload-time = "2025-10-15T23:17:28.06Z" }, - { url = "https://files.pythonhosted.org/packages/ca/e3/8643d077c53868b681af077edf6b3cb58288b5423610f21c62aadcbe99f4/cryptography-46.0.3-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:6f61efb26e76c45c4a227835ddeae96d83624fb0d29eb5df5b96e14ed1a0afb7", size = 4466564, upload-time = "2025-10-15T23:17:29.665Z" }, - { url = "https://files.pythonhosted.org/packages/0e/43/c1e8726fa59c236ff477ff2b5dc071e54b21e5a1e51aa2cee1676f1c986f/cryptography-46.0.3-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:23b1a8f26e43f47ceb6d6a43115f33a5a37d57df4ea0ca295b780ae8546e8044", size = 4292415, upload-time = "2025-10-15T23:17:31.686Z" }, - { url = "https://files.pythonhosted.org/packages/42/f9/2f8fefdb1aee8a8e3256a0568cffc4e6d517b256a2fe97a029b3f1b9fe7e/cryptography-46.0.3-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:b419ae593c86b87014b9be7396b385491ad7f320bde96826d0dd174459e54665", size = 4931457, upload-time = "2025-10-15T23:17:33.478Z" }, - { url = "https://files.pythonhosted.org/packages/79/30/9b54127a9a778ccd6d27c3da7563e9f2d341826075ceab89ae3b41bf5be2/cryptography-46.0.3-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:50fc3343ac490c6b08c0cf0d704e881d0d660be923fd3076db3e932007e726e3", size = 4466074, upload-time = "2025-10-15T23:17:35.158Z" }, - { url = "https://files.pythonhosted.org/packages/ac/68/b4f4a10928e26c941b1b6a179143af9f4d27d88fe84a6a3c53592d2e76bf/cryptography-46.0.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:22d7e97932f511d6b0b04f2bfd818d73dcd5928db509460aaf48384778eb6d20", size = 4420569, upload-time = "2025-10-15T23:17:37.188Z" }, - { url = "https://files.pythonhosted.org/packages/a3/49/3746dab4c0d1979888f125226357d3262a6dd40e114ac29e3d2abdf1ec55/cryptography-46.0.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:d55f3dffadd674514ad19451161118fd010988540cee43d8bc20675e775925de", size = 4681941, upload-time = "2025-10-15T23:17:39.236Z" }, - { url = "https://files.pythonhosted.org/packages/fd/30/27654c1dbaf7e4a3531fa1fc77986d04aefa4d6d78259a62c9dc13d7ad36/cryptography-46.0.3-cp314-cp314t-win32.whl", hash = "sha256:8a6e050cb6164d3f830453754094c086ff2d0b2f3a897a1d9820f6139a1f0914", size = 3022339, upload-time = "2025-10-15T23:17:40.888Z" }, - { url = "https://files.pythonhosted.org/packages/f6/30/640f34ccd4d2a1bc88367b54b926b781b5a018d65f404d409aba76a84b1c/cryptography-46.0.3-cp314-cp314t-win_amd64.whl", hash = "sha256:760f83faa07f8b64e9c33fc963d790a2edb24efb479e3520c14a45741cd9b2db", size = 3494315, upload-time = "2025-10-15T23:17:42.769Z" }, - { url = "https://files.pythonhosted.org/packages/ba/8b/88cc7e3bd0a8e7b861f26981f7b820e1f46aa9d26cc482d0feba0ecb4919/cryptography-46.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:516ea134e703e9fe26bcd1277a4b59ad30586ea90c365a87781d7887a646fe21", size = 2919331, upload-time = "2025-10-15T23:17:44.468Z" }, - { url = "https://files.pythonhosted.org/packages/fd/23/45fe7f376a7df8daf6da3556603b36f53475a99ce4faacb6ba2cf3d82021/cryptography-46.0.3-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:cb3d760a6117f621261d662bccc8ef5bc32ca673e037c83fbe565324f5c46936", size = 7218248, upload-time = "2025-10-15T23:17:46.294Z" }, - { url = "https://files.pythonhosted.org/packages/27/32/b68d27471372737054cbd34c84981f9edbc24fe67ca225d389799614e27f/cryptography-46.0.3-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:4b7387121ac7d15e550f5cb4a43aef2559ed759c35df7336c402bb8275ac9683", size = 4294089, upload-time = "2025-10-15T23:17:48.269Z" }, - { url = "https://files.pythonhosted.org/packages/26/42/fa8389d4478368743e24e61eea78846a0006caffaf72ea24a15159215a14/cryptography-46.0.3-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:15ab9b093e8f09daab0f2159bb7e47532596075139dd74365da52ecc9cb46c5d", size = 4440029, upload-time = "2025-10-15T23:17:49.837Z" }, - { url = "https://files.pythonhosted.org/packages/5f/eb/f483db0ec5ac040824f269e93dd2bd8a21ecd1027e77ad7bdf6914f2fd80/cryptography-46.0.3-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:46acf53b40ea38f9c6c229599a4a13f0d46a6c3fa9ef19fc1a124d62e338dfa0", size = 4297222, upload-time = "2025-10-15T23:17:51.357Z" }, - { url = "https://files.pythonhosted.org/packages/fd/cf/da9502c4e1912cb1da3807ea3618a6829bee8207456fbbeebc361ec38ba3/cryptography-46.0.3-cp38-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:10ca84c4668d066a9878890047f03546f3ae0a6b8b39b697457b7757aaf18dbc", size = 4012280, upload-time = "2025-10-15T23:17:52.964Z" }, - { url = "https://files.pythonhosted.org/packages/6b/8f/9adb86b93330e0df8b3dcf03eae67c33ba89958fc2e03862ef1ac2b42465/cryptography-46.0.3-cp38-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:36e627112085bb3b81b19fed209c05ce2a52ee8b15d161b7c643a7d5a88491f3", size = 4978958, upload-time = "2025-10-15T23:17:54.965Z" }, - { url = "https://files.pythonhosted.org/packages/d1/a0/5fa77988289c34bdb9f913f5606ecc9ada1adb5ae870bd0d1054a7021cc4/cryptography-46.0.3-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:1000713389b75c449a6e979ffc7dcc8ac90b437048766cef052d4d30b8220971", size = 4473714, upload-time = "2025-10-15T23:17:56.754Z" }, - { url = "https://files.pythonhosted.org/packages/14/e5/fc82d72a58d41c393697aa18c9abe5ae1214ff6f2a5c18ac470f92777895/cryptography-46.0.3-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:b02cf04496f6576afffef5ddd04a0cb7d49cf6be16a9059d793a30b035f6b6ac", size = 4296970, upload-time = "2025-10-15T23:17:58.588Z" }, - { url = "https://files.pythonhosted.org/packages/78/06/5663ed35438d0b09056973994f1aec467492b33bd31da36e468b01ec1097/cryptography-46.0.3-cp38-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:71e842ec9bc7abf543b47cf86b9a743baa95f4677d22baa4c7d5c69e49e9bc04", size = 4940236, upload-time = "2025-10-15T23:18:00.897Z" }, - { url = "https://files.pythonhosted.org/packages/fc/59/873633f3f2dcd8a053b8dd1d38f783043b5fce589c0f6988bf55ef57e43e/cryptography-46.0.3-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:402b58fc32614f00980b66d6e56a5b4118e6cb362ae8f3fda141ba4689bd4506", size = 4472642, upload-time = "2025-10-15T23:18:02.749Z" }, - { url = "https://files.pythonhosted.org/packages/3d/39/8e71f3930e40f6877737d6f69248cf74d4e34b886a3967d32f919cc50d3b/cryptography-46.0.3-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:ef639cb3372f69ec44915fafcd6698b6cc78fbe0c2ea41be867f6ed612811963", size = 4423126, upload-time = "2025-10-15T23:18:04.85Z" }, - { url = "https://files.pythonhosted.org/packages/cd/c7/f65027c2810e14c3e7268353b1681932b87e5a48e65505d8cc17c99e36ae/cryptography-46.0.3-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3b51b8ca4f1c6453d8829e1eb7299499ca7f313900dd4d89a24b8b87c0a780d4", size = 4686573, upload-time = "2025-10-15T23:18:06.908Z" }, - { url = "https://files.pythonhosted.org/packages/0a/6e/1c8331ddf91ca4730ab3086a0f1be19c65510a33b5a441cb334e7a2d2560/cryptography-46.0.3-cp38-abi3-win32.whl", hash = "sha256:6276eb85ef938dc035d59b87c8a7dc559a232f954962520137529d77b18ff1df", size = 3036695, upload-time = "2025-10-15T23:18:08.672Z" }, - { url = "https://files.pythonhosted.org/packages/90/45/b0d691df20633eff80955a0fc7695ff9051ffce8b69741444bd9ed7bd0db/cryptography-46.0.3-cp38-abi3-win_amd64.whl", hash = "sha256:416260257577718c05135c55958b674000baef9a1c7d9e8f306ec60d71db850f", size = 3501720, upload-time = "2025-10-15T23:18:10.632Z" }, - { url = "https://files.pythonhosted.org/packages/e8/cb/2da4cc83f5edb9c3257d09e1e7ab7b23f049c7962cae8d842bbef0a9cec9/cryptography-46.0.3-cp38-abi3-win_arm64.whl", hash = "sha256:d89c3468de4cdc4f08a57e214384d0471911a3830fcdaf7a8cc587e42a866372", size = 2918740, upload-time = "2025-10-15T23:18:12.277Z" }, - { url = "https://files.pythonhosted.org/packages/06/8a/e60e46adab4362a682cf142c7dcb5bf79b782ab2199b0dcb81f55970807f/cryptography-46.0.3-pp311-pypy311_pp73-macosx_10_9_x86_64.whl", hash = "sha256:7ce938a99998ed3c8aa7e7272dca1a610401ede816d36d0693907d863b10d9ea", size = 3698132, upload-time = "2025-10-15T23:18:17.056Z" }, - { url = "https://files.pythonhosted.org/packages/da/38/f59940ec4ee91e93d3311f7532671a5cef5570eb04a144bf203b58552d11/cryptography-46.0.3-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:191bb60a7be5e6f54e30ba16fdfae78ad3a342a0599eb4193ba88e3f3d6e185b", size = 4243992, upload-time = "2025-10-15T23:18:18.695Z" }, - { url = "https://files.pythonhosted.org/packages/b0/0c/35b3d92ddebfdfda76bb485738306545817253d0a3ded0bfe80ef8e67aa5/cryptography-46.0.3-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:c70cc23f12726be8f8bc72e41d5065d77e4515efae3690326764ea1b07845cfb", size = 4409944, upload-time = "2025-10-15T23:18:20.597Z" }, - { url = "https://files.pythonhosted.org/packages/99/55/181022996c4063fc0e7666a47049a1ca705abb9c8a13830f074edb347495/cryptography-46.0.3-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:9394673a9f4de09e28b5356e7fff97d778f8abad85c9d5ac4a4b7e25a0de7717", size = 4242957, upload-time = "2025-10-15T23:18:22.18Z" }, - { url = "https://files.pythonhosted.org/packages/ba/af/72cd6ef29f9c5f731251acadaeb821559fe25f10852f44a63374c9ca08c1/cryptography-46.0.3-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:94cd0549accc38d1494e1f8de71eca837d0509d0d44bf11d158524b0e12cebf9", size = 4409447, upload-time = "2025-10-15T23:18:24.209Z" }, - { url = "https://files.pythonhosted.org/packages/0d/c3/e90f4a4feae6410f914f8ebac129b9ae7a8c92eb60a638012dde42030a9d/cryptography-46.0.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:6b5063083824e5509fdba180721d55909ffacccc8adbec85268b48439423d78c", size = 3438528, upload-time = "2025-10-15T23:18:26.227Z" }, -] - [[package]] name = "cssselect" version = "1.3.0" @@ -662,19 +588,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/18/79/1b8fa1bb3568781e84c9200f951c735f3f157429f44be0495da55894d620/filetype-1.2.0-py2.py3-none-any.whl", hash = "sha256:7ce71b6880181241cf7ac8697a2f1eb6a8bd9b429f7ad6d27b8db9ba5f1c2d25", size = 19970, upload-time = "2022-11-02T17:34:01.425Z" }, ] -[[package]] -name = "furl" -version = "2.1.4" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "orderedmultidict" }, - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/53/e4/203a76fa2ef46cdb0a618295cc115220cbb874229d4d8721068335eb87f0/furl-2.1.4.tar.gz", hash = "sha256:877657501266c929269739fb5f5980534a41abd6bbabcb367c136d1d3b2a6015", size = 57526, upload-time = "2025-03-09T05:36:21.175Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/61/8c/dce3b1b7593858eba995b2dfdb833f872c7f863e3da92aab7128a6b11af4/furl-2.1.4-py2.py3-none-any.whl", hash = "sha256:da34d0b34e53ffe2d2e6851a7085a05d96922b5b578620a37377ff1dbeeb11c8", size = 27550, upload-time = "2025-03-09T05:36:19.928Z" }, -] - [[package]] name = "furo" version = "2025.12.19" @@ -1008,20 +921,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b1/dd/ead9d8ea85bf202d90cc513b533f9c363121c7792674f78e0d8a854b63b4/jupyterlab_pygments-0.3.0-py3-none-any.whl", hash = "sha256:841a89020971da1d8693f1a99997aefc5dc424bb1b251fd6322462a1b8842780", size = 15884, upload-time = "2023-11-23T09:26:34.325Z" }, ] -[[package]] -name = "jwskate" -version = "0.12.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "binapy" }, - { name = "cryptography" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/f5/45/85a545c824439ba37aa61bed6c10ddf89dc51915d28b937931de8cca2eef/jwskate-0.12.2.tar.gz", hash = "sha256:7c38b036b633d689b31c89b358823dbc8c439e4c74596cb1fceb0dfe4cf9efce", size = 128629, upload-time = "2025-04-02T10:06:46.539Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/80/21/4252ccb378deb49f9e38635731b30d43aee03c2238d2fe0100011242af62/jwskate-0.12.2-py3-none-any.whl", hash = "sha256:fd10271bd651db8da7df256f7b5bcface84bf165a203b991ae05fb728f3d3aef", size = 88775, upload-time = "2025-04-02T10:06:45.021Z" }, -] - [[package]] name = "lap" version = "0.5.12" @@ -1729,18 +1628,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5b/c7/b801bf98514b6ae6475e941ac05c58e6411dd863ea92916bfd6d510b08c1/numpy-2.4.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:4f1b68ff47680c2925f8063402a693ede215f0257f02596b1318ecdfb1d79e33", size = 12492579, upload-time = "2026-01-10T06:44:57.094Z" }, ] -[[package]] -name = "orderedmultidict" -version = "1.0.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "six" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5c/62/61ad51f6c19d495970230a7747147ce7ed3c3a63c2af4ebfdb1f6d738703/orderedmultidict-1.0.2.tar.gz", hash = "sha256:16a7ae8432e02cc987d2d6d5af2df5938258f87c870675c73ee77a0920e6f4a6", size = 13973, upload-time = "2025-11-18T08:00:42.649Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/b2/6c/d8a02ffb24876b5f51fbd781f479fc6525a518553a4196bd0433dae9ff8e/orderedmultidict-1.0.2-py2.py3-none-any.whl", hash = "sha256:ab5044c1dca4226ae4c28524cfc5cc4c939f0b49e978efa46a6ad6468049f79b", size = 11897, upload-time = "2025-11-18T08:00:41.44Z" }, -] - [[package]] name = "packaging" version = "25.0" @@ -1825,6 +1712,7 @@ dependencies = [ { name = "eyconf", extra = ["cli", "pydantic"] }, { name = "levenshtein" }, { name = "platformdirs" }, + { name = "pydantic" }, { name = "requests" }, { name = "typer" }, { name = "typing-extensions" }, @@ -1834,7 +1722,6 @@ dependencies = [ allservices = [ { name = "lxml" }, { name = "nest-asyncio" }, - { name = "requests-oauth2client" }, { name = "sqlalchemy" }, { name = "tinytag" }, ] @@ -1848,12 +1735,6 @@ plex = [ { name = "nest-asyncio" }, { name = "tinytag" }, ] -spotify = [ - { name = "requests-oauth2client" }, -] -tidal = [ - { name = "requests-oauth2client" }, -] traktor = [ { name = "lxml" }, ] @@ -1874,7 +1755,6 @@ dev = [ { name = "pytest-benchmark" }, { name = "pytest-cov" }, { name = "pytest-xdist", extra = ["psutil"] }, - { name = "requests-oauth2client" }, { name = "ruff" }, { name = "sphinx" }, { name = "sphinx-autoapi" }, @@ -1917,7 +1797,6 @@ test = [ ] typed = [ { name = "mypy" }, - { name = "requests-oauth2client" }, { name = "tinytag" }, { name = "types-lxml" }, { name = "types-pyyaml" }, @@ -1934,9 +1813,8 @@ requires-dist = [ { name = "platformdirs", specifier = ">=4.5.1" }, { name = "plistsync", extras = ["local"], marker = "extra == 'plex'" }, { name = "plistsync", extras = ["traktor", "spotify", "tidal", "local", "beets", "plex"], marker = "extra == 'allservices'" }, + { name = "pydantic", specifier = ">=2.0" }, { name = "requests", specifier = ">=2.32.5" }, - { name = "requests-oauth2client", marker = "extra == 'spotify'", specifier = ">=1.8.0" }, - { name = "requests-oauth2client", marker = "extra == 'tidal'", specifier = ">=1.8.0" }, { name = "sqlalchemy", marker = "extra == 'beets'", specifier = ">=2.0.45" }, { name = "tinytag", marker = "extra == 'local'", specifier = ">=2.2.0" }, { name = "typer", specifier = ">=0.21.1" }, @@ -1960,7 +1838,6 @@ dev = [ { name = "pytest-benchmark", specifier = ">=5.1.0" }, { name = "pytest-cov", specifier = ">=7.0.0" }, { name = "pytest-xdist", extras = ["psutil"], specifier = ">=3.8.0" }, - { name = "requests-oauth2client", specifier = ">=1.8.0" }, { name = "ruff", specifier = ">=0.14.11" }, { name = "sphinx", specifier = ">=8.2.3" }, { name = "sphinx-autoapi", specifier = ">=3.6.1" }, @@ -2003,7 +1880,6 @@ test = [ ] typed = [ { name = "mypy", specifier = ">=1.19.1" }, - { name = "requests-oauth2client", specifier = ">=1.8.0" }, { name = "tinytag", specifier = ">=2.2.0" }, { name = "types-lxml", specifier = ">=2026.1.1" }, { name = "types-pyyaml", specifier = ">=6.0.12.20260724" }, @@ -2557,22 +2433,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/1e/db/4254e3eabe8020b458f1a747140d32277ec7a271daf1d235b70dc0b4e6e3/requests-2.32.5-py3-none-any.whl", hash = "sha256:2462f94637a34fd532264295e186976db0f5d453d1cdd31473c85a6a161affb6", size = 64738, upload-time = "2025-08-18T20:46:00.542Z" }, ] -[[package]] -name = "requests-oauth2client" -version = "1.8.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "attrs" }, - { name = "binapy" }, - { name = "furl" }, - { name = "jwskate" }, - { name = "requests" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/13/7f/b3084153443ed7b568854b6a6b0d66971b8f25354ec73f2694a85823d8a2/requests_oauth2client-1.8.0.tar.gz", hash = "sha256:a550f18c41bae5082548257b8a4cd453da6315552f451fc81352c2aaa79b89b3", size = 131048, upload-time = "2025-12-22T20:22:03.335Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/69/6d/18a6d7354924d5b9b71cbb6c247784c9eccf0f9f76c83c4e44bc891157bc/requests_oauth2client-1.8.0-py3-none-any.whl", hash = "sha256:afff45c7dcabe3d7762bcc3e25c002b3645cee6f3ce99776dff54c1f6048b83d", size = 85061, upload-time = "2025-12-22T20:22:01.828Z" }, -] - [[package]] name = "rich" version = "14.2.0"