diff --git a/streamrip/client/tidal.py b/streamrip/client/tidal.py index 92455d20..8e466500 100644 --- a/streamrip/client/tidal.py +++ b/streamrip/client/tidal.py @@ -9,7 +9,11 @@ import aiohttp from ..config import Config -from ..exceptions import NonStreamableError +from ..exceptions import ( + AuthenticationError, + MissingCredentialsError, + NonStreamableError, +) from .client import Client from .downloadable import TidalDownloadable @@ -55,7 +59,9 @@ async def login(self): ) c = self.config if not c.access_token: - raise Exception("Access token not found in config.") + raise MissingCredentialsError( + "No Tidal access token in config -- Tidal has not been set up yet." + ) self.token_expiry = float(c.token_expiry) self.refresh_token = c.refresh_token @@ -300,7 +306,13 @@ async def _refresh_access_token(self): resp = await self._api_post(f"{AUTH_URL}/token", data, AUTH) if resp.get("status", 200) != 200: - raise Exception("Refresh failed") + # The refresh token itself has lapsed or been revoked, so there is + # nothing left to refresh from and only a fresh device login will + # help. Typed so the caller can offer that instead of dying with a + # traceback. + raise AuthenticationError( + "Tidal refresh token has expired or been revoked." + ) c = self.config c.access_token = resp["access_token"] diff --git a/streamrip/rip/main.py b/streamrip/rip/main.py index 562773fc..048aecef 100644 --- a/streamrip/rip/main.py +++ b/streamrip/rip/main.py @@ -2,13 +2,16 @@ import json import logging import platform +import sys import aiofiles +from rich.prompt import Confirm from .. import db from ..client import Client, DeezerClient, QobuzClient, SoundcloudClient, TidalClient from ..config import Config from ..console import console +from ..exceptions import AuthenticationError, MissingCredentialsError from ..media import ( Media, Pending, @@ -145,13 +148,42 @@ async def get_logged_in_client(self, source: str): await prompter.prompt_and_login() prompter.save() else: - with console.status(f"[cyan]Logging into {source}", spinner="dots"): - # Log into client using credentials from config - await client.login() + try: + with console.status( + f"[cyan]Logging into {source}", spinner="dots" + ): + # Log into client using credentials from config + await client.login() + except (AuthenticationError, MissingCredentialsError) as e: + # has_creds() only checks that something is *stored*, not + # that it still works. Saved tokens expire, so the usual + # way to discover a lapsed login is a failure here -- which + # used to be a bare traceback, even though the prompter + # that fixes it is already built and sitting right there. + await self._reauthenticate(source, prompter, e) assert client.logged_in return client + async def _reauthenticate(self, source: str, prompter, cause: Exception): + """Offer a fresh login after stored credentials stop working.""" + console.print(f"[yellow]{source.title()} login failed: {cause}") + + # Never block on a prompt nobody is there to answer: rip is run from + # cron and from scripts, where a hidden y/n means hanging forever + # rather than failing. + if not sys.stdin.isatty(): + raise AuthenticationError( + f"{source} needs authorising again. Re-run this from an " + f"interactive terminal and you will be prompted to log in." + ) from cause + + if not Confirm.ask(f"Log into {source} again now?"): + raise cause + + await prompter.prompt_and_login() + prompter.save() + async def resolve(self): """Resolve all currently pending items.""" with console.status("Resolving URLs...", spinner="dots"): diff --git a/tests/test_reauth_prompt.py b/tests/test_reauth_prompt.py new file mode 100644 index 00000000..98038b6e --- /dev/null +++ b/tests/test_reauth_prompt.py @@ -0,0 +1,74 @@ +"""Stored credentials that stop working should offer a fresh login. + +`has_creds()` only checks that something is *stored*, not that it still works, +so an expired token passes that check and the failure surfaces from `login()`. +Before this was handled, that meant a traceback -- even though the prompter +that fixes it was already built. +""" + +from contextlib import ExitStack +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from streamrip.exceptions import AuthenticationError +from streamrip.rip.main import Main + + +def _main_with_expired_token(): + main = Main.__new__(Main) + client = MagicMock() + client.logged_in = False + client.login = AsyncMock( + side_effect=AuthenticationError("Tidal refresh token has expired.") + ) + main.clients = {"tidal": client} + main.config = MagicMock() + + prompter = MagicMock() + prompter.has_creds.return_value = True + prompter.prompt_and_login = AsyncMock( + side_effect=lambda: setattr(client, "logged_in", True) + ) + return main, client, prompter + + +def _patches(prompter, *, isatty: bool, confirm: bool): + stack = ExitStack() + stack.enter_context( + patch("streamrip.rip.main.get_prompter", return_value=prompter) + ) + stack.enter_context(patch("sys.stdin.isatty", return_value=isatty)) + stack.enter_context( + patch("streamrip.rip.main.Confirm.ask", return_value=confirm) + ) + return stack + + +@pytest.mark.asyncio +async def test_prompts_and_recovers_when_user_agrees(): + main, client, prompter = _main_with_expired_token() + with _patches(prompter, isatty=True, confirm=True): + result = await main.get_logged_in_client("tidal") + prompter.prompt_and_login.assert_awaited_once() + prompter.save.assert_called_once() + assert result is client + + +@pytest.mark.asyncio +async def test_propagates_when_user_declines(): + main, _, prompter = _main_with_expired_token() + with _patches(prompter, isatty=True, confirm=False): + with pytest.raises(AuthenticationError, match="refresh token has expired"): + await main.get_logged_in_client("tidal") + prompter.prompt_and_login.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_never_prompts_without_a_terminal(): + """rip runs from cron and from scripts, where a hidden y/n hangs forever.""" + main, _, prompter = _main_with_expired_token() + with _patches(prompter, isatty=False, confirm=True): + with pytest.raises(AuthenticationError, match="interactive terminal"): + await main.get_logged_in_client("tidal") + prompter.prompt_and_login.assert_not_awaited()