From f6190ec8289f4ddfcf460cf7f5c11b54fb91532b Mon Sep 17 00:00:00 2001 From: Sergio Florez Date: Tue, 24 Nov 2026 15:58:27 +0000 Subject: [PATCH 1/2] fix(auth): login robustness and clearer sign-in errors ## Summary Email-code sign-in now chooses the organization from the verify step, explains waits the server asks for, and ends a sign-in the server no longer accepts cleanly instead of leaving it on disk. ## Change Log - Choose the organization from verify-code's selection answer (interactive picker, or --org sent as organization_uuid); request-code's organization list is no longer needed - A repeated selection answer stops instead of looping; an --org that is not offered lists the account's organizations and the rerun hint - 429 on either sign-in door prints the server's sentence and the wait (retry_after or Retry-After), exits 6 and never retries - The verification code is not shown while typing and is never printed back in the next-step hints - org_cache.json gets a 10-minute life (saved_at); older files count as expired - A final 401 to the stored login, or a refused refresh, removes the stored sign-in when it still holds the refused credential, keeps the server's reason, and tells the person to run `dailybot login`; DAILYBOT_CLI_TOKEN is never touched - Docs: API reference, architecture, configuration, troubleshooting ## Risks - Works with both request-code answers (organizations listed or not); the new organization_uuid field is optional and sent only with --org or a pick Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 69 ++- dailybot_cli/commands/auth.py | 226 ++++++---- dailybot_cli/commands/public_api_helpers.py | 39 +- dailybot_cli/config.py | 55 ++- dailybot_cli/display.py | 33 ++ docs/API_REFERENCE.md | 12 +- docs/ARCHITECTURE.md | 15 +- docs/CONFIGURATION.md | 2 +- docs/TROUBLESHOOTING.md | 5 + tests/commands_test.py | 66 ++- tests/credentials_refresh_test.py | 6 +- tests/login_robustness_test.py | 448 ++++++++++++++++++++ tests/standalone_org_login_test.py | 13 +- 13 files changed, 842 insertions(+), 147 deletions(-) create mode 100644 tests/login_robustness_test.py diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 535a1860..08298cea 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -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, @@ -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 @@ -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 @@ -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. @@ -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): + 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. @@ -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: @@ -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/", diff --git a/dailybot_cli/commands/auth.py b/dailybot_cli/commands/auth.py index fb06d15f..f9efd129 100644 --- a/dailybot_cli/commands/auth.py +++ b/dailybot_cli/commands/auth.py @@ -2,7 +2,7 @@ import os import re -from typing import Any +from typing import Any, NoReturn import click import questionary @@ -10,7 +10,12 @@ from dailybot_cli import __version__ from dailybot_cli.api_client import AUTH_BACKEND_UNAVAILABLE_CODE, APIError, DailyBotClient from dailybot_cli.commands import _device_login -from dailybot_cli.commands.public_api_helpers import exit_for_api_error +from dailybot_cli.commands.public_api_helpers import ( + ERROR_CODE_MESSAGES, + EXIT_RATE_LIMITED, + exit_for_api_error, + retry_after_seconds, +) from dailybot_cli.config import ( RepoEnvError, clear_credentials, @@ -30,14 +35,21 @@ ) from dailybot_cli.display import ( console, + plain_text, print_cli_auth_deprecation, print_error, print_info, + print_sign_in_refusal, print_success, print_warning, ) CLI_AUTH_DEPRECATED_CODE: str = "cli_auth_deprecated" +HTTP_TOO_MANY_REQUESTS: int = 429 +# Shown in the next-step hints instead of the code itself, so it never reaches +# scrollback, logs or a transcript. +CODE_PLACEHOLDER: str = "CODE" +LOGIN_RATE_LIMITED_FALLBACK: str = "Too many sign-in requests for this email right now." _LEADING_DIGITS: re.Pattern[str] = re.compile(r"^(\d+)") # One notice per `dailybot login` run, even when two doors both carry the field. @@ -171,57 +183,110 @@ def _resolve_org_uuid(organizations: list[dict[str, Any]], org_uuid: str) -> int return None +def _exit_for_login_door_error(error: APIError) -> NoReturn: + """Render a refusal from the email-code doors and exit; never retried here. + + A 429 (too many requests for this email, or a cooldown between codes) shows the + server's sentence and the wait, and exits with the rate-limit status, so it is + never mistaken for a wrong code. Anything else keeps the long-standing output. + """ + if error.status_code == HTTP_TOO_MANY_REQUESTS: + fallback: str = ERROR_CODE_MESSAGES.get(error.code or "") or LOGIN_RATE_LIMITED_FALLBACK + print_sign_in_refusal(error.detail.strip() or fallback, retry_after_seconds(error)) + _notice_deprecation(error.extra) + raise SystemExit(EXIT_RATE_LIMITED) + print_error(error.detail) + _notice_deprecation(error.extra) + raise SystemExit(1) + + +def _print_code_requested(email: str, request_result: dict[str, Any]) -> None: + """Confirm the code request with the server's own sentence when it sends one.""" + detail: Any = request_result.get("detail") + if isinstance(detail, str) and detail.strip(): + print_success(plain_text(detail)) + else: + print_success(f"Verification code sent to {email}") + print_info("Check your inbox (including spam folder).") + + +def _org_rerun_hint(email: str) -> None: + """How to finish a non-interactive sign-in with an organization (code not repeated).""" + print_info(f"Run: dailybot login --email={email} --code={CODE_PLACEHOLDER} --org=ORG_UUID") + + def _verify_and_save( client: DailyBotClient, email: str, code: str, - organization_id: int | None, + organization_id: int | None = None, *, + organization_uuid: str | None = None, allow_interactive_org_pick: bool = False, + picked: bool = False, ) -> None: - """Verify OTP code and save credentials.""" + """Verify the code, choose the organization if the server asks, save credentials. + + The organization always comes from verify-code's ``requires_organization_selection`` + answer (the code is not spent by that answer; the pick is a second call with the + same code). ``picked`` marks that second call, so a repeated selection answer + stops instead of looping. + """ + org_kwargs: dict[str, Any] = {"organization_id": organization_id} + if organization_uuid is not None: + org_kwargs["organization_uuid"] = organization_uuid try: with console.status("Verifying code..."): - result: dict[str, Any] = client.verify_code( - email, code, organization_id=organization_id - ) + result: dict[str, Any] = client.verify_code(email, code, **org_kwargs) except APIError as e: - print_error(e.detail) - _notice_deprecation(e.extra) - raise SystemExit(1) + _exit_for_login_door_error(e) _notice_deprecation(result) - # If the API says org selection is required, auto-select or prompt if result.get("requires_organization_selection"): - organizations: list[dict[str, Any]] = result.get("organizations", []) - if len(organizations) == 1: - # Auto-select the only org and retry - auto_org_id: int = organizations[0]["id"] - print_info(f"Auto-selecting organization: {organizations[0].get('name', 'Unknown')}") - _verify_and_save( - client, - email, - code, - auto_org_id, - allow_interactive_org_pick=allow_interactive_org_pick, - ) - return - elif organizations: - if allow_interactive_org_pick: - selected_org: dict[str, Any] = _prompt_org_selection(organizations) - _verify_and_save( - client, - email, - code, - selected_org["id"], - allow_interactive_org_pick=True, - ) - return + raw_orgs: Any = result.get("organizations") + organizations: list[dict[str, Any]] = ( + [org for org in raw_orgs if isinstance(org, dict)] if isinstance(raw_orgs, list) else [] + ) + if organizations: + # A later `--org` rerun resolves against this list (finite life). + save_org_cache(email, organizations) + choice: dict[str, Any] | None = None + if not organizations: + print_error("Organization selection required but no organizations returned.") + elif picked: + print_error("The organization could not be selected. Pick one from this list:") _print_org_list(organizations) - print_info(f"Run: dailybot login --email={email} --code={code} --org=ORG_UUID") + _org_rerun_hint(email) + elif organization_uuid is not None: + choice = next((o for o in organizations if o.get("uuid") == organization_uuid), None) + if choice is None: + print_error( + f"Organization '{plain_text(organization_uuid)}' is not one of this " + "account's organizations." + ) + _print_org_list(organizations) + _org_rerun_hint(email) + elif len(organizations) == 1: + choice = organizations[0] + print_info(f"Auto-selecting organization: {choice.get('name', 'Unknown')}") + elif allow_interactive_org_pick: + choice = _prompt_org_selection(organizations) else: - print_error("Organization selection required but no organizations returned.") - raise SystemExit(1) + _print_org_list(organizations) + _org_rerun_hint(email) + if choice is None: + raise SystemExit(1) + choice_uuid: Any = choice.get("uuid") + _verify_and_save( + client, + email, + code, + choice.get("id"), + organization_uuid=str(choice_uuid) if choice_uuid else None, + allow_interactive_org_pick=allow_interactive_org_pick, + picked=True, + ) + return token: str | None = result.get("token") if not token: @@ -242,6 +307,7 @@ def _verify_and_save( organization_uuid=org_uuid, api_url=client.api_url, ) + clear_org_cache() # Cache the (non-sensitive) plan tier when the login response exposes it, so # non-allowlisted commands can short-circuit on a free plan. Absent = unknown. plan_tier: Any = (org_raw.get("plan") if isinstance(org_raw, dict) else None) or result.get( @@ -256,43 +322,21 @@ def _do_login(email: str) -> None: """Shared login logic for 'dailybot login' and interactive mode.""" client: DailyBotClient = DailyBotClient() - # Step 1: Request OTP code + # Step 1: Request the code. Its answer is never needed to pick the organization. try: with console.status("Sending verification code..."): request_result: dict[str, Any] = client.request_code(email) except APIError as e: - print_error(e.detail) - _notice_deprecation(e.extra) - raise SystemExit(1) + _exit_for_login_door_error(e) _notice_deprecation(request_result) + _print_code_requested(email, request_result) - print_success(f"Verification code sent to {email}") - print_info("Check your inbox (including spam folder).") - - is_multi_org: bool = request_result.get("is_multi_org", False) - organizations: list[dict[str, Any]] = request_result.get("organizations", []) - - # Step 2: Pick organization before the code prompt so questionary TUI works - # reliably (click.prompt can break questionary if it runs afterward). - organization_id: int | None = None - if is_multi_org and len(organizations) > 1: - selected_org: dict[str, Any] = _prompt_org_selection(organizations) - organization_id = selected_org["id"] - elif len(organizations) == 1: - organization_id = organizations[0].get("id") - - # Step 3: Enter code - code: str = click.prompt("Enter the 6-digit code", type=str) + # Step 2: Enter the code (not shown while typing). + code: str = click.prompt("Enter the 6-digit code", type=str, hide_input=True) code = code.strip() - # Step 4: Verify code and save credentials - _verify_and_save( - client, - email, - code, - organization_id, - allow_interactive_org_pick=True, - ) + # Step 3: Verify; the organization is picked here if the account has several. + _verify_and_save(client, email, code, allow_interactive_org_pick=True) def _request_code_non_interactive(email: str) -> None: @@ -303,48 +347,44 @@ def _request_code_non_interactive(email: str) -> None: with console.status("Sending verification code..."): request_result: dict[str, Any] = client.request_code(email) except APIError as e: - print_error(e.detail) - _notice_deprecation(e.extra) - raise SystemExit(1) + _exit_for_login_door_error(e) _notice_deprecation(request_result) - - print_success(f"Verification code sent to {email}") - print_info("Check your inbox (including spam folder).") + _print_code_requested(email, request_result) is_multi_org: bool = request_result.get("is_multi_org", False) - organizations: list[dict[str, Any]] = request_result.get("organizations", []) + raw_orgs: Any = request_result.get("organizations") + organizations: list[dict[str, Any]] = raw_orgs if isinstance(raw_orgs, list) else [] if is_multi_org and len(organizations) > 1: + # Servers that still list organizations here: keep the familiar output. save_org_cache(email, organizations) _print_org_list(organizations) - print_info(f"Run: dailybot login --email={email} --code=CODE --org=ORG_UUID") - else: - print_info(f"Run: dailybot login --email={email} --code=CODE") + _org_rerun_hint(email) + return + print_info(f"Run: dailybot login --email={email} --code={CODE_PLACEHOLDER}") + if not organizations: + print_info( + "If you belong to several organizations, that step lists them; " + "pick one with --org=ORG_UUID." + ) def _verify_non_interactive(email: str, code: str, org_uuid: str | None) -> None: - """Non-interactive step 2: verify code, handle missing --org for multi-org.""" + """Non-interactive step 2: verify the code, with the organization from ``--org``. + + ``--org`` is sent as ``organization_uuid``. When a recent organization list is + cached (from step 1 or an earlier selection answer) its integer id is sent too, + for servers that only read ``organization_id``. + """ client: DailyBotClient = DailyBotClient() organization_id: int | None = None if org_uuid is not None: - # Resolve UUID → integer ID from the cached org list (saved in step 1). - # This avoids calling request_code or verify_code without org_id, - # which would consume/invalidate the OTP. cached_orgs: list[dict[str, Any]] | None = load_org_cache(email) - if cached_orgs is None: - print_error("No cached organization list found. Run step 1 first:") - print_info(f" dailybot login --email={email}") - raise SystemExit(1) + if cached_orgs: + organization_id = _resolve_org_uuid(cached_orgs, org_uuid) - organization_id = _resolve_org_uuid(cached_orgs, org_uuid) - if organization_id is None: - print_error(f"Organization with uuid '{org_uuid}' not found.") - _print_org_list(cached_orgs) - raise SystemExit(1) - - _verify_and_save(client, email, code.strip(), organization_id) - clear_org_cache() + _verify_and_save(client, email, code.strip(), organization_id, organization_uuid=org_uuid) @click.command() diff --git a/dailybot_cli/commands/public_api_helpers.py b/dailybot_cli/commands/public_api_helpers.py index 80553d40..ea72f4b4 100644 --- a/dailybot_cli/commands/public_api_helpers.py +++ b/dailybot_cli/commands/public_api_helpers.py @@ -23,8 +23,9 @@ load_credentials, mark_org_plan_refreshed, save_org_plan, + text_or_none, ) -from dailybot_cli.display import error_console, print_error, print_info +from dailybot_cli.display import error_console, print_error, print_info, print_sign_in_ended # Plan tiers the server treats as "free" (matched case-insensitively). Kept # tolerant of naming so the client short-circuit activates once the API exposes @@ -133,6 +134,16 @@ "That chat platform is not connected to this organization. Run `dailybot org` " "to see the chat platforms you can use." ), + # --- Email-code sign-in doors --------------------------------------------- + # Fallback copy only: the server's own sentence is shown when it sends one. + "otp_cooldown": ( + "A verification code was requested for this email moments ago. " + "Check your inbox, or wait before asking for another one." + ), + "otp_attempts_exceeded": ( + "Sign-in with a verification code is paused for this email for a while. " + "Wait, then request a new code." + ), # Today a field on the legacy login doors; after the sunset, their error code. "cli_auth_deprecated": ( "Email-code sign-in has been retired. Run `dailybot upgrade`, then sign in with " @@ -988,7 +999,7 @@ def rows_of(data: Any) -> list[dict[str, Any]]: return [] -def _retry_after_seconds(exc: APIError) -> int | None: +def retry_after_seconds(exc: APIError) -> int | None: """Whole seconds to wait after a 429: the body's `extra.retry_after`, else the header's.""" if exc.status_code != 429: return None @@ -1029,7 +1040,7 @@ def exit_for_tasks_error( if is_person_shaped_refusal(exc, door=door) else tasks_write_exit_code(exc) ) - wait: int | None = _retry_after_seconds(exc) + wait: int | None = retry_after_seconds(exc) if json_mode: emit_json( { @@ -1116,7 +1127,7 @@ def agent_error_message(exc: APIError) -> str: message: str = ( _augment_code_message(base, code, exc.extra or {}) if base and code else exc.detail ) - return f"{message}{_throttle_hint(exc, _retry_after_seconds(exc))}" + return f"{message}{_throttle_hint(exc, retry_after_seconds(exc))}" # 401 codes of the device-flow session (DEVICE_FLOW_WIRE §4, CONTRACT_SESSION §7) @@ -1169,6 +1180,14 @@ def exit_for_api_error( else "Session expired. Run: dailybot login" ) exit_code: int = EXIT_NOT_AUTHENTICATED + if not json_mode: + print_error(message) + print_sign_in_ended( + text_or_none(extra.get("server_detail")), + code, + bool(extra.get("session_cleared")), + ) + raise SystemExit(exit_code) elif exc.status_code == 403: message = mapped_message or exc.detail exit_code = EXIT_PERMISSION_DENIED @@ -1209,9 +1228,15 @@ def exit_for_api_error( payload["code"] = code if exc.detail and exc.detail != message: payload["detail"] = exc.detail - retry_after_seconds: float | None = getattr(exc, "retry_after", None) - if exc.status_code == 429 and retry_after_seconds is not None: - payload["retry_after_seconds"] = int(retry_after_seconds) + header_wait: float | None = getattr(exc, "retry_after", None) + if exc.status_code == 429 and header_wait is not None: + payload["retry_after_seconds"] = int(header_wait) + if exc.status_code == 401: + server_detail: str | None = text_or_none(extra.get("server_detail")) + if server_detail: + payload["server_detail"] = server_detail + if extra.get("session_cleared"): + payload["session_cleared"] = True emit_json(payload) else: print_error(message) diff --git a/dailybot_cli/config.py b/dailybot_cli/config.py index 82acd568..21b9cfcd 100644 --- a/dailybot_cli/config.py +++ b/dailybot_cli/config.py @@ -2,6 +2,7 @@ import json import os +import time from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -9,6 +10,9 @@ DEFAULT_API_URL: str = "https://api.dailybot.com" DEFAULT_APP_URL: str = "https://app.dailybot.com" +# How long the organization list saved by `dailybot login` stays usable: the life +# of a verification code, so a stale list never outlives the sign-in it served. +ORG_CACHE_TTL_SECS: int = 600 _api_url_override: str | None = None # The agent executing this invocation on a person's behalf (root `--agent-name`). _agent_name_override: str | None = None @@ -232,6 +236,34 @@ def clear_credentials() -> None: creds_path.unlink() +def clear_credentials_if_current( + api_url: str, *, token: str | None = None, refresh: str | None = None +) -> bool: + """Remove the stored login only if it is still the session the server refused. + + Compare-and-clear: the file must have been issued by ``api_url``'s host and + still hold ``token`` (or ``refresh``). A session another CLI process rotated or + replaced meanwhile is kept. Returns ``True`` when the file was removed. + """ + if not token and not refresh: + return False + creds: dict[str, Any] | None = load_credentials() + if not creds: + return False + issued_by: str = str(creds.get("api_url") or DEFAULT_API_URL) + if _origin(issued_by) != _origin(api_url): + return False + matches_token: bool = bool(token) and creds.get("token") == token + matches_refresh: bool = bool(refresh) and creds.get("refresh") == refresh + if not (matches_token or matches_refresh): + return False + try: + _credentials_path().unlink() + except FileNotFoundError: + return False + return True + + def get_api_url() -> str: """Return the API URL. @@ -466,12 +498,21 @@ def _safe_active_env_profile() -> dict[str, Any] | None: def save_org_cache(email: str, organizations: list[dict[str, Any]]) -> None: """Cache the org list from request_code for UUID resolution in step 2.""" get_config_dir() - data: dict[str, Any] = {"email": email, "organizations": organizations} + data: dict[str, Any] = { + "email": email, + "organizations": organizations, + "saved_at": time.time(), + } _write_secret_file(_org_cache_path(), json.dumps(data)) def load_org_cache(email: str) -> list[dict[str, Any]] | None: - """Load cached org list for the given email. Returns None if missing or stale.""" + """Load cached org list for the given email. + + Returns ``None`` when the file is missing, belongs to another email, or is older + than :data:`ORG_CACHE_TTL_SECS` (a file without ``saved_at``, written by an older + CLI, counts as expired). + """ cache_path: Path = _org_cache_path() if not cache_path.exists(): return None @@ -479,9 +520,15 @@ def load_org_cache(email: str) -> list[dict[str, Any]] | None: data: dict[str, Any] = json.loads(cache_path.read_text()) except (json.JSONDecodeError, OSError): return None - if data.get("email") != email: + if not isinstance(data, dict) or data.get("email") != email: + return None + saved_at: Any = data.get("saved_at") + if not isinstance(saved_at, (int, float)) or isinstance(saved_at, bool): + return None + if time.time() - saved_at > ORG_CACHE_TTL_SECS: return None - return data.get("organizations") + organizations: Any = data.get("organizations") + return organizations if isinstance(organizations, list) else None def clear_org_cache() -> None: diff --git a/dailybot_cli/display.py b/dailybot_cli/display.py index 7a51f36b..92eacf05 100644 --- a/dailybot_cli/display.py +++ b/dailybot_cli/display.py @@ -44,6 +44,39 @@ def print_info(message: str) -> None: console.print(f"[dim]{escape(message)}[/dim]") +SECONDS_PER_MINUTE: int = 60 + + +def format_wait(seconds: int) -> str: + """A wait in words: ``"30 seconds"``, ``"1 minute"``, ``"15 minutes"`` (rounded up).""" + if seconds < SECONDS_PER_MINUTE: + return f"{seconds} second" if seconds == 1 else f"{seconds} seconds" + minutes: int = -(-seconds // SECONDS_PER_MINUTE) + return "1 minute" if minutes == 1 else f"{minutes} minutes" + + +def print_sign_in_refusal(message: str, wait_secs: int | None = None) -> None: + """A sign-in door asked the person to wait: the server's sentence, then the wait.""" + print_error(_neutralize(message)) + if wait_secs is not None and wait_secs > 0: + print_info(f"Try again in {format_wait(wait_secs)}.") + else: + print_info("Wait a little, then try again.") + + +def print_sign_in_ended(server_detail: str | None, code: str | None, cleared: bool) -> None: + """Why the stored sign-in stopped working, and what was done about it (stderr).""" + if server_detail or code: + reason: str = _neutralize(server_detail or "") + tag: str = f" ({_neutralize(code)})" if code else "" + error_console.print(f"[dim]Server response: {escape(reason)}{escape(tag)}[/dim]") + if cleared: + error_console.print( + "[dim]The saved sign-in was removed from this computer. " + "Run `dailybot login` to sign in again.[/dim]" + ) + + def print_device_login_instructions( verification_uri: str, user_code: str, verification_uri_complete: str | None = None ) -> None: diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index c3102b2d..383b4a98 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -75,15 +75,15 @@ Authenticate via email-OTP. Three modes: | Mode | Invocation | Behavior | |------|------------|----------| -| Fully interactive | `dailybot login` | Prompts for email, requests code, prompts for code, prompts for org if multi-org | +| Fully interactive | `dailybot login` | Prompts for email, requests code, prompts for code (not shown while typing), then prompts for the org when verify-code asks for one | | Non-interactive step 1 | `dailybot login --email=` | Sends OTP, prints next-step instructions, exits | -| Non-interactive step 2 | `dailybot login --email= --code= [--org=]` | Verifies and saves credentials | +| Non-interactive step 2 | `dailybot login --email= --code= [--org=]` | Verifies and saves credentials. Without `--org` on a multi-org account it lists the organizations and exits `1` with the rerun hint (`--code=CODE`, the code is never printed back) | | Flag | Notes | |------|-------| | `--email` | If flag is present (vs. prompted), CLI runs in non-interactive mode | | `--code` | Required for step 2; without it, runs step 1 | -| `--org` | Org UUID (not integer ID) — resolved against `org_cache.json` saved during step 1 | +| `--org` | Org UUID (not integer ID) — sent as `organization_uuid`; when `org_cache.json` (step 1 or an earlier selection answer, valid 10 minutes) holds it, its `organization_id` is sent too. If verify-code still asks for a selection, the id is taken from that answer and the same code is sent once more | Persists: `~/.config/dailybot/credentials.json` (`0o600`). @@ -673,8 +673,8 @@ All endpoints are POSTed to `{api_url}/v1/...`. The default `api_url` is `https: | Method | Path | Request | Response (200/201) | Notes | |--------|------|---------|--------------------|-------| -| `POST` | `/v1/cli/auth/request-code/` | `{ email }` | `{ is_multi_org, organizations: [{id, uuid, name}] }` | No auth | -| `POST` | `/v1/cli/auth/verify-code/` | `{ email, code, organization_id? }` | `{ token, organization: {name, uuid} }` or `{ requires_organization_selection: true, organizations: [...] }` (a standalone organization adds `platform: "dailybot", standalone: true`) | No auth | +| `POST` | `/v1/cli/auth/request-code/` | `{ email }` | `{ detail, is_multi_org, organizations: [{id, uuid, name}] }` (`organizations` may be empty: the CLI never needs it and chooses the organization from verify-code) | No auth. `429` with `code` `otp_cooldown` and `retry_after` (+ `Retry-After`) | +| `POST` | `/v1/cli/auth/verify-code/` | `{ email, code, organization_id?, organization_uuid? }` | `{ token, organization: {name, uuid} }` or `{ requires_organization_selection: true, organizations: [...] }` (a standalone organization adds `platform: "dailybot", standalone: true`); a selection answer does not use up the code, the pick is a second call with it | No auth. `400` for a wrong code; `429` with `code` `otp_attempts_exceeded` and `retry_after` (+ `Retry-After`). On a `429` either door prints the server's sentence and the wait, never retries, and exits `6` | | — | request-code / verify-code `deprecation` | — | `deprecation: { code: "cli_auth_deprecated", min_version, sunset, detail }` on 200 **and** 400 bodies, plus `Deprecation`, `Sunset` and `Link` headers, while the server's notice is on | A field, never an error. The CLI shows the `sunset` date once and suggests `dailybot upgrade` only when its version is below `min_version` (`APIError.extra["deprecation"]` on a 400). | | `GET` | `/v1/cli/auth/status/` | — | `{ user: {email}, organization: {name, uuid} }` | Bearer | | `POST` | `/v1/cli/auth/logout/` | — | `{ detail }` | Bearer | @@ -823,7 +823,7 @@ not a dead session: it keeps the server's `detail` and `code`. | HTTP | Default behavior | Per-command override | |------|------------------|----------------------| | Any | `APIError(status_code, detail)` | All commands wrap calls in `try/except APIError` | -| 401 (bearer) | `_handle_response` rewrites detail to "Session expired. Run 'dailybot login' to re-authenticate." | Multiple commands also catch and prefix with their own context | +| 401 (bearer) | `_handle_response` rewrites detail to "Session expired. Run 'dailybot login' to re-authenticate.", keeps the server's sentence in `extra["server_detail"]` (a refused refresh's code and sentence win), and removes the stored login when it still holds the refused token (`extra["session_cleared"]`; never for `DAILYBOT_CLI_TOKEN`) | `exit_for_api_error` prints the server response and that the saved sign-in was removed. Multiple commands also catch and prefix with their own context | | 401 (api_key) | passes through with the backend's `detail` and `code` | `agent configure` treats it as an invalid key | | 403 (either credential) | passes through with the backend's `detail` and `code` (never rewritten to "Session expired") | Commands dispatch on `code` via `ERROR_CODE_MESSAGES`; agent commands use `agent_error_message` (`plan_upgrade_required` explains the agent-key scope and appends `upgrade_url`; `invalid_credentials` mentions a deleted agent). `agent configure` treats a 403 `plan_upgrade_required` as a valid key that is out of scope, and any other 401/403 as an invalid key | | 400 with a known `code` | passes through | Agent commands and `agent register` show the code's message; an unknown or absent code shows `detail` | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 59300781..0961ad41 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -116,7 +116,7 @@ def (...) -> None: Specific notes per file: -- **`auth.py`** — login is a 4-step flow (request code → optional org list → enter code → verify-and-save). Three call paths share `_verify_and_save`: interactive, non-interactive step 2 (`_verify_non_interactive`), and the auto-recurse on `requires_organization_selection`. The cached org list (`org_cache.json`) is critical for non-interactive multi-org login — re-calling `request_code` would invalidate the OTP. `login --device` runs the RFC 8628 browser sign-in in `commands/_device_login.py` (start → show link and code → poll at the server interval → save the access/refresh pair), falling back to the email code on a 404/405 start. The client refreshes that pair only on `401 access_token_expired` (`DailyBotClient._refresh_session`), and retries `503 auth_backend_unavailable` with a bounded wait (`_retry_auth_backend`). +- **`auth.py`** — login is request code → enter code → verify → (pick the organization when verify-code answers `requires_organization_selection`, then verify again with the same code) → save. The request-code answer is never used to choose the organization. Three call paths share `_verify_and_save`: interactive, non-interactive step 2 (`_verify_non_interactive`, `--org` sent as `organization_uuid`), and the single re-call after a selection answer (`picked`, so a repeated selection answer stops). `org_cache.json` (10-minute life) only supplies the integer id for servers that read `organization_id`; re-calling `request_code` would invalidate the OTP. A `429` on either door goes through `_exit_for_login_door_error` (server sentence + wait, exit `6`, no retry). `login --device` runs the RFC 8628 browser sign-in in `commands/_device_login.py` (start → show link and code → poll at the server interval → save the access/refresh pair), falling back to the email code on a 404/405 start. The client refreshes that pair only on `401 access_token_expired` (`DailyBotClient._refresh_session`), and retries `503 auth_backend_unavailable` with a bounded wait (`_retry_auth_backend`). - **`status.py`** — two modes: list pending check-ins (default) or verify auth (`--auth`). The `--auth` path tries OTP first, then API key, with carefully tuned error messages. - **`update.py`** — supports free-text + structured fields. When invoked with no args, falls back to a stdin loop (Enter twice to submit). 401/403 → `dailybot login`; 400 with "ai processing failed" → contact support. - **`agent.py`** — the largest module. Sub-groups: `webhook`, `message`, `email`. The `_resolve_agent_context` helper centralizes the 5-step auth resolution and is the only function that should be touched if the resolution order needs to change. The `register` command implements a math-challenge handshake (no auth needed). @@ -140,13 +140,14 @@ user runs `dailybot login` │ ├─ commands/auth.py::login → _do_login(email) │ ├─ DailyBotClient().request_code(email) - │ │ POST /v1/cli/auth/request-code/ → { is_multi_org, organizations: [...] } + │ │ POST /v1/cli/auth/request-code/ → { detail, ... } (organizations not used) │ │ - │ ├─ display._print_org_list(orgs) - │ ├─ click.prompt for the 6-digit code - │ ├─ questionary.select an org - │ └─ _verify_and_save(client, email, code, org_id) - │ ├─ client.verify_code(...) → { token, organization, organization_uuid } + │ ├─ click.prompt for the 6-digit code (hidden input) + │ └─ _verify_and_save(client, email, code) + │ ├─ client.verify_code(email, code) → { requires_organization_selection, organizations } + │ ├─ questionary.select an org + │ ├─ client.verify_code(email, code, organization_id, organization_uuid) + │ │ → { token, organization } │ ├─ config.save_credentials(...) (chmod 0600) │ └─ print_success(f"Logged in as {email} ({org_name})") ``` diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 628829aa..47d50f06 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -10,7 +10,7 @@ The Dailybot CLI persists state in `~/.config/dailybot/` by default. The path ca | `config.json` | `dailybot config` | `{ api_key }` (and any future settings) | `0o600` | | `agents.json` | `dailybot agent configure` / `register` | `{ default, profiles: { : { agent_name, api_key?, agent_email? } } }` | `0o600` | | `plan_cache.json` | `dailybot login`, `dailybot org`, the plan short-circuit | `{ : , _refreshed_at: { : } }` — tiers only, never a secret | `0o600` | -| `org_cache.json` | `dailybot login --email` (step 1) | `{ email, organizations: [...] }` | (no chmod — non-secret) | +| `org_cache.json` | `dailybot login --email` (step 1), or a verify-code selection answer | `{ email, organizations: [...], saved_at }` — read only for 10 minutes (`ORG_CACHE_TTL_SECS`); a file without `saved_at` counts as expired; removed after a successful login | `0o600` | | `ledger/.json` | `dailybot hook ...` / `dailybot agent update` | Per-repo report ledger: `{ repo, first_seen_at, last_report_at, last_reported_commit, last_nudge_at, last_activity_at, work_pending, snoozed_until, turns_since_report, reported_by }` | `0o600` (dir `0o700`) | | `ledger/_global.json` | `dailybot hook session-start` | Cross-repo hook state: `{ last_login_nudge_at }` | `0o600` | | `/.dailybot/profile.json` | hand-authored, committed to git | `{ name?, profile?, default_metadata?, vars?, report? }` | (no chmod — must be readable by team) | diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 9d5f006d..cd60fdd5 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -40,6 +40,11 @@ Common issues and how to fix them. If you hit something that isn't here, add it - The Bearer token has expired. Re-run `dailybot login`. - The API URL has changed (e.g., switched from prod to staging without re-authenticating). Tokens are URL-scoped — log in to the new URL. +- The sign-in was ended on the server (for example after a password change, or a logout elsewhere). The line `Server response: …` under the error shows the server's own reason. When the stored sign-in on this computer is the one that was refused, the CLI removes it and says so; `dailybot login` stores a new one. A `DAILYBOT_CLI_TOKEN` in the environment is never removed from anywhere. + +### `dailybot login`: "Try again in …" (exit 6) + +The sign-in doors answered `429`: a code was requested for this email moments ago, or too many codes were tried. The CLI prints the server's sentence and the wait, and does not retry by itself. Use the code already in your inbox if you have one, or wait the time shown and run `dailybot login` again. ### "Dailybot sign-in is temporarily unavailable" (`auth_backend_unavailable`, exit 6) diff --git a/tests/commands_test.py b/tests/commands_test.py index 0dec6f87..ccbb01a0 100644 --- a/tests/commands_test.py +++ b/tests/commands_test.py @@ -514,9 +514,9 @@ def test_login_single_org( assert "Logged in" in result.output assert "MyOrg" in result.output mock_save.assert_called_once() - # Single-org: verify is called once with organization_id + # The organization never comes from request-code: one verify, no pick needed. mock_client.verify_code.assert_called_once_with( - "user@test.com", "123456", organization_id=1 + "user@test.com", "123456", organization_id=None ) @patch("dailybot_cli.commands.auth.DailyBotClient") @@ -592,12 +592,14 @@ def test_login_multi_org( "organizations": orgs, "is_multi_org": True, } - mock_client.verify_code.return_value = { - "requires_organization_selection": False, - "token": "tok456", - "user": {"email": "user@test.com"}, - "organization": {"id": 2, "name": "Side Project", "uuid": "def-456"}, - } + mock_client.verify_code.side_effect = [ + {"requires_organization_selection": True, "organizations": orgs}, + { + "token": "tok456", + "user": {"email": "user@test.com"}, + "organization": {"id": 2, "name": "Side Project", "uuid": "def-456"}, + }, + ] # Mock questionary.select to return the second org mock_questionary.select.return_value.ask.return_value = orgs[1] @@ -606,9 +608,10 @@ def test_login_multi_org( assert result.exit_code == 0 assert "Logged in" in result.output assert "Side Project" in result.output - # Org selected before verify — single call with org_id - mock_client.verify_code.assert_called_once_with( - "user@test.com", "123456", organization_id=2 + # Org picked from verify-code's selection answer, then the same code again + assert mock_client.verify_code.call_count == 2 + mock_client.verify_code.assert_called_with( + "user@test.com", "123456", organization_id=2, organization_uuid="def-456" ) @patch("dailybot_cli.commands.auth.DailyBotClient") @@ -681,9 +684,9 @@ def test_login_non_interactive_verify_with_org( assert "Side Project" in result.output # Should NOT call request_code (would invalidate the OTP) mock_client.request_code.assert_not_called() - # Single verify call with resolved integer ID + # Single verify call with the uuid and the id resolved from the cache mock_client.verify_code.assert_called_once_with( - "user@test.com", "654321", organization_id=2 + "user@test.com", "654321", organization_id=2, organization_uuid="def-456" ) mock_clear_cache.assert_called_once() @@ -695,32 +698,49 @@ def test_login_non_interactive_verify_with_bad_org_uuid( mock_load_cache: MagicMock, runner: CliRunner, ) -> None: - """Non-interactive --org with unknown UUID shows error and org list.""" - mock_load_cache.return_value = [ - {"id": 1, "name": "Acme Corp", "uuid": "abc-123"}, - ] + """Non-interactive --org with an unknown UUID: the server's list is shown.""" + orgs = [{"id": 1, "name": "Acme Corp", "uuid": "abc-123"}] + mock_load_cache.return_value = orgs + mock_client: MagicMock = mock_client_cls.return_value + mock_client.verify_code.return_value = { + "requires_organization_selection": True, + "organizations": [*orgs, {"id": 2, "name": "Side Project", "uuid": "def-456"}], + } result = runner.invoke( cli, ["login", "--email=user@test.com", "--code=654321", "--org=wrong-uuid"] ) assert result.exit_code != 0 - assert "not found" in result.output + assert "wrong-uuid" in result.output + assert "not one of this account's organizations" in result.output assert "Acme Corp" in result.output @patch("dailybot_cli.commands.auth.load_org_cache") + @patch("dailybot_cli.commands.auth.DailyBotClient") + @patch("dailybot_cli.commands.auth.save_credentials") def test_login_non_interactive_verify_with_org_no_cache( self, + mock_save: MagicMock, + mock_client_cls: MagicMock, mock_load_cache: MagicMock, runner: CliRunner, ) -> None: - """Non-interactive --org without cached org list tells user to run step 1.""" + """Non-interactive --org without a cached list sends the uuid as is.""" mock_load_cache.return_value = None + mock_client: MagicMock = mock_client_cls.return_value + mock_client.api_url = "https://api.dailybot.com" + mock_client.verify_code.return_value = { + "token": "tok-uuid", + "organization": {"id": 1, "name": "Acme Corp", "uuid": "abc-123"}, + } result = runner.invoke( cli, ["login", "--email=user@test.com", "--code=654321", "--org=abc-123"] ) - assert result.exit_code != 0 - assert "No cached organization list" in result.output + assert result.exit_code == 0 + mock_client.verify_code.assert_called_once_with( + "user@test.com", "654321", organization_id=None, organization_uuid="abc-123" + ) @patch("dailybot_cli.commands.auth.save_org_cache") @patch("dailybot_cli.commands.auth.DailyBotClient") @@ -808,7 +828,9 @@ def test_login_non_interactive_verify_auto_selects_single_org( assert "Auto-selecting organization: MyOrg" in result.output assert "Logged in" in result.output assert mock_client.verify_code.call_count == 2 - mock_client.verify_code.assert_called_with("user@test.com", "123456", organization_id=1) + mock_client.verify_code.assert_called_with( + "user@test.com", "123456", organization_id=1, organization_uuid="org-uuid" + ) @patch("dailybot_cli.commands.auth.DailyBotClient") def test_login_non_interactive_request_code_single_org( diff --git a/tests/credentials_refresh_test.py b/tests/credentials_refresh_test.py index c74af251..4f96538c 100644 --- a/tests/credentials_refresh_test.py +++ b/tests/credentials_refresh_test.py @@ -219,7 +219,7 @@ def test_a_pair_from_another_host_is_never_refreshed(self) -> None: class TestRefreshFailures: @pytest.mark.parametrize("code", ["refresh_token_expired", "user_disabled"]) - def test_a_refused_refresh_keeps_todays_fallback(self, code: str) -> None: + def test_a_refused_refresh_falls_back_and_ends_the_stored_session(self, code: str) -> None: _save_pair() client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") with ( @@ -234,8 +234,8 @@ def test_a_refused_refresh_keeps_todays_fallback(self, code: str) -> None: ): assert client.get_status() == {"ok": True} assert get.call_args_list[1].kwargs["headers"].get("X-API-KEY") == "test-key" - creds: dict[str, Any] | None = load_credentials() - assert creds is not None and creds["token"] == OLD_ACCESS + # The refused pair is over: it is removed, the key keeps the command working. + assert load_credentials() is None def test_a_transport_failure_never_falls_back_or_changes_credentials(self) -> None: _save_pair() diff --git a/tests/login_robustness_test.py b/tests/login_robustness_test.py new file mode 100644 index 00000000..5337b989 --- /dev/null +++ b/tests/login_robustness_test.py @@ -0,0 +1,448 @@ +"""Login robustness: organization chosen after verification, clearer sign-in errors, +a finite organization cache, and a stored sign-in that ends cleanly. + +Every flow is exercised against both server answers the CLI meets in the field: +the long-standing request-code body (organizations listed) and the newer one +(the same neutral answer for every email, organizations only after verify-code). +HTTP is mocked at the call site. +""" + +import json +import time +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest +from click.testing import CliRunner, Result + +from dailybot_cli.api_client import APIError, DailyBotClient +from dailybot_cli.commands.public_api_helpers import EXIT_RATE_LIMITED +from dailybot_cli.config import ( + ORG_CACHE_TTL_SECS, + load_credentials, + load_org_cache, + save_credentials, + save_org_cache, +) +from dailybot_cli.main import cli + +POST: str = "dailybot_cli.api_client.httpx.post" +GET: str = "dailybot_cli.api_client.httpx.get" +API: str = "https://api.dailybot.com" +EMAIL: str = "me@example.com" +CODE: str = "424242" + +ORG_A: dict[str, Any] = {"id": 11, "name": "My Team", "uuid": "org-uuid-a"} +ORG_B: dict[str, Any] = {"id": 22, "name": "Side Project", "uuid": "org-uuid-b"} + +NEUTRAL_REQUEST_BODY: dict[str, Any] = { + "detail": "If this email has a Dailybot account, a verification code is on its way.", + "organizations": [], + "is_multi_org": False, +} +LISTED_REQUEST_BODY: dict[str, Any] = { + "detail": "Verification code sent to your email.", + "organizations": [ORG_A, ORG_B], + "is_multi_org": True, +} +SELECTION_BODY: dict[str, Any] = { + "requires_organization_selection": True, + "organizations": [ORG_A, ORG_B], +} + + +@pytest.fixture(autouse=True) +def _no_ambient_credentials(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ("DAILYBOT_API_KEY", "DAILYBOT_CLI_TOKEN", "DAILYBOT_API_URL"): + monkeypatch.delenv(name, raising=False) + + +def _response( + status: int, body: dict[str, Any], headers: dict[str, str] | None = None +) -> MagicMock: + response: MagicMock = MagicMock() + response.status_code = status + response.headers = headers or {} + response.json.return_value = body + response.text = json.dumps(body) + return response + + +def _token_for(org: dict[str, Any]) -> MagicMock: + return _response( + 200, + {"token": "test-token", "user": {"email": EMAIL}, "organization": dict(org)}, + ) + + +def _verify_payloads(post: MagicMock) -> list[dict[str, Any]]: + return [ + call.kwargs["json"] + for call in post.call_args_list + if call.args and str(call.args[0]).endswith("/verify-code/") + ] + + +class TestVerifyCodeWire: + def test_organization_uuid_is_sent_when_given(self) -> None: + with patch(POST, return_value=_token_for(ORG_A)) as post: + DailyBotClient(api_url=API).verify_code(EMAIL, CODE, organization_uuid=ORG_A["uuid"]) + assert post.call_args.kwargs["json"] == { + "email": EMAIL, + "code": CODE, + "organization_uuid": ORG_A["uuid"], + } + + def test_the_body_is_unchanged_without_an_organization(self) -> None: + with patch(POST, return_value=_token_for(ORG_A)) as post: + DailyBotClient(api_url=API).verify_code(EMAIL, CODE) + assert post.call_args.kwargs["json"] == {"email": EMAIL, "code": CODE} + + def test_a_top_level_retry_after_reaches_the_error(self) -> None: + body: dict[str, Any] = {"detail": "Wait.", "code": "otp_cooldown", "retry_after": 30} + with patch(POST, return_value=_response(429, body)), pytest.raises(APIError) as caught: + DailyBotClient(api_url=API).request_code(EMAIL) + assert caught.value.code == "otp_cooldown" + assert caught.value.extra["retry_after"] == 30 + + +class TestInteractive: + @pytest.mark.parametrize("request_body", [NEUTRAL_REQUEST_BODY, LISTED_REQUEST_BODY]) + def test_the_organization_is_chosen_after_the_code(self, request_body: dict[str, Any]) -> None: + question: MagicMock = MagicMock() + question.ask.return_value = ORG_B + with ( + patch("dailybot_cli.commands.auth.questionary.select", return_value=question), + patch( + POST, + side_effect=[ + _response(200, request_body), + _response(200, SELECTION_BODY), + _token_for(ORG_B), + ], + ) as post, + ): + result: Result = CliRunner().invoke(cli, ["login"], input=f"{EMAIL}\n{CODE}\n") + assert result.exit_code == 0, result.output + payloads: list[dict[str, Any]] = _verify_payloads(post) + assert payloads[0] == {"email": EMAIL, "code": CODE} + # The pick is a second call with the same code. + assert payloads[1]["code"] == CODE + assert payloads[1]["organization_uuid"] == ORG_B["uuid"] + assert payloads[1]["organization_id"] == ORG_B["id"] + creds: dict[str, Any] | None = load_credentials() + assert creds is not None and creds["organization_uuid"] == ORG_B["uuid"] + + def test_a_single_organization_logs_in_with_one_verify(self) -> None: + with patch( + POST, side_effect=[_response(200, NEUTRAL_REQUEST_BODY), _token_for(ORG_A)] + ) as post: + result: Result = CliRunner().invoke(cli, ["login"], input=f"{EMAIL}\n{CODE}\n") + assert result.exit_code == 0, result.output + assert _verify_payloads(post) == [{"email": EMAIL, "code": CODE}] + assert "Logged in" in result.output + + def test_the_typed_code_is_not_shown(self) -> None: + with patch(POST, side_effect=[_response(200, NEUTRAL_REQUEST_BODY), _token_for(ORG_A)]): + result: Result = CliRunner().invoke(cli, ["login"], input=f"{EMAIL}\n{CODE}\n") + assert result.exit_code == 0, result.output + assert CODE not in result.output + + def test_the_neutral_answer_is_shown_as_sent(self) -> None: + with patch(POST, side_effect=[_response(200, NEUTRAL_REQUEST_BODY), _token_for(ORG_A)]): + result: Result = CliRunner().invoke(cli, ["login"], input=f"{EMAIL}\n{CODE}\n") + assert "a verification code is on its way" in result.output + + +class TestNonInteractiveStepOne: + def test_the_neutral_answer_prints_the_next_step(self) -> None: + with patch(POST, return_value=_response(200, NEUTRAL_REQUEST_BODY)): + result: Result = CliRunner().invoke(cli, ["login", "--email", EMAIL]) + assert result.exit_code == 0, result.output + assert f"dailybot login --email={EMAIL} --code=CODE" in result.output + assert "If you belong to several organizations" in result.output + assert load_org_cache(EMAIL) is None + + def test_a_listed_answer_keeps_todays_output(self) -> None: + with patch(POST, return_value=_response(200, LISTED_REQUEST_BODY)): + result: Result = CliRunner().invoke(cli, ["login", "--email", EMAIL]) + assert result.exit_code == 0, result.output + assert f"{ORG_A['name']} (uuid: {ORG_A['uuid']})" in result.output + assert "--code=CODE --org=ORG_UUID" in result.output + assert load_org_cache(EMAIL) == [ORG_A, ORG_B] + + +class TestNonInteractiveStepTwo: + def test_a_selection_answer_lists_the_organizations_and_fails(self) -> None: + with patch(POST, return_value=_response(200, SELECTION_BODY)): + result: Result = CliRunner().invoke(cli, ["login", "--email", EMAIL, "--code", CODE]) + assert result.exit_code == 1 + assert f"{ORG_A['name']} (uuid: {ORG_A['uuid']})" in result.output + assert f"{ORG_B['name']} (uuid: {ORG_B['uuid']})" in result.output + assert f"dailybot login --email={EMAIL} --code=CODE --org=ORG_UUID" in result.output + # The code is never printed back. + assert CODE not in result.output + assert load_org_cache(EMAIL) == [ORG_A, ORG_B] + + def test_org_without_any_cache_sends_the_uuid(self) -> None: + with patch(POST, return_value=_token_for(ORG_B)) as post: + result: Result = CliRunner().invoke( + cli, ["login", "--email", EMAIL, "--code", CODE, "--org", ORG_B["uuid"]] + ) + assert result.exit_code == 0, result.output + assert _verify_payloads(post) == [ + {"email": EMAIL, "code": CODE, "organization_uuid": ORG_B["uuid"]} + ] + + def test_org_with_a_cache_sends_the_uuid_and_the_id(self) -> None: + save_org_cache(EMAIL, [ORG_A, ORG_B]) + with patch(POST, return_value=_token_for(ORG_B)) as post: + result: Result = CliRunner().invoke( + cli, ["login", "--email", EMAIL, "--code", CODE, "--org", ORG_B["uuid"]] + ) + assert result.exit_code == 0, result.output + assert _verify_payloads(post) == [ + { + "email": EMAIL, + "code": CODE, + "organization_id": ORG_B["id"], + "organization_uuid": ORG_B["uuid"], + } + ] + assert load_org_cache(EMAIL) is None + + def test_the_selection_after_a_failed_step_two_completes_the_rerun(self) -> None: + runner: CliRunner = CliRunner() + with patch(POST, side_effect=[_response(200, SELECTION_BODY), _token_for(ORG_A)]) as post: + first: Result = runner.invoke(cli, ["login", "--email", EMAIL, "--code", CODE]) + second: Result = runner.invoke( + cli, ["login", "--email", EMAIL, "--code", CODE, "--org", ORG_A["uuid"]] + ) + assert first.exit_code == 1 + assert second.exit_code == 0, second.output + assert _verify_payloads(post)[1]["organization_id"] == ORG_A["id"] + + def test_a_server_that_ignores_the_uuid_is_answered_with_the_id(self) -> None: + with patch(POST, side_effect=[_response(200, SELECTION_BODY), _token_for(ORG_B)]) as post: + result: Result = CliRunner().invoke( + cli, ["login", "--email", EMAIL, "--code", CODE, "--org", ORG_B["uuid"]] + ) + assert result.exit_code == 0, result.output + second: dict[str, Any] = _verify_payloads(post)[1] + assert second["organization_id"] == ORG_B["id"] + assert second["code"] == CODE + + def test_an_org_that_is_not_offered_fails_with_the_list(self) -> None: + with patch(POST, return_value=_response(200, SELECTION_BODY)) as post: + result: Result = CliRunner().invoke( + cli, ["login", "--email", EMAIL, "--code", CODE, "--org", "not-mine"] + ) + assert result.exit_code == 1 + assert "not-mine" in result.output + assert f"{ORG_A['name']} (uuid: {ORG_A['uuid']})" in result.output + assert len(_verify_payloads(post)) == 1 + + def test_a_repeated_selection_answer_never_loops(self) -> None: + with patch(POST, return_value=_response(200, SELECTION_BODY)) as post: + result: Result = CliRunner().invoke( + cli, ["login", "--email", EMAIL, "--code", CODE, "--org", ORG_A["uuid"]] + ) + assert result.exit_code == 1 + assert len(_verify_payloads(post)) == 2 + + def test_a_wrong_code_keeps_todays_error(self) -> None: + with patch(POST, return_value=_response(400, {"detail": "Invalid verification code."})): + result: Result = CliRunner().invoke(cli, ["login", "--email", EMAIL, "--code", CODE]) + assert result.exit_code == 1 + assert "Invalid verification code." in result.output + + +class TestRateLimited: + def test_request_code_429_shows_the_wait_and_stops(self) -> None: + body: dict[str, Any] = { + "detail": "Please wait before asking for another code.", + "code": "otp_cooldown", + "retry_after": 30, + } + with patch(POST, return_value=_response(429, body, {"Retry-After": "30"})) as post: + result: Result = CliRunner().invoke(cli, ["login", "--email", EMAIL]) + assert result.exit_code == EXIT_RATE_LIMITED + assert "Please wait before asking for another code." in result.output + assert "30 seconds" in result.output + assert post.call_count == 1 + + def test_verify_code_429_uses_the_header_and_is_not_an_invalid_code(self) -> None: + body: dict[str, Any] = { + "detail": "Too many attempts for this email. Try again later.", + "code": "otp_attempts_exceeded", + } + with patch(POST, return_value=_response(429, body, {"Retry-After": "900"})) as post: + result: Result = CliRunner().invoke(cli, ["login", "--email", EMAIL, "--code", CODE]) + assert result.exit_code == EXIT_RATE_LIMITED + assert "Too many attempts for this email." in result.output + assert "15 minutes" in result.output + assert "Invalid" not in result.output + assert post.call_count == 1 + + def test_a_429_without_a_detail_falls_back_to_the_code_message(self) -> None: + with patch(POST, return_value=_response(429, {"code": "otp_cooldown", "detail": ""})): + result: Result = CliRunner().invoke(cli, ["login", "--email", EMAIL]) + assert result.exit_code == EXIT_RATE_LIMITED + assert "verification code" in result.output.lower() + + def test_interactive_429_on_request_stops_before_the_code_prompt(self) -> None: + body: dict[str, Any] = {"detail": "Please wait.", "code": "otp_cooldown", "retry_after": 5} + with patch(POST, return_value=_response(429, body)): + result: Result = CliRunner().invoke(cli, ["login"], input=f"{EMAIL}\n") + assert result.exit_code == EXIT_RATE_LIMITED + assert "6-digit code" not in result.output + + +class TestOrgCacheLifetime: + def test_a_fresh_cache_is_read(self) -> None: + save_org_cache(EMAIL, [ORG_A]) + assert load_org_cache(EMAIL) == [ORG_A] + + def test_an_old_cache_is_ignored(self, monkeypatch: pytest.MonkeyPatch) -> None: + save_org_cache(EMAIL, [ORG_A]) + later: float = time.time() + ORG_CACHE_TTL_SECS + 1 + monkeypatch.setattr("dailybot_cli.config.time.time", lambda: later) + assert load_org_cache(EMAIL) is None + + def test_a_cache_without_a_timestamp_is_ignored(self, _isolated_environment: Path) -> None: + _isolated_environment.mkdir(parents=True, exist_ok=True) + (_isolated_environment / "org_cache.json").write_text( + json.dumps({"email": EMAIL, "organizations": [ORG_A]}) + ) + assert load_org_cache(EMAIL) is None + + +def _save_legacy(token: str = "test-token") -> None: + save_credentials( + token=token, email=EMAIL, organization="My Team", organization_uuid="org-1", api_url=API + ) + + +def _save_pair() -> None: + save_credentials( + token="dbc_at_test-access", + email=EMAIL, + organization="My Team", + organization_uuid="org-1", + api_url=API, + refresh="dbc_rt_test-refresh", + expires_at="2030-01-01T00:00:00Z", + refresh_expires_at="2030-04-01T00:00:00Z", + ) + + +class TestEndedSession: + def test_a_401_on_the_stored_token_clears_it(self) -> None: + _save_legacy() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch(GET, return_value=_response(401, {"detail": "Invalid token."})), + pytest.raises(APIError) as caught, + ): + client.auth_status() + assert load_credentials() is None + assert caught.value.extra["session_cleared"] is True + assert caught.value.extra["server_detail"] == "Invalid token." + assert "dailybot login" in caught.value.detail + + def test_a_refused_refresh_clears_the_pair_and_keeps_its_code(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + expired: MagicMock = _response( + 401, {"detail": "Access token expired.", "code": "access_token_expired"} + ) + revoked: MagicMock = _response( + 401, {"detail": "Session revoked.", "code": "session_revoked"} + ) + with ( + patch(GET, return_value=expired), + patch(POST, return_value=revoked), + pytest.raises(APIError) as caught, + ): + client.auth_status() + assert caught.value.code == "session_revoked" + assert caught.value.extra["server_detail"] == "Session revoked." + assert load_credentials() is None + + def test_a_refused_refresh_clears_the_pair_even_when_a_key_answers(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") + expired: MagicMock = _response( + 401, {"detail": "Access token expired.", "code": "access_token_expired"} + ) + refused: MagicMock = _response(401, {"detail": "Expired.", "code": "refresh_token_expired"}) + with ( + patch(GET, side_effect=[expired, _response(200, {"ok": True})]), + patch(POST, return_value=refused), + ): + assert client.auth_status() == {"ok": True} + assert load_credentials() is None + + def test_a_failed_renewal_without_a_refusal_keeps_the_pair(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + expired: MagicMock = _response( + 401, {"detail": "Access token expired.", "code": "access_token_expired"} + ) + malformed: MagicMock = _response(200, {"access": "", "refresh": ""}) + with ( + patch(GET, return_value=expired), + patch(POST, return_value=malformed), + pytest.raises(APIError) as caught, + ): + client.auth_status() + assert load_credentials() is not None + assert caught.value.extra["session_cleared"] is False + + def test_an_env_token_never_clears_the_file(self, monkeypatch: pytest.MonkeyPatch) -> None: + _save_legacy() + monkeypatch.setenv("DAILYBOT_CLI_TOKEN", "test-env-token") + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch(GET, return_value=_response(401, {"detail": "Invalid token."})), + pytest.raises(APIError) as caught, + ): + client.auth_status() + assert load_credentials() is not None + assert caught.value.extra["session_cleared"] is False + + def test_a_file_rotated_meanwhile_is_kept(self) -> None: + _save_legacy(token="test-token-old") + client: DailyBotClient = DailyBotClient(api_url=API) + _save_legacy(token="test-token-new") + with ( + patch(GET, return_value=_response(401, {"detail": "Invalid token."})), + pytest.raises(APIError), + ): + client.auth_status() + creds: dict[str, Any] | None = load_credentials() + assert creds is not None and creds["token"] == "test-token-new" + + def test_a_401_to_an_api_key_never_clears_the_session(self) -> None: + _save_legacy() + client: DailyBotClient = DailyBotClient( + api_url=API, api_key="test-key", prefer_api_key=True, token=None + ) + client.token = None + with ( + patch(GET, return_value=_response(401, {"detail": "Invalid key."})), + pytest.raises(APIError), + ): + client.auth_status() + assert load_credentials() is not None + + def test_the_command_tells_the_person_what_happened(self) -> None: + _save_legacy() + with patch(GET, return_value=_response(401, {"detail": "Invalid token."})): + result: Result = CliRunner().invoke(cli, ["user", "list"]) + assert result.exit_code == 3 + assert "Invalid token." in result.output + assert "removed" in result.output + assert "dailybot login" in result.output + assert load_credentials() is None diff --git a/tests/standalone_org_login_test.py b/tests/standalone_org_login_test.py index af6c8b16..50c083ff 100644 --- a/tests/standalone_org_login_test.py +++ b/tests/standalone_org_login_test.py @@ -118,7 +118,10 @@ def pick(_message: str, choices: list[Any]) -> MagicMock: with ( patch("dailybot_cli.commands.auth.questionary.select", side_effect=pick), - patch(POST, side_effect=[_request_code_multi(), _token_for(NATIVE_ORG)]) as post, + patch( + POST, + side_effect=[_request_code_multi(), _selection_required(), _token_for(NATIVE_ORG)], + ) as post, ): result: Result = CliRunner().invoke(cli, ["login"], input="me@example.com\n123456\n") assert result.exit_code == 0, result.output @@ -133,10 +136,14 @@ def test_the_numbered_fallback_selects_it(self) -> None: native_index: int = ORGS.index(NATIVE_ORG) + 1 with ( patch("dailybot_cli.commands.auth.questionary.select", return_value=question), - patch(POST, side_effect=[_request_code_multi(), _token_for(NATIVE_ORG)]) as post, + patch( + POST, + side_effect=[_request_code_multi(), _selection_required(), _token_for(NATIVE_ORG)], + ) as post, ): + # The organization is picked after the code now. result: Result = CliRunner().invoke( - cli, ["login"], input=f"me@example.com\n{native_index}\n123456\n" + cli, ["login"], input=f"me@example.com\n123456\n{native_index}\n" ) assert result.exit_code == 0, result.output assert org_choice_label(NATIVE_ORG) in result.output From 80194c51aaeb12687246fabcee49f25400f58ae3 Mon Sep 17 00:00:00 2001 From: Sergio Florez Date: Tue, 24 Nov 2026 17:12:45 +0000 Subject: [PATCH 2/2] test(auth): pin the confirmed sign-in answers Cover the server's exact answers for an ended CLI session (revoked access token, revoked refresh, bare 401 on a legacy token), an organization that is not offered, and the two wait sentences on the sign-in doors. Co-Authored-By: Claude Opus 5.5 --- tests/login_robustness_test.py | 85 ++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/tests/login_robustness_test.py b/tests/login_robustness_test.py index 5337b989..18b52caf 100644 --- a/tests/login_robustness_test.py +++ b/tests/login_robustness_test.py @@ -446,3 +446,88 @@ def test_the_command_tells_the_person_what_happened(self) -> None: assert "removed" in result.output assert "dailybot login" in result.output assert load_credentials() is None + + +# The server's confirmed answers (PLAN_006 contract), byte for byte. +REVOKED_DETAIL: str = "This CLI session was revoked. Log in again." +ATTEMPTS_DETAIL: str = ( + "Too many incorrect codes for this email. Wait 15 minute(s), then run `dailybot login` again." +) +COOLDOWN_DETAIL: str = ( + "A code was just requested for this email. Wait 30 second(s) before asking for another one." +) + + +class TestConfirmedContract: + def test_a_revoked_access_token_ends_the_session_without_a_refresh(self) -> None: + _save_pair() + revoked: MagicMock = _response(401, {"detail": REVOKED_DETAIL, "code": "session_revoked"}) + with patch(GET, return_value=revoked), patch(POST) as post: + result: Result = CliRunner().invoke(cli, ["user", "list"]) + post.assert_not_called() + assert result.exit_code == 3 + assert "signed out" in result.output + assert REVOKED_DETAIL in result.output + assert load_credentials() is None + + def test_a_revoked_refresh_ends_the_session(self) -> None: + _save_pair() + expired: MagicMock = _response( + 401, {"detail": "Access token expired.", "code": "access_token_expired"} + ) + revoked: MagicMock = _response(401, {"detail": REVOKED_DETAIL, "code": "session_revoked"}) + with patch(GET, return_value=expired), patch(POST, return_value=revoked): + result: Result = CliRunner().invoke(cli, ["user", "list"]) + assert result.exit_code == 3 + assert "signed out" in result.output + assert REVOKED_DETAIL in result.output + assert load_credentials() is None + + def test_a_bare_401_on_a_legacy_token_means_log_in_again(self) -> None: + _save_legacy() + bare: MagicMock = _response( + 401, {"detail": "Authentication credentials were not provided."} + ) + with patch(GET, return_value=bare): + result: Result = CliRunner().invoke(cli, ["user", "list"]) + assert result.exit_code == 3 + assert "dailybot login" in result.output + assert load_credentials() is None + + def test_an_org_uuid_that_is_not_offered_shows_the_400(self) -> None: + refused: MagicMock = _response( + 400, {"detail": "That organization is not available for this account."} + ) + with patch(POST, return_value=refused) as post: + result: Result = CliRunner().invoke( + cli, ["login", "--email", EMAIL, "--code", CODE, "--org", "not-mine"] + ) + assert result.exit_code == 1 + assert "That organization is not available for this account." in result.output + assert len(_verify_payloads(post)) == 1 + + @pytest.mark.parametrize( + ("argv", "body", "wait"), + [ + ( + ["login", "--email", EMAIL], + {"detail": COOLDOWN_DETAIL, "code": "otp_cooldown", "retry_after": 30}, + "30 seconds", + ), + ( + ["login", "--email", EMAIL, "--code", CODE], + {"detail": ATTEMPTS_DETAIL, "code": "otp_attempts_exceeded", "retry_after": 900}, + "15 minutes", + ), + ], + ) + def test_the_429_sentences_are_shown_as_sent( + self, argv: list[str], body: dict[str, Any], wait: str + ) -> None: + headers: dict[str, str] = {"Retry-After": str(body["retry_after"])} + with patch(POST, return_value=_response(429, body, headers)) as post: + result: Result = CliRunner().invoke(cli, argv) + assert result.exit_code == EXIT_RATE_LIMITED + assert " ".join(str(body["detail"]).split()) in " ".join(result.output.split()) + assert wait in result.output + assert post.call_count == 1