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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/fastapi_cloud_cli/api/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."

Expand Down
8 changes: 8 additions & 0 deletions src/fastapi_cloud_cli/api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion src/fastapi_cloud_cli/commands/_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.",
)

Expand Down
15 changes: 11 additions & 4 deletions src/fastapi_cloud_cli/commands/_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class AuthorizationData(BaseModel):

class TokenResponse(BaseModel):
access_token: str
expires_in: int | None = None


class LoginOutput(BaseModel):
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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(
Expand All @@ -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",
Expand All @@ -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")
4 changes: 3 additions & 1 deletion src/fastapi_cloud_cli/commands/apps/link.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.",
)

Expand Down
6 changes: 4 additions & 2 deletions src/fastapi_cloud_cli/commands/deploy/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
)

Expand All @@ -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.")
Expand Down
10 changes: 0 additions & 10 deletions src/fastapi_cloud_cli/commands/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
43 changes: 39 additions & 4 deletions src/fastapi_cloud_cli/commands/logout.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,67 @@
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:
toolkit.print_title("FastAPI Cloud")
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:
"""
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,
)
79 changes: 11 additions & 68 deletions src/fastapi_cloud_cli/utils/auth.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import base64
import binascii
import json
import logging
import os
import time
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -124,20 +65,22 @@ 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

if self.is_user_token_expired():
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

Expand Down
11 changes: 8 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down
Loading
Loading