Skip to content

Commit 24459a4

Browse files
authored
✨ Revoke logins on logout and stop reading tokens locally (#381)
1 parent 9c902cb commit 24459a4

17 files changed

Lines changed: 453 additions & 211 deletions

File tree

‎src/fastapi_cloud_cli/api/_errors.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def _handle_unauthorized(auth_mode: AuthMode) -> str:
2727
if auth_mode == "user":
2828
delete_auth_config()
2929

30-
message += "Use `fastapi login` to generate a new token."
30+
message += "Run `fastapi cloud login` to generate a new token."
3131
else:
3232
message += "Make sure to use a valid token."
3333

‎src/fastapi_cloud_cli/api/client.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,14 @@ def restart_custom_domain_setup(
211211

212212
return CustomDomain.model_validate(response.json())
213213

214+
def logout(self) -> None:
215+
"""Revoke the token this client sends."""
216+
# Short, so logging out doesn't hang when FastAPI Cloud is slow.
217+
response = self.post("/logout", timeout=5)
218+
# FastAPI Cloud without /logout can't revoke tokens, so there's nothing to do.
219+
if response.status_code != 404:
220+
response.raise_for_status()
221+
214222
@attempts(STREAM_LOGS_MAX_RETRIES, STREAM_LOGS_TIMEOUT)
215223
def stream_build_logs(
216224
self, deployment_id: str, *, follow: bool = True

‎src/fastapi_cloud_cli/commands/_auth.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ def invoke(self, ctx: Context) -> Any:
3030
if not identity.is_logged_in():
3131
toolkit.fail(
3232
"not_logged_in",
33-
"No credentials found.",
33+
"Your session has expired."
34+
if identity.is_user_token_expired()
35+
else "No credentials found.",
3436
hint="Run `fastapi cloud login`.",
3537
)
3638

‎src/fastapi_cloud_cli/commands/_flow.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class AuthorizationData(BaseModel):
2626

2727
class TokenResponse(BaseModel):
2828
access_token: str
29+
expires_in: int | None = None
2930

3031

3132
class LoginOutput(BaseModel):
@@ -85,7 +86,7 @@ def fetch_access_token(
8586
device_code: str,
8687
interval: int,
8788
timeout: int = DEFAULT_LOGIN_TIMEOUT_SECONDS,
88-
) -> str:
89+
) -> TokenResponse:
8990
settings = Settings.get()
9091
start = time.monotonic()
9192

@@ -130,7 +131,7 @@ def fetch_access_token(
130131
response_data = TokenResponse.model_validate_json(response.text)
131132
logger.debug("Access token received successfully.")
132133

133-
return response_data.access_token
134+
return response_data
134135

135136

136137
def complete_device_login(
@@ -145,7 +146,7 @@ def complete_device_login(
145146
) -> LoginOutput:
146147
try:
147148
with client.handle_http_errors(progress, toolkit=toolkit):
148-
access_token = fetch_access_token(client, device_code, interval, timeout)
149+
token = fetch_access_token(client, device_code, interval, timeout)
149150
except LoginDeniedError:
150151
toolkit.fail(
151152
"permission_denied",
@@ -167,6 +168,12 @@ def complete_device_login(
167168
hint=cancel_hint,
168169
)
169170

170-
write_auth_config(AuthConfig(access_token=access_token))
171+
expires_at = None
172+
if token.expires_in is not None:
173+
expires_at = int(time.time()) + token.expires_in
174+
175+
write_auth_config(
176+
AuthConfig(access_token=token.access_token, expires_at=expires_at)
177+
)
171178

172179
return LoginOutput(authenticated=True, auth_mode="user")

‎src/fastapi_cloud_cli/commands/apps/link.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,9 @@ def link_app(
219219

220220
toolkit.fail(
221221
"not_logged_in",
222-
"No credentials found.",
222+
"Your session has expired."
223+
if identity.is_user_token_expired()
224+
else "No credentials found.",
223225
hint="Run `fastapi cloud login`.",
224226
)
225227

‎src/fastapi_cloud_cli/commands/deploy/command.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,9 @@ def deploy(
217217
if json_output:
218218
toolkit.fail(
219219
"not_logged_in",
220-
"No credentials found.",
220+
"Your session has expired."
221+
if identity.is_user_token_expired()
222+
else "No credentials found.",
221223
hint="Run `fastapi cloud login` or set FASTAPI_CLOUD_TOKEN.",
222224
)
223225

@@ -229,7 +231,7 @@ def deploy(
229231
)
230232
toolkit.print_line()
231233

232-
if identity.user_token and identity.is_user_token_expired():
234+
if identity.is_user_token_expired():
233235
toolkit.print("Your session has expired. Please log in again.")
234236
else:
235237
toolkit.print("You need to be logged in to deploy to FastAPI Cloud.")

‎src/fastapi_cloud_cli/commands/login.py‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -103,16 +103,6 @@ def login(
103103
toolkit.print_title("Login to FastAPI Cloud", tag="FastAPI Cloud", emoji="🔐")
104104
toolkit.print_line()
105105

106-
if identity.is_logged_in():
107-
toolkit.print("You are already logged in.")
108-
toolkit.print_line()
109-
toolkit.print(
110-
"Run [bold]fastapi cloud logout[/bold] first if you want to switch accounts.",
111-
emoji="💡",
112-
)
113-
114-
return
115-
116106
if identity.has_deploy_token():
117107
toolkit.print(
118108
"You have [bold blue]FASTAPI_CLOUD_TOKEN[/] environment variable set.\n"
Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,67 @@
1-
from typing import Any
1+
import logging
2+
from typing import Annotated, Any
23

3-
from pydantic import BaseModel
4+
import httpx
5+
from pydantic import BaseModel, Field
46
from rich_toolkit import RichToolkit
57

68
from fastapi_cloud_cli._app import cloud_app
7-
from fastapi_cloud_cli.utils.auth import delete_auth_config
9+
from fastapi_cloud_cli.api import APIClient
10+
from fastapi_cloud_cli.utils.auth import Identity, delete_auth_config
811
from fastapi_cloud_cli.utils.cli import get_rich_toolkit
912
from fastapi_cloud_cli.utils.execution import JsonOutputOption
1013

14+
logger = logging.getLogger(__name__)
15+
1116

1217
class LogoutOutput(BaseModel):
1318
logged_out: bool
19+
revoke_failed: Annotated[bool, Field(exclude=True)] = False
20+
21+
22+
REVOKE_FAILED_MESSAGE = (
23+
"Couldn't sign out on FastAPI Cloud, so this login stays valid until it expires."
24+
)
1425

1526

1627
def _render_logout_output(data: LogoutOutput, toolkit: RichToolkit) -> None:
1728
toolkit.print_title("FastAPI Cloud")
1829
toolkit.print_line()
1930
toolkit.print("You are now logged out!", emoji="👋")
2031

32+
if data.revoke_failed:
33+
toolkit.print_line()
34+
toolkit.print(REVOKE_FAILED_MESSAGE, emoji="⚠️")
35+
2136

2237
@cloud_app.command()
2338
def logout(json_output: JsonOutputOption = False) -> Any:
2439
"""
2540
Logout from FastAPI Cloud.
2641
"""
2742
with get_rich_toolkit(json_output=json_output) as toolkit:
43+
revoke_failed = False
44+
45+
if Identity().user_token:
46+
# Revoke the token on a best-effort basis: logging out must still
47+
# work when FastAPI Cloud can't be reached.
48+
try:
49+
with APIClient() as client:
50+
client.logout()
51+
except httpx.HTTPError as e:
52+
logger.debug("Could not revoke the token: %s", e)
53+
revoke_failed = True
54+
2855
delete_auth_config()
56+
57+
warnings = []
58+
if revoke_failed:
59+
warnings.append(
60+
{"code": "token_not_revoked", "message": REVOKE_FAILED_MESSAGE}
61+
)
62+
2963
toolkit.success(
30-
LogoutOutput(logged_out=True),
64+
LogoutOutput(logged_out=True, revoke_failed=revoke_failed),
65+
warnings=warnings,
3166
render_output=_render_logout_output,
3267
)

‎src/fastapi_cloud_cli/utils/auth.py‎

Lines changed: 11 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
import base64
2-
import binascii
3-
import json
41
import logging
52
import os
63
import time
@@ -17,6 +14,8 @@
1714

1815
class AuthConfig(BaseModel):
1916
access_token: str
17+
# Unix time when FastAPI Cloud expires the token. Older logins didn't save it.
18+
expires_at: int | None = None
2019

2120

2221
def write_auth_config(auth_data: AuthConfig) -> None:
@@ -50,69 +49,11 @@ def read_auth_config() -> AuthConfig | None:
5049
return AuthConfig.model_validate_json(auth_path.read_text(encoding="utf-8"))
5150

5251

53-
def _get_auth_token() -> str | None:
54-
logger.debug("Getting auth token")
55-
auth_data = read_auth_config()
56-
57-
if auth_data is None:
58-
logger.debug("No auth data found")
59-
return None
60-
61-
logger.debug("Auth token retrieved successfully")
62-
return auth_data.access_token
63-
64-
65-
def _is_jwt_expired(token: str) -> bool:
66-
try:
67-
parts = token.split(".")
68-
69-
if len(parts) != 3:
70-
logger.debug("Invalid JWT format: expected 3 parts, got %d", len(parts))
71-
return True
72-
73-
payload = parts[1]
74-
75-
# Add padding if needed (JWT uses base64url encoding without padding)
76-
if padding := len(payload) % 4:
77-
payload += "=" * (4 - padding)
78-
79-
payload = payload.replace("-", "+").replace("_", "/")
80-
decoded_bytes = base64.b64decode(payload)
81-
payload_data = json.loads(decoded_bytes)
82-
83-
exp = payload_data.get("exp")
84-
85-
if exp is None:
86-
logger.debug("No 'exp' claim found in token")
87-
88-
return False
89-
90-
if not isinstance(exp, int): # pragma: no cover
91-
logger.debug("Invalid 'exp' claim: expected int, got %s", type(exp))
92-
93-
return True
94-
95-
current_time = time.time()
96-
97-
is_expired = current_time >= exp
98-
99-
logger.debug(
100-
"Token expiration check: current=%d, exp=%d, expired=%s",
101-
current_time,
102-
exp,
103-
is_expired,
104-
)
105-
106-
return is_expired
107-
except (binascii.Error, json.JSONDecodeError) as e:
108-
logger.debug("Error parsing JWT token: %s", e)
109-
110-
return True
111-
112-
11352
class Identity:
11453
def __init__(self) -> None:
115-
self._user_token = _get_auth_token()
54+
auth_config = read_auth_config()
55+
self._user_token = auth_config.access_token if auth_config else None
56+
self._user_token_expires_at = auth_config.expires_at if auth_config else None
11657
self._deploy_token: str | None = os.environ.get("FASTAPI_CLOUD_TOKEN")
11758

11859
@property
@@ -124,20 +65,22 @@ def deploy_token(self) -> str | None:
12465
return self._deploy_token
12566

12667
def is_user_token_expired(self) -> bool:
127-
if not self._user_token:
128-
return True
68+
# Without a saved expiry, only FastAPI Cloud can tell, with a 401.
69+
if self._user_token_expires_at is None:
70+
return False
12971

130-
return _is_jwt_expired(self._user_token)
72+
return time.time() >= self._user_token_expires_at
13173

13274
def is_logged_in(self) -> bool:
133-
if self._user_token is None:
75+
if not self._user_token:
13476
logger.debug("Login status: False (no token)")
13577
return False
13678

13779
if self.is_user_token_expired():
13880
logger.debug("Login status: False (token expired)")
13981
return False
14082

83+
# A revoked token still gets a 401, which deletes the stored token.
14184
logger.debug("Login status: True")
14285
return True
14386

‎tests/conftest.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from fastapi_cloud_cli.config import Settings
1313

14-
from .utils import create_jwt_token
14+
from .utils import USER_TOKEN
1515

1616

1717
@pytest.fixture(autouse=True)
@@ -67,9 +67,14 @@ def respx_mock(settings: Settings) -> Generator[respx.MockRouter, None, None]:
6767

6868
@pytest.fixture
6969
def logged_in_cli(temp_auth_config: Path) -> Generator[None, None, None]:
70-
valid_token = create_jwt_token({"sub": "test_user_12345"})
70+
temp_auth_config.write_text(f'{{"access_token": "{USER_TOKEN}"}}')
7171

72-
temp_auth_config.write_text(f'{{"access_token": "{valid_token}"}}')
72+
yield
73+
74+
75+
@pytest.fixture
76+
def logged_in_with_expired_token(temp_auth_config: Path) -> Generator[None, None, None]:
77+
temp_auth_config.write_text(f'{{"access_token": "{USER_TOKEN}", "expires_at": 0}}')
7378

7479
yield
7580

0 commit comments

Comments
 (0)