Repository navigation
fix(auth): login robustness and clearer sign-in errors - #157
Conversation
## 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 <[email protected]>
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 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This comment has been minimized.
This comment has been minimized.
AI review for
|
There was a problem hiding this comment.
Code review — 7 finding(s): 0 critical · 4 warning · 3 info
Verification: 2 verified · 0 downgraded · 0 refuted · 2 unverified · 3 skipped — grok-4.5
Check: ✅ passing — strictness block-on-critical: highest severity warning ≤ critical threshold
Findings
| Severity | Location | Title | Verification | Agreement |
|---|---|---|---|---|
dailybot_cli/api_client.py:891 |
Silent credentials wipe when API-key fallback succeeds | unverified | — | |
dailybot_cli/commands/public_api_helpers.py:1186 |
session_cleared messaging only on exit_for_api_error path | unverified | — | |
dailybot_cli/commands/public_api_helpers.py:1232 |
JSON 429 still ignores body retry_after now stored in extra | verified | — | |
dailybot_cli/commands/auth.py:195 |
login 429 path assumes detail is a str | verified | — | |
| ℹ️ info | dailybot_cli/api_client.py:891 |
Cleared session leaves self.token set | skipped | — |
| ℹ️ info | dailybot_cli/display.py:72 |
Empty Server response line when only code is set | skipped | — |
| ℹ️ info | dailybot_cli/commands/auth.py:335 |
Org picker now runs after click.prompt | skipped | — |
Summary
Verdict
Solid auth robustness work with strong tests, but the new session-ending path can delete credentials.json while a command still succeeds via API-key fallback, with no user-visible notice. Messaging for that wipe is only wired through exit_for_api_error, so several other 401 handlers stay quiet about it.
What works well
- Organization selection after verify-code matches the new server contract;
organization_uuidis optional and keeps the bare verify body byte-identical when omitted. - Compare-and-clear (
clear_credentials_if_current) is the right shape for concurrent CLI processes (covered by tests). - Login 429 handling (exit 6, server sentence + wait, no auto-retry, code never echoed) is clear and well tested.
org_cache.jsonTTL +saved_atis a safe Rule 16 additive change; writes still go through_write_secret_file(0o600).- Docs and the 39-test
login_robustness_test.pysuite pin the PLAN_006 answers.
Main concerns
- Silent session wipe on successful fallback (
_end_session_after_refusal): a refused refresh deletes the stored pair immediately. If an org/API key then answers the same request, the command exits 0 and never prints that login was removed. Dual-auth users (credentials.json+ key / env.json) hit this on ordinary commands, includingdailybot status --auth. - Incomplete surface of
session_cleared: onlyexit_for_api_errorcallsprint_sign_in_ended. Agent commands,update,status --auth, and interactive paths still catchAPIErrorthemselves after the client has already unlinked the file. - Body
retry_afteronly half-wired:_handle_responsenow copies top-levelretry_afterintoextra, and login usesretry_after_seconds(), butexit_for_api_errorJSON (and the unchanged human 429 branch) still read onlyAPIError.retry_afterfrom the header. error.detail.strip()on the login 429 path assumes a string;_handle_responsestill assignsbody["detail"]unchecked, so a list/object detail raisesAttributeErrorinstead of the fallback copy.
Residual risk / notes
- Interactive multi-org now prompts for the code before the org picker (required by the new contract). Numbered fallback covers
questionaryreturningNoneafterclick.prompt; broken TUI that does not returnNoneis still possible on some terminals. - Spurious bearer 401s (proxy/captive portal) will also clear a stored login. That matches the “ended session” goal but is aggressive.
Recommendation: request-changes
Check status: ✅ passing — strictness
block-on-critical, highest severity in effectwarning: highest severitywarning≤ critical threshold.This line is written by the reviewer runtime after the gate ran and matches the check conclusion and the tracking comment. Any recommendation above is the model's advisory opinion, not the gate.
| 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): |
There was a problem hiding this comment.
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).
| if not json_mode: | ||
| print_error(message) | ||
| print_sign_in_ended( |
There was a problem hiding this comment.
print_sign_in_ended is only invoked here. The client now unlinks the stored login on bearer 401 / refused refresh for every caller, but agent_error_message, update, status --auth, interactive, and several other except APIError blocks still print their own text and never read extra["session_cleared"] / server_detail.
Failure mode: user runs e.g. dailybot update or dailybot agent health on a revoked session, sees a generic auth error, and does not learn the saved sign-in was removed (or the server’s real reason after a refused refresh).
Fix options: centralize ended-session stderr in one helper used by every 401 path, or have those handlers call print_sign_in_ended the same way.
| 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) |
There was a problem hiding this comment.
This PR teaches _handle_response to copy a top-level body retry_after into extra (and login uses retry_after_seconds(), which reads it). The JSON envelope here still takes only exc.retry_after (header-derived). A 429 with body wait and no Retry-After header omits retry_after_seconds for machine consumers of exit_for_api_error.
The human 429 branch a few lines above has the same header-only gap (unchanged line, same fix).
| header_wait: float | None = getattr(exc, "retry_after", None) | |
| wait_secs: int | None = retry_after_seconds(exc) | |
| if exc.status_code == 429 and wait_secs is not None: | |
| payload["retry_after_seconds"] = wait_secs |
| 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)) |
There was a problem hiding this comment.
error.detail.strip() will raise AttributeError if detail is a list or object. DailyBotClient._handle_response still does detail = body.get("detail", …) with no str/isinstance coercion, so a non-string 429 body crashes before the otp_cooldown / LOGIN_RATE_LIMITED_FALLBACK copy can run.
| 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)) | |
| detail_text: str = error.detail if isinstance(error.detail, str) else "" | |
| fallback: str = ERROR_CODE_MESSAGES.get(error.code or "") or LOGIN_RATE_LIMITED_FALLBACK | |
| print_sign_in_refusal(detail_text.strip() or fallback, retry_after_seconds(error)) |
| self._session_end = error | ||
| if clear_credentials_if_current(self.api_url, refresh=refresh): |
There was a problem hiding this comment.
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.
| 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]") |
There was a problem hiding this comment.
When server_detail is missing/empty but code is set, this prints Server response: (some_code) with a blank reason. That can show up for hand-built APIErrors or paths that pass a code without extra["server_detail"].
Prefer printing the code alone when reason is empty, e.g. Server response: (code) or skip the reason segment.
| # Step 2: Enter the code (not shown while typing). | ||
| code: str = click.prompt("Enter the 6-digit code", type=str, hide_input=True) |
There was a problem hiding this comment.
Previously org selection ran before the code prompt specifically because click.prompt can break the questionary TUI afterward. The new server contract requires picking after verify-code, so this order is necessary. _prompt_org_selection still falls back to the numbered list when ask() returns None, which covers cancel/unrenderable cases; worth a quick manual check on a multi-org account in a plain SSH terminal so the fallback is what users actually hit when the TUI misbehaves.
|
Reviewed as part of the coordinated sign-in release. No changes needed: up to date with |
Summary
Email-code sign-in now picks the organization after the code is verified. Waits the server asks for are explained instead of shown as failures. A sign-in the server no longer accepts is cleared, with a clear prompt to log in again. Browser sign-in (
dailybot login --device) is unchanged, and so is the default login.Change Log
--org, sent asorganization_uuid, plusorganization_idwhen a recent cached list has it. The pick is a second call with the same code. Without--org, a multi-org account gets its organizations listed with the exact rerun command. An--orgthat is not offered shows the server's answer or the list. A repeated selection answer stops instead of looping.429from either sign-in door prints the server's sentence and the wait (retry_afterorRetry-After) and exits6. It never retries automatically and is never reported as a wrong code. Code-keyed fallback copy coversotp_cooldownandotp_attempts_exceeded.401to the stored login, or a refused renewal, the CLI shows the server's reason (Server response: …). It removes the saved sign-in when the file still holds the refused credential (compare-and-clear, so a session renewed by another terminal is kept) and asks fordailybot login.DAILYBOT_CLI_TOKENis never touched. An expired access token whose renewal failed without a refusal keeps its pair. JSON output addsserver_detailandsession_cleared.--code=CODE, never the code.org_cache.jsonstoressaved_atand is read for 10 minutes. Older files count as expired. It is removed after a successful login.Compatibility
organization_uuidis optional and sent only with--orgor after a pick. Without an organization, the verify body is byte-identical to before.credentials.jsonschema unchanged.org_cache.jsongainssaved_at, an added key (Rule 16).DEVICE_LOGIN_IS_DEFAULTunchanged.Tests
tests/login_robustness_test.py(39 tests): wire bodies, interactive and non-interactive organization selection on both server answers, 429 rendering and exit code, cache lifetime, and ended sessions (legacy bare 401, revoked access token, revoked or refused refresh, env token, a session rotated by another process).--orgwithout a cache, a refused renewal removes the pair).pytest,ruff check,ruff format --check,mypy dailybot_cli.Risks
🤖 Generated with Claude Code