diff --git a/src/fastapi_cloud_cli/api/_errors.py b/src/fastapi_cloud_cli/api/_errors.py index 25e67f30..b561bb19 100644 --- a/src/fastapi_cloud_cli/api/_errors.py +++ b/src/fastapi_cloud_cli/api/_errors.py @@ -27,7 +27,7 @@ def _handle_unauthorized(auth_mode: AuthMode) -> str: if auth_mode == "user": delete_auth_config() - message += "Use `fastapi login` to generate a new token." + message += "Run `fastapi cloud login` to generate a new token." else: message += "Make sure to use a valid token." diff --git a/src/fastapi_cloud_cli/api/client.py b/src/fastapi_cloud_cli/api/client.py index 709f845b..9792e3d7 100644 --- a/src/fastapi_cloud_cli/api/client.py +++ b/src/fastapi_cloud_cli/api/client.py @@ -211,6 +211,14 @@ def restart_custom_domain_setup( return CustomDomain.model_validate(response.json()) + def logout(self) -> None: + """Revoke the token this client sends.""" + # Short, so logging out doesn't hang when FastAPI Cloud is slow. + response = self.post("/logout", timeout=5) + # FastAPI Cloud without /logout can't revoke tokens, so there's nothing to do. + if response.status_code != 404: + response.raise_for_status() + @attempts(STREAM_LOGS_MAX_RETRIES, STREAM_LOGS_TIMEOUT) def stream_build_logs( self, deployment_id: str, *, follow: bool = True diff --git a/src/fastapi_cloud_cli/commands/_auth.py b/src/fastapi_cloud_cli/commands/_auth.py index b9a750a5..ff939feb 100644 --- a/src/fastapi_cloud_cli/commands/_auth.py +++ b/src/fastapi_cloud_cli/commands/_auth.py @@ -30,7 +30,9 @@ def invoke(self, ctx: Context) -> Any: if not identity.is_logged_in(): toolkit.fail( "not_logged_in", - "No credentials found.", + "Your session has expired." + if identity.is_user_token_expired() + else "No credentials found.", hint="Run `fastapi cloud login`.", ) diff --git a/src/fastapi_cloud_cli/commands/_flow.py b/src/fastapi_cloud_cli/commands/_flow.py index 1ef28dde..a81fa02e 100644 --- a/src/fastapi_cloud_cli/commands/_flow.py +++ b/src/fastapi_cloud_cli/commands/_flow.py @@ -26,6 +26,7 @@ class AuthorizationData(BaseModel): class TokenResponse(BaseModel): access_token: str + expires_in: int | None = None class LoginOutput(BaseModel): @@ -85,7 +86,7 @@ def fetch_access_token( device_code: str, interval: int, timeout: int = DEFAULT_LOGIN_TIMEOUT_SECONDS, -) -> str: +) -> TokenResponse: settings = Settings.get() start = time.monotonic() @@ -130,7 +131,7 @@ def fetch_access_token( response_data = TokenResponse.model_validate_json(response.text) logger.debug("Access token received successfully.") - return response_data.access_token + return response_data def complete_device_login( @@ -145,7 +146,7 @@ def complete_device_login( ) -> LoginOutput: try: with client.handle_http_errors(progress, toolkit=toolkit): - access_token = fetch_access_token(client, device_code, interval, timeout) + token = fetch_access_token(client, device_code, interval, timeout) except LoginDeniedError: toolkit.fail( "permission_denied", @@ -167,6 +168,12 @@ def complete_device_login( hint=cancel_hint, ) - write_auth_config(AuthConfig(access_token=access_token)) + expires_at = None + if token.expires_in is not None: + expires_at = int(time.time()) + token.expires_in + + write_auth_config( + AuthConfig(access_token=token.access_token, expires_at=expires_at) + ) return LoginOutput(authenticated=True, auth_mode="user") diff --git a/src/fastapi_cloud_cli/commands/apps/link.py b/src/fastapi_cloud_cli/commands/apps/link.py index 5f52ae72..9407c04d 100644 --- a/src/fastapi_cloud_cli/commands/apps/link.py +++ b/src/fastapi_cloud_cli/commands/apps/link.py @@ -219,7 +219,9 @@ def link_app( toolkit.fail( "not_logged_in", - "No credentials found.", + "Your session has expired." + if identity.is_user_token_expired() + else "No credentials found.", hint="Run `fastapi cloud login`.", ) diff --git a/src/fastapi_cloud_cli/commands/deploy/command.py b/src/fastapi_cloud_cli/commands/deploy/command.py index 52a75d36..ca0158af 100644 --- a/src/fastapi_cloud_cli/commands/deploy/command.py +++ b/src/fastapi_cloud_cli/commands/deploy/command.py @@ -217,7 +217,9 @@ def deploy( if json_output: toolkit.fail( "not_logged_in", - "No credentials found.", + "Your session has expired." + if identity.is_user_token_expired() + else "No credentials found.", hint="Run `fastapi cloud login` or set FASTAPI_CLOUD_TOKEN.", ) @@ -229,7 +231,7 @@ def deploy( ) toolkit.print_line() - if identity.user_token and identity.is_user_token_expired(): + if identity.is_user_token_expired(): toolkit.print("Your session has expired. Please log in again.") else: toolkit.print("You need to be logged in to deploy to FastAPI Cloud.") diff --git a/src/fastapi_cloud_cli/commands/login.py b/src/fastapi_cloud_cli/commands/login.py index 9493ef8e..474041b6 100644 --- a/src/fastapi_cloud_cli/commands/login.py +++ b/src/fastapi_cloud_cli/commands/login.py @@ -103,16 +103,6 @@ def login( toolkit.print_title("Login to FastAPI Cloud", tag="FastAPI Cloud", emoji="🔐") toolkit.print_line() - if identity.is_logged_in(): - toolkit.print("You are already logged in.") - toolkit.print_line() - toolkit.print( - "Run [bold]fastapi cloud logout[/bold] first if you want to switch accounts.", - emoji="💡", - ) - - return - if identity.has_deploy_token(): toolkit.print( "You have [bold blue]FASTAPI_CLOUD_TOKEN[/] environment variable set.\n" diff --git a/src/fastapi_cloud_cli/commands/logout.py b/src/fastapi_cloud_cli/commands/logout.py index e6811d08..08317f15 100644 --- a/src/fastapi_cloud_cli/commands/logout.py +++ b/src/fastapi_cloud_cli/commands/logout.py @@ -1,16 +1,27 @@ -from typing import Any +import logging +from typing import Annotated, Any -from pydantic import BaseModel +import httpx +from pydantic import BaseModel, Field from rich_toolkit import RichToolkit from fastapi_cloud_cli._app import cloud_app -from fastapi_cloud_cli.utils.auth import delete_auth_config +from fastapi_cloud_cli.api import APIClient +from fastapi_cloud_cli.utils.auth import Identity, delete_auth_config from fastapi_cloud_cli.utils.cli import get_rich_toolkit from fastapi_cloud_cli.utils.execution import JsonOutputOption +logger = logging.getLogger(__name__) + class LogoutOutput(BaseModel): logged_out: bool + revoke_failed: Annotated[bool, Field(exclude=True)] = False + + +REVOKE_FAILED_MESSAGE = ( + "Couldn't sign out on FastAPI Cloud, so this login stays valid until it expires." +) def _render_logout_output(data: LogoutOutput, toolkit: RichToolkit) -> None: @@ -18,6 +29,10 @@ def _render_logout_output(data: LogoutOutput, toolkit: RichToolkit) -> None: toolkit.print_line() toolkit.print("You are now logged out!", emoji="👋") + if data.revoke_failed: + toolkit.print_line() + toolkit.print(REVOKE_FAILED_MESSAGE, emoji="⚠️") + @cloud_app.command() def logout(json_output: JsonOutputOption = False) -> Any: @@ -25,8 +40,28 @@ def logout(json_output: JsonOutputOption = False) -> Any: Logout from FastAPI Cloud. """ with get_rich_toolkit(json_output=json_output) as toolkit: + revoke_failed = False + + if Identity().user_token: + # Revoke the token on a best-effort basis: logging out must still + # work when FastAPI Cloud can't be reached. + try: + with APIClient() as client: + client.logout() + except httpx.HTTPError as e: + logger.debug("Could not revoke the token: %s", e) + revoke_failed = True + delete_auth_config() + + warnings = [] + if revoke_failed: + warnings.append( + {"code": "token_not_revoked", "message": REVOKE_FAILED_MESSAGE} + ) + toolkit.success( - LogoutOutput(logged_out=True), + LogoutOutput(logged_out=True, revoke_failed=revoke_failed), + warnings=warnings, render_output=_render_logout_output, ) diff --git a/src/fastapi_cloud_cli/utils/auth.py b/src/fastapi_cloud_cli/utils/auth.py index 86527363..f5b74419 100644 --- a/src/fastapi_cloud_cli/utils/auth.py +++ b/src/fastapi_cloud_cli/utils/auth.py @@ -1,6 +1,3 @@ -import base64 -import binascii -import json import logging import os import time @@ -17,6 +14,8 @@ class AuthConfig(BaseModel): access_token: str + # Unix time when FastAPI Cloud expires the token. Older logins didn't save it. + expires_at: int | None = None def write_auth_config(auth_data: AuthConfig) -> None: @@ -50,69 +49,11 @@ def read_auth_config() -> AuthConfig | None: return AuthConfig.model_validate_json(auth_path.read_text(encoding="utf-8")) -def _get_auth_token() -> str | None: - logger.debug("Getting auth token") - auth_data = read_auth_config() - - if auth_data is None: - logger.debug("No auth data found") - return None - - logger.debug("Auth token retrieved successfully") - return auth_data.access_token - - -def _is_jwt_expired(token: str) -> bool: - try: - parts = token.split(".") - - if len(parts) != 3: - logger.debug("Invalid JWT format: expected 3 parts, got %d", len(parts)) - return True - - payload = parts[1] - - # Add padding if needed (JWT uses base64url encoding without padding) - if padding := len(payload) % 4: - payload += "=" * (4 - padding) - - payload = payload.replace("-", "+").replace("_", "/") - decoded_bytes = base64.b64decode(payload) - payload_data = json.loads(decoded_bytes) - - exp = payload_data.get("exp") - - if exp is None: - logger.debug("No 'exp' claim found in token") - - return False - - if not isinstance(exp, int): # pragma: no cover - logger.debug("Invalid 'exp' claim: expected int, got %s", type(exp)) - - return True - - current_time = time.time() - - is_expired = current_time >= exp - - logger.debug( - "Token expiration check: current=%d, exp=%d, expired=%s", - current_time, - exp, - is_expired, - ) - - return is_expired - except (binascii.Error, json.JSONDecodeError) as e: - logger.debug("Error parsing JWT token: %s", e) - - return True - - class Identity: def __init__(self) -> None: - self._user_token = _get_auth_token() + auth_config = read_auth_config() + self._user_token = auth_config.access_token if auth_config else None + self._user_token_expires_at = auth_config.expires_at if auth_config else None self._deploy_token: str | None = os.environ.get("FASTAPI_CLOUD_TOKEN") @property @@ -124,13 +65,14 @@ def deploy_token(self) -> str | None: return self._deploy_token def is_user_token_expired(self) -> bool: - if not self._user_token: - return True + # Without a saved expiry, only FastAPI Cloud can tell, with a 401. + if self._user_token_expires_at is None: + return False - return _is_jwt_expired(self._user_token) + return time.time() >= self._user_token_expires_at def is_logged_in(self) -> bool: - if self._user_token is None: + if not self._user_token: logger.debug("Login status: False (no token)") return False @@ -138,6 +80,7 @@ def is_logged_in(self) -> bool: logger.debug("Login status: False (token expired)") return False + # A revoked token still gets a 401, which deletes the stored token. logger.debug("Login status: True") return True diff --git a/tests/conftest.py b/tests/conftest.py index 0167bbe6..4089e40e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,7 +11,7 @@ from fastapi_cloud_cli.config import Settings -from .utils import create_jwt_token +from .utils import USER_TOKEN @pytest.fixture(autouse=True) @@ -67,9 +67,14 @@ def respx_mock(settings: Settings) -> Generator[respx.MockRouter, None, None]: @pytest.fixture def logged_in_cli(temp_auth_config: Path) -> Generator[None, None, None]: - valid_token = create_jwt_token({"sub": "test_user_12345"}) + temp_auth_config.write_text(f'{{"access_token": "{USER_TOKEN}"}}') - temp_auth_config.write_text(f'{{"access_token": "{valid_token}"}}') + yield + + +@pytest.fixture +def logged_in_with_expired_token(temp_auth_config: Path) -> Generator[None, None, None]: + temp_auth_config.write_text(f'{{"access_token": "{USER_TOKEN}", "expires_at": 0}}') yield diff --git a/tests/test_auth.py b/tests/test_auth.py index de8fce73..ac1da039 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -1,112 +1,59 @@ -import base64 import time from pathlib import Path -import pytest +from fastapi_cloud_cli.utils.auth import AuthConfig, Identity, write_auth_config -from fastapi_cloud_cli.utils.auth import ( - AuthConfig, - Identity, - _is_jwt_expired, - write_auth_config, -) +from .utils import USER_TOKEN, create_jwt_token -from .utils import create_jwt_token - -def test_is_jwt_expired_with_valid_token() -> None: - future_exp = int(time.time()) + 3600 - - token = create_jwt_token({"exp": future_exp, "sub": "test_user"}) - - assert not _is_jwt_expired(token) - - -def test_is_jwt_expired_with_expired_token() -> None: - past_exp = int(time.time()) - 3600 - token = create_jwt_token({"exp": past_exp, "sub": "test_user"}) - - assert _is_jwt_expired(token) - - -def test_is_jwt_expired_with_no_exp_claim() -> None: - token = create_jwt_token({"sub": "test_user"}) - - # Tokens without exp claim should be considered valid - assert not _is_jwt_expired(token) - - -@pytest.mark.parametrize( - "token", - [ - "not.a.valid.jwt.token", - "only.two", - "invalid", - "", - "...", - ], -) -def test_is_jwt_expired_with_malformed_token(token: str) -> None: - assert _is_jwt_expired(token) - - -def test_is_jwt_expired_with_invalid_base64() -> None: - token = "header.!!!invalid_signature!!!.signature" - assert _is_jwt_expired(token) - - -def test_is_jwt_expired_with_invalid_json() -> None: - header_encoded = base64.urlsafe_b64encode(b'{"alg":"HS256"}').decode().rstrip("=") - payload_encoded = base64.urlsafe_b64encode(b"{invalid json}").decode().rstrip("=") - signature = base64.urlsafe_b64encode(b"signature").decode().rstrip("=") - token = f"{header_encoded}.{payload_encoded}.{signature}" - - assert _is_jwt_expired(token) +def test_is_logged_in_with_no_token(temp_auth_config: Path) -> None: + assert not temp_auth_config.exists() + assert not Identity().is_logged_in() -def test_is_jwt_expired_edge_case_exact_expiration() -> None: - current_time = int(time.time()) - token = create_jwt_token({"exp": current_time, "sub": "test_user"}) +def test_is_logged_in_with_token(temp_auth_config: Path) -> None: + write_auth_config(AuthConfig(access_token=USER_TOKEN)) - assert _is_jwt_expired(token) + assert Identity().is_logged_in() -def test_is_jwt_expired_edge_case_one_second_before() -> None: - current_time = int(time.time()) - token = create_jwt_token({"exp": current_time + 1, "sub": "test_user"}) +def test_is_logged_in_before_token_expires(temp_auth_config: Path) -> None: + write_auth_config( + AuthConfig(access_token=USER_TOKEN, expires_at=int(time.time()) + 3600) + ) - assert not _is_jwt_expired(token) + identity = Identity() + assert identity.is_logged_in() + assert not identity.is_user_token_expired() -def test_is_user_token_expired_with_no_token(temp_auth_config: Path) -> None: - assert not temp_auth_config.exists() - assert Identity().is_user_token_expired() +def test_is_logged_in_with_expired_token(temp_auth_config: Path) -> None: + write_auth_config( + AuthConfig(access_token=USER_TOKEN, expires_at=int(time.time()) - 3600) + ) -def test_is_logged_in_with_no_token(temp_auth_config: Path) -> None: - assert not temp_auth_config.exists() - assert not Identity().is_logged_in() - - -def test_is_logged_in_with_valid_token(temp_auth_config: Path) -> None: - future_exp = int(time.time()) + 3600 - token = create_jwt_token({"exp": future_exp, "sub": "test_user"}) - - write_auth_config(AuthConfig(access_token=token)) + identity = Identity() - assert Identity().is_logged_in() + assert not identity.is_logged_in() + assert identity.is_user_token_expired() -def test_is_logged_in_with_expired_token(temp_auth_config: Path) -> None: +def test_token_without_saved_expiry_is_left_to_the_server( + temp_auth_config: Path, +) -> None: past_exp = int(time.time()) - 3600 token = create_jwt_token({"exp": past_exp, "sub": "test_user"}) write_auth_config(AuthConfig(access_token=token)) - assert not Identity().is_logged_in() + identity = Identity() + + assert identity.is_logged_in() + assert not identity.is_user_token_expired() -def test_is_logged_in_with_malformed_token(temp_auth_config: Path) -> None: - write_auth_config(AuthConfig(access_token="not.a.valid.token")) +def test_is_logged_in_with_empty_token(temp_auth_config: Path) -> None: + write_auth_config(AuthConfig(access_token="")) assert not Identity().is_logged_in() diff --git a/tests/test_cli_deploy.py b/tests/test_cli_deploy.py index c8d10f7e..8409b239 100644 --- a/tests/test_cli_deploy.py +++ b/tests/test_cli_deploy.py @@ -29,11 +29,11 @@ from fastapi_cloud_cli.utils.cli import get_rich_toolkit from tests.conftest import ConfiguredApp from tests.utils import ( + USER_TOKEN, Keys, SnapshotCliRunner, build_logs_response, changing_dir, - create_jwt_token, ) runner = CliRunner() @@ -113,7 +113,8 @@ def test_starts_login_when_not_logged_in( settings: Settings, ) -> None: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -177,8 +178,7 @@ def test_cancels_deploy_when_user_declines_login( def test_shows_login_prompt_when_token_is_expired( temp_auth_config: Path, tmp_path: Path ) -> None: - expired_token = create_jwt_token({"sub": "test_user", "exp": 0}) - temp_auth_config.write_text(f'{{"access_token": "{expired_token}"}}') + temp_auth_config.write_text(f'{{"access_token": "{USER_TOKEN}", "expires_at": 0}}') with ( changing_dir(tmp_path), @@ -277,6 +277,22 @@ def test_deploy_json_returns_missing_required_input_without_app_context( } +def test_deploy_json_returns_session_expired( + logged_in_with_expired_token: None, tmp_path: Path +) -> None: + with changing_dir(tmp_path): + result = runner.invoke(app, ["deploy", "--json"]) + + assert result.exit_code == 1 + assert json.loads(result.stdout) == { + "error": { + "code": "not_logged_in", + "message": "Your session has expired.", + "hint": "Run `fastapi cloud login` or set FASTAPI_CLOUD_TOKEN.", + } + } + + def test_deploy_json_returns_not_logged_in_without_prompt( logged_out_cli: None, tmp_path: Path ) -> None: diff --git a/tests/test_cli_link.py b/tests/test_cli_link.py index 5d54caeb..6751f176 100644 --- a/tests/test_cli_link.py +++ b/tests/test_cli_link.py @@ -29,6 +29,22 @@ def test_link_json_requires_app_id(logged_in_cli: None) -> None: assert result.stderr == "" +def test_link_json_returns_session_expired( + logged_in_with_expired_token: None, +) -> None: + result = runner.invoke(app, ["link", "--json"]) + + assert result.exit_code == 1 + assert json.loads(result.stdout) == { + "error": { + "code": "not_logged_in", + "message": "Your session has expired.", + "hint": "Run `fastapi cloud login`.", + } + } + assert result.stderr == "" + + def test_link_json_returns_not_logged_in_when_logged_out(logged_out_cli: None) -> None: result = runner.invoke(app, ["link", "--json"]) diff --git a/tests/test_cli_login.py b/tests/test_cli_login.py index 33114128..1e0d6bc1 100644 --- a/tests/test_cli_login.py +++ b/tests/test_cli_login.py @@ -1,10 +1,12 @@ import json +from datetime import datetime, timezone from pathlib import Path from unittest.mock import patch import httpx import pytest import respx +import time_machine from httpx import Response from inline_snapshot import snapshot from typer.testing import CliRunner @@ -14,6 +16,7 @@ from tests.utils import SnapshotCliRunner runner = CliRunner() +snapshot_runner = SnapshotCliRunner() assets_path = Path(__file__).parent / "assets" @@ -24,7 +27,8 @@ def test_shows_a_message_if_something_is_wrong( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock(return_value=Response(500)) result = runner.invoke(app, ["login"]) @@ -44,7 +48,8 @@ def test_full_login( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -79,8 +84,59 @@ def test_full_login( assert "Now you are logged in!" in result.output # Verify auth file was created with correct content - assert temp_auth_config.exists() - assert '"access_token":"test_token_1234"' in temp_auth_config.read_text() + assert json.loads(temp_auth_config.read_text()) == { + "access_token": "test_token_1234", + "expires_at": None, + } + + +@pytest.mark.respx +@time_machine.travel(datetime(2026, 11, 2, 12, tzinfo=timezone.utc), tick=False) +def test_login_saves_token_expiry( + respx_mock: respx.MockRouter, temp_auth_config: Path, settings: Settings +) -> None: + respx_mock.post( + "/login/device/authorization", + data={"client_id": settings.client_id}, + ).mock( + return_value=Response( + 200, + json={ + "verification_uri_complete": "http://test.com/device?code=query-code", + "verification_uri": "http://test.com", + "user_code": "manual-code", + "device_code": "5678", + }, + ) + ) + respx_mock.post( + "/login/device/token", + data={ + "device_code": "5678", + "client_id": settings.client_id, + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + }, + ).mock( + return_value=Response( + 200, + json={ + "access_token": "test_token_1234", + "token_type": "bearer", + "expires_in": 691190, + }, + ) + ) + + with patch("fastapi_cloud_cli.commands.login.typer.launch"): + result = runner.invoke(app, ["login"]) + + assert result.exit_code == 0 + + expires_at = datetime(2026, 11, 10, 11, 59, 50, tzinfo=timezone.utc) + assert json.loads(temp_auth_config.read_text()) == { + "access_token": "test_token_1234", + "expires_at": int(expires_at.timestamp()), + } @pytest.mark.respx @@ -89,7 +145,8 @@ def test_cloud_auth_login_alias_uses_interactive_login( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -129,7 +186,8 @@ def test_cloud_login_json_returns_authorization_data( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -166,7 +224,8 @@ def test_top_level_login_json_returns_authorization_data( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -210,7 +269,8 @@ def test_auth_login_as_json_returns_authorization_data( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -292,7 +352,8 @@ def test_full_login_with_no_open_shows_manual_authorization_details( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -561,7 +622,8 @@ def test_full_login_with_deploy_token_set( ) -> None: with patch("fastapi_cloud_cli.commands.login.typer.launch") as mock_open: respx_mock.post( - "/login/device/authorization", data={"client_id": settings.client_id} + "/login/device/authorization", + data={"client_id": settings.client_id}, ).mock( return_value=Response( 200, @@ -623,9 +685,9 @@ def test_fetch_access_token_success_immediately( ).mock(return_value=Response(200, json={"access_token": "test_token_success"})) with APIClient() as client: - access_token = fetch_access_token(client, "test_device_code", 5) + token = fetch_access_token(client, "test_device_code", 5) - assert access_token == "test_token_success" + assert token.access_token == "test_token_success" @pytest.mark.respx @@ -653,9 +715,9 @@ def test_fetch_access_token_authorization_pending_then_success( with patch("fastapi_cloud_cli.commands._flow.time.sleep") as mock_sleep: with APIClient() as client: - access_token = fetch_access_token(client, "test_device_code", 3) + token = fetch_access_token(client, "test_device_code", 3) - assert access_token == "test_token_after_pending" + assert token.access_token == "test_token_after_pending" mock_sleep.assert_called_once_with(3) @@ -703,14 +765,48 @@ def test_fetch_access_token_handles_500_error( @pytest.mark.respx -def test_notify_already_logged_in_user( - respx_mock: respx.MockRouter, logged_in_cli: None +def test_login_replaces_stored_token( + respx_mock: respx.MockRouter, + logged_in_cli: None, + temp_auth_config: Path, + settings: Settings, ) -> None: - result = runner.invoke(app, ["login"]) + respx_mock.post( + "/login/device/authorization", + data={"client_id": settings.client_id}, + ).mock( + return_value=Response( + 200, + json={ + "verification_uri_complete": "http://test.com/device?code=query-code", + "verification_uri": "http://test.com", + "user_code": "manual-code", + "device_code": "5678", + }, + ) + ) + respx_mock.post( + "/login/device/token", + data={ + "device_code": "5678", + "client_id": settings.client_id, + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + }, + ).mock(return_value=Response(200, json={"access_token": "new_token"})) + + result = snapshot_runner.invoke(app, ["login", "--no-open"]) assert result.exit_code == 0 - assert "You are already logged in." in result.output - assert ( - "Run fastapi cloud logout first if you want to switch accounts." - in result.output - ) + assert result.output == snapshot("""\ +FastAPI Cloud + +🔐 Login to FastAPI Cloud + + Open http://test.com/device?code=query-code + + Now you are logged in! 🚀\ +""") + assert json.loads(temp_auth_config.read_text()) == { + "access_token": "new_token", + "expires_at": None, + } diff --git a/tests/test_cli_logout.py b/tests/test_cli_logout.py index 605d9014..b69b5c67 100644 --- a/tests/test_cli_logout.py +++ b/tests/test_cli_logout.py @@ -1,27 +1,119 @@ import json from pathlib import Path -from typer.testing import CliRunner +import httpx +import pytest +import respx +from httpx import Response +from inline_snapshot import snapshot from fastapi_cloud_cli.cli import cloud_app as app +from tests.utils import USER_TOKEN, SnapshotCliRunner -runner = CliRunner() +runner = SnapshotCliRunner() -def test_logout_with_existing_auth_file(temp_auth_config: Path) -> None: +@pytest.mark.respx +def test_logout_with_existing_auth_file( + respx_mock: respx.MockRouter, temp_auth_config: Path +) -> None: temp_auth_config.write_text('{"access_token": "test_token"}') + respx_mock.post("/logout", headers={"Authorization": "Bearer test_token"}).mock( + return_value=Response(204) + ) + assert temp_auth_config.exists() result = runner.invoke(app, ["logout"]) + assert result.exit_code == 0 + assert result.output == snapshot("""\ +FastAPI Cloud + +👋 You are now logged out!\ +""") + + assert not temp_auth_config.exists() + + +@pytest.mark.respx +def test_logout_revokes_the_token( + respx_mock: respx.MockRouter, + logged_in_cli: None, + temp_auth_config: Path, +) -> None: + logout_route = respx_mock.post( + "/logout", + headers={"Authorization": f"Bearer {USER_TOKEN}"}, + ).mock(return_value=Response(204)) + + result = runner.invoke(app, ["logout"]) + assert result.exit_code == 0 assert "You are now logged out!" in result.output + assert not temp_auth_config.exists() + + timeout = logout_route.calls.last.request.extensions["timeout"] + assert timeout == httpx.Timeout(5).as_dict() + + +@pytest.mark.respx +@pytest.mark.parametrize( + "logout_response", + [ + Response(401), + Response(500), + httpx.ConnectError("Connection refused"), + httpx.ReadTimeout("Timed out"), + ], + ids=["unauthorized", "server-error", "network-error", "timeout"], +) +def test_logout_warns_when_the_token_is_not_revoked( + respx_mock: respx.MockRouter, + logged_in_cli: None, + temp_auth_config: Path, + logout_response: Response | httpx.HTTPError, +) -> None: + respx_mock.post("/logout").mock(side_effect=[logout_response]) + + result = runner.invoke(app, ["logout"]) + + assert result.exit_code == 0 + assert result.output == snapshot("""\ +FastAPI Cloud + +👋 You are now logged out! + +⚠️ Couldn't sign out on FastAPI Cloud, so this login stays valid until it + expires.\ +""") + assert not temp_auth_config.exists() + + +@pytest.mark.respx +def test_logout_does_not_warn_when_the_server_has_no_logout( + respx_mock: respx.MockRouter, temp_auth_config: Path +) -> None: + temp_auth_config.write_text('{"access_token": "test_token"}') + + respx_mock.post("/logout").mock(return_value=Response(404)) + + result = runner.invoke(app, ["logout"]) + + assert result.exit_code == 0 + assert result.output == snapshot("""\ +FastAPI Cloud +👋 You are now logged out!\ +""") assert not temp_auth_config.exists() -def test_logout_with_no_auth_file(temp_auth_config: Path) -> None: +@pytest.mark.respx +def test_logout_with_no_auth_file( + respx_mock: respx.MockRouter, temp_auth_config: Path +) -> None: assert not temp_auth_config.exists() result = runner.invoke(app, ["logout"]) @@ -30,11 +122,19 @@ def test_logout_with_no_auth_file(temp_auth_config: Path) -> None: assert "You are now logged out!" in result.output assert not temp_auth_config.exists() + assert not respx_mock.calls -def test_logout_json_with_existing_auth_file(temp_auth_config: Path) -> None: +@pytest.mark.respx +def test_logout_json_with_existing_auth_file( + respx_mock: respx.MockRouter, temp_auth_config: Path +) -> None: temp_auth_config.write_text('{"access_token": "test_token"}') + respx_mock.post("/logout", headers={"Authorization": "Bearer test_token"}).mock( + return_value=Response(204) + ) + result = runner.invoke(app, ["logout", "--json"]) assert result.exit_code == 0 @@ -43,7 +143,37 @@ def test_logout_json_with_existing_auth_file(temp_auth_config: Path) -> None: assert not temp_auth_config.exists() -def test_logout_json_with_no_auth_file(temp_auth_config: Path) -> None: +@pytest.mark.respx +def test_logout_json_warns_when_the_token_is_not_revoked( + respx_mock: respx.MockRouter, + logged_in_cli: None, + temp_auth_config: Path, +) -> None: + respx_mock.post("/logout").mock(side_effect=httpx.ConnectError("Refused")) + + result = runner.invoke(app, ["logout", "--json"]) + + assert result.exit_code == 0 + assert json.loads(result.stdout) == { + "data": {"logged_out": True}, + "warnings": [ + { + "code": "token_not_revoked", + "message": ( + "Couldn't sign out on FastAPI Cloud, " + "so this login stays valid until it expires." + ), + } + ], + } + assert result.stderr == "" + assert not temp_auth_config.exists() + + +@pytest.mark.respx +def test_logout_json_with_no_auth_file( + respx_mock: respx.MockRouter, temp_auth_config: Path +) -> None: assert not temp_auth_config.exists() result = runner.invoke(app, ["logout", "--json"]) @@ -52,3 +182,4 @@ def test_logout_json_with_no_auth_file(temp_auth_config: Path) -> None: assert json.loads(result.stdout) == {"data": {"logged_out": True}} assert result.stderr == "" assert not temp_auth_config.exists() + assert not respx_mock.calls diff --git a/tests/test_cli_whoami.py b/tests/test_cli_whoami.py index d664cc37..7eee5c47 100644 --- a/tests/test_cli_whoami.py +++ b/tests/test_cli_whoami.py @@ -4,14 +4,17 @@ import pytest import respx from httpx import ReadTimeout, Response +from inline_snapshot import snapshot from typer.testing import CliRunner from fastapi_cloud_cli.cli import app as root_app from fastapi_cloud_cli.cli import cloud_app as app from fastapi_cloud_cli.commands.whoami import WhoAmIOutput from fastapi_cloud_cli.utils.cli import FastAPIRichToolkit +from tests.utils import USER_TOKEN, SnapshotCliRunner runner = CliRunner() +snapshot_runner = SnapshotCliRunner() assets_path = Path(__file__).parent / "assets" @@ -43,6 +46,27 @@ def test_shows_a_message_when_token_is_invalid( assert "The specified token is not valid" in result.output +@pytest.mark.respx +def test_revoked_token_asks_to_log_in_again( + logged_in_cli: None, + temp_auth_config: Path, + respx_mock: respx.MockRouter, +) -> None: + respx_mock.get( + "/users/me", + headers={"Authorization": f"Bearer {USER_TOKEN}"}, + ).mock(return_value=Response(401)) + + result = snapshot_runner.invoke(app, ["whoami"]) + + assert result.exit_code == 1 + assert result.output == snapshot("""\ +✗ The specified token is not valid. Run `fastapi cloud login` to generate a + new token.\ +""") + assert not temp_auth_config.exists() + + @pytest.mark.respx def test_shows_a_message_when_user_has_no_permissions( logged_in_cli: None, respx_mock: respx.MockRouter @@ -174,7 +198,7 @@ def test_prints_json_error_when_token_is_invalid( "code": "invalid_token", "message": ( "The specified token is not valid. " - "Use `fastapi login` to generate a new token." + "Run `fastapi cloud login` to generate a new token." ), "hint": "Run `fastapi cloud login` to generate a new token.", } @@ -261,6 +285,21 @@ def test_prints_not_logged_in(logged_out_cli: None) -> None: assert "Run `fastapi cloud login`." in result.output +@pytest.mark.respx +def test_prints_session_expired( + logged_in_with_expired_token: None, respx_mock: respx.MockRouter +) -> None: + result = snapshot_runner.invoke(app, ["whoami"]) + + assert result.exit_code == 1 + assert result.output == snapshot("""\ +✗ error: Your session has expired. + + hint: Run `fastapi cloud login`.\ +""") + assert not respx_mock.calls + + def test_prints_not_logged_in_with_deploy_token(logged_out_cli: None) -> None: result = runner.invoke(app, ["whoami"], env={"FASTAPI_CLOUD_TOKEN": "ABC"}) diff --git a/tests/utils.py b/tests/utils.py index 9aef242f..43ed2e0b 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -97,6 +97,9 @@ class Keys: BACKSPACE = "\x7f" +USER_TOKEN = "test_user_token" + + def create_jwt_token(payload: dict[str, Any]) -> str: # Note: This creates a JWT with an invalid signature, but that's OK for our tests # since we only parse the payload, not verify the signature.