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
69 changes: 68 additions & 1 deletion dailybot_cli/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from dailybot_cli import __version__
from dailybot_cli.config import (
API_KEY_SOURCE_ENV_JSON,
clear_credentials_if_current,
get_agent_name,
get_api_key,
get_api_key_source,
Expand Down Expand Up @@ -564,6 +565,11 @@ def __init__(
self.api_key: str | None = api_key or get_api_key()
self.timeout: float = timeout
self._agent_auth_mode: str | None = None
# The refusal that ended the stored login session during this client's life
# (a refused refresh), and whether the stored session was removed because of
# it. Both feed the final 401 so the person sees the server's own reason.
self._session_end: APIError | None = None
self._session_cleared: bool = False
# Credential preference on the wire. A key resolved from
# `.dailybot/env.json` expresses per-repo intent, so it must beat the
# global Bearer session on the FIRST attempt — otherwise the Bearer
Expand All @@ -590,6 +596,10 @@ def _headers(self, authenticated: bool = True) -> dict[str, str]:
wins on the first attempt; the 401/403 retry covers the reverse.
"""
headers: dict[str, str] = _base_headers()
if not authenticated:
# This request carries no credential: its answer says nothing about the
# stored session (a refused refresh or login door is not a dead Bearer).
self._agent_auth_mode = None
if authenticated:
if self.api_key and (self._prefer_api_key or not self.token):
headers["X-API-KEY"] = self.api_key
Expand Down Expand Up @@ -837,15 +847,18 @@ def _refresh_session(self) -> bool:
if error.status_code != HTTP_UNAUTHORIZED:
raise
if error.code != SESSION_REVOKED_CODE:
self._end_session_after_refusal(error, refresh)
return False
reread: str | None = get_refresh_token_for(self.api_url)
if not reread or reread == refresh:
self._end_session_after_refusal(error, refresh)
return False
try:
pair = self.refresh_token_pair(reread)
except APIError as second:
if second.status_code != HTTP_UNAUTHORIZED:
raise
self._end_session_after_refusal(second, reread)
return False
finally:
# The refresh door is unauthenticated; the replay is a Bearer request again.
Expand All @@ -868,6 +881,37 @@ def _refresh_session(self) -> bool:
self.token = access
return True

def _end_session_after_refusal(self, error: APIError, refresh: str) -> None:
"""A refused refresh ends the stored session: remember why, and remove it.

Only the pair that was refused is removed (compare-and-clear), so a pair
another CLI process stored meanwhile is kept.
"""
self._session_end = error
if clear_credentials_if_current(self.api_url, refresh=refresh):
Comment on lines +884 to +891

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A refused refresh calls clear_credentials_if_current immediately here, before the caller tries the alternate credential. If an org/API key then answers the same request, the command returns success and never surfaces _session_cleared (nothing reads it on the happy path). Dual-auth setups lose ~/.config/dailybot/credentials.json as a side effect of a working command (including dailybot status --auth, whose docstring still describes a silent key fallback while keeping the Bearer file).

The PR risks section calls this out; it still needs a user-visible signal. Smallest fix: after a successful request, if _session_cleared and the winning mode is api_key, emit one stderr line via print_sign_in_ended (or clear self.token and defer the unlink until a final bearer failure so status/auth paths can report it).

Comment on lines +890 to +891

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After a successful compare-and-clear, self.token still holds the refused access token. A later call on the same client instance will send Bearer first again, pay another 401, and only then fall back. Setting self.token = None (and optionally clearing _session_end bookkeeping consistently) when the file is removed avoids that extra round-trip in long-lived clients and tests.

self._session_cleared = True

def _end_stored_session(self, code: str | None) -> bool:
"""Remove the stored login after a final 401 to its Bearer; ``True`` if removed.

A ``DAILYBOT_CLI_TOKEN`` is the caller's own credential and never touches the
file; a file that no longer holds the refused token is kept. An expired access
token whose pair still holds an unrefused refresh token is not an ended
session (the renewal itself may simply have failed), so it is kept too.
"""
if self._session_cleared:
return True
if os.environ.get("DAILYBOT_CLI_TOKEN"):
return False
if (
code == ACCESS_TOKEN_EXPIRED_CODE
and self._session_end is None
and get_refresh_token_for(self.api_url)
):
return False
self._session_cleared = clear_credentials_if_current(self.api_url, token=self.token)
return self._session_cleared

def _is_final_person_refusal(self, url: str, response: httpx.Response) -> bool:
"""A Tasks door that refused the signed-in person keeps that answer.

Expand Down Expand Up @@ -1017,12 +1061,28 @@ def _handle_response(self, response: httpx.Response) -> dict[str, Any]:
upgrade_url: Any = body.get("upgrade_url")
if isinstance(upgrade_url, str):
extra["upgrade_url"] = upgrade_url
# Some doors send the wait at the top level of a 429 body; keep it
# where the renderers read it.
body_retry_after: Any = body.get("retry_after")
if (
"retry_after" not in extra
and isinstance(body_retry_after, (int, float))
and not isinstance(body_retry_after, bool)
):
extra["retry_after"] = body_retry_after
except Exception:
detail = _fallback_detail(response)
# Only a 401 means the session is unusable. A 403 is an authorization
# verdict (wrong role, wrong plan) whose server detail explains the
# actual cause — overwriting it sends the user into a re-login loop.
if response.status_code == 401 and self._agent_auth_mode == "bearer":
server_detail: str = detail
if self._session_end is not None:
# The refused refresh is the real reason the session ended.
code = self._session_end.code or code
server_detail = self._session_end.detail
extra["server_detail"] = server_detail
extra["session_cleared"] = self._end_stored_session(code)
detail = "Session expired. Run 'dailybot login' to re-authenticate."
retry_after: float | None = None
if response.status_code == 429 or code == AUTH_BACKEND_UNAVAILABLE_CODE:
Expand Down Expand Up @@ -1211,11 +1271,18 @@ def verify_code(
email: str,
code: str,
organization_id: int | None = None,
organization_uuid: str | None = None,
) -> dict[str, Any]:
"""POST /v1/cli/auth/verify-code/"""
"""POST /v1/cli/auth/verify-code/

``organization_uuid`` names the same organization as ``organization_id``;
either (or both) may be sent. Without either the body is unchanged.
"""
payload: dict[str, Any] = {"email": email, "code": code}
if organization_id is not None:
payload["organization_id"] = organization_id
if organization_uuid is not None:
payload["organization_uuid"] = organization_uuid
response: httpx.Response = self._guard_transport(
lambda: httpx.post(
f"{self.api_url}/v1/cli/auth/verify-code/",
Expand Down
Loading
Loading