Skip to content

fix(auth): login robustness and clearer sign-in errors - #157

Merged
xergioalex merged 3 commits into
mainfrom
security__plan006_cli_login
Nov 25, 2026
Merged

xergioalex merged 3 commits into
mainfrom
security__plan006_cli_login

Conversation

@xergioalex

Copy link
Copy Markdown
Member

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.

Release note for the API rollout: once the server lists organizations only after verification, non-interactive login for an account with several organizations (dailybot login --email … --code … --org …) needs this CLI release. Older CLIs still sign in interactively, and single-organization accounts work on every version.

Change Log

  • Organization after verification. The CLI no longer needs the organization list from the code request. When verify-code asks for a selection, the CLI shows the picker (interactive) or uses --org, sent as organization_uuid, plus organization_id when 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 --org that is not offered shows the server's answer or the list. A repeated selection answer stops instead of looping.
  • Clearer waits. A 429 from either sign-in door prints the server's sentence and the wait (retry_after or Retry-After) and exits 6. It never retries automatically and is never reported as a wrong code. Code-keyed fallback copy covers otp_cooldown and otp_attempts_exceeded.
  • Ended sign-ins. After a final 401 to 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 for dailybot login. DAILYBOT_CLI_TOKEN is never touched. An expired access token whose renewal failed without a refusal keeps its pair. JSON output adds server_detail and session_cleared.
  • The code stays off the screen. It is hidden while typing, and next-step hints print --code=CODE, never the code.
  • Short-lived organization cache. org_cache.json stores saved_at and is read for 10 minutes. Older files count as expired. It is removed after a successful login.
  • Docs: API reference, architecture, configuration, troubleshooting.

Compatibility

  • It works against both server answers to the code request (organizations listed, or an empty list).
  • organization_uuid is optional and sent only with --org or after a pick. Without an organization, the verify body is byte-identical to before.
  • credentials.json schema unchanged. org_cache.json gains saved_at, an added key (Rule 16).
  • DEVICE_LOGIN_IS_DEFAULT unchanged.

Tests

  • New 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).
  • Existing login and refresh tests updated where the behaviour intentionally changed (pick after the code, --org without a cache, a refused renewal removes the pair).
  • pytest, ruff check, ruff format --check, mypy dailybot_cli.

Risks

  • An interactive multi-org login now picks the organization after the code prompt. The numbered fallback covers terminals where the arrow-key picker does not render.
  • A refused renewal followed by a working API key removes the saved sign-in without printing anything, because the command itself succeeded.

🤖 Generated with Claude Code

xergioalexpro and others added 3 commits November 24, 2026 15:58
## 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]>
@xergioalex xergioalex added the Ready Trigger AI code review label Nov 24, 2026
@github-actions

This comment has been minimized.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

AI review for f1507dd — ✅ done

View review →

Highest severity: warning

Verifier: 4 checked · 2 verified · 0 downgraded · 0 refuted · 2 unverified · 3 skipped — grok-4.5 (economy), 49s

Strictness gate: ✅ highest severity warning ≤ critical threshold

7 inline comment(s) attached.

Usage: 1608.3k in (93% cached) · 24.1k out · est. $0.83 · 19 turns · 393s

Iteration-Aware Review: gen 1, round 1, policy=first-pass-exhaustive (first_review) — 7 surfaced.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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
⚠️ warning dailybot_cli/api_client.py:891 Silent credentials wipe when API-key fallback succeeds unverified —
⚠️ warning dailybot_cli/commands/public_api_helpers.py:1186 session_cleared messaging only on exit_for_api_error path unverified —
⚠️ warning dailybot_cli/commands/public_api_helpers.py:1232 JSON 429 still ignores body retry_after now stored in extra verified —
⚠️ warning 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_uuid is 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.json TTL + saved_at is a safe Rule 16 additive change; writes still go through _write_secret_file (0o600).
  • Docs and the 39-test login_robustness_test.py suite pin the PLAN_006 answers.

Main concerns

  1. 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, including dailybot status --auth.
  2. Incomplete surface of session_cleared: only exit_for_api_error calls print_sign_in_ended. Agent commands, update, status --auth, and interactive paths still catch APIError themselves after the client has already unlinked the file.
  3. Body retry_after only half-wired: _handle_response now copies top-level retry_after into extra, and login uses retry_after_seconds(), but exit_for_api_error JSON (and the unchanged human 429 branch) still read only APIError.retry_after from the header.
  4. error.detail.strip() on the login 429 path assumes a string; _handle_response still assigns body["detail"] unchecked, so a list/object detail raises AttributeError instead 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 questionary returning None after click.prompt; broken TUI that does not return None is 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 effect warning: highest severity warning ≤ 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.

Comment on lines +884 to +891
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):

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 +1184 to +1186
if not json_mode:
print_error(message)
print_sign_in_ended(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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).

Suggested change
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

Comment on lines +193 to +195
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Suggested change
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))

Comment on lines +890 to +891
self._session_end = error
if clear_credentials_if_current(self.api_url, refresh=refresh):

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.

Comment thread dailybot_cli/display.py
Comment on lines +67 to +72
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]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

Comment on lines +334 to +335
# Step 2: Enter the code (not shown while typing).
code: str = click.prompt("Enter the 6-digit code", type=str, hide_input=True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@github-actions github-actions Bot added the pr-reviewed Passed AI code review label Nov 24, 2026
@oscarmarin621

Copy link
Copy Markdown
Contributor

Reviewed as part of the coordinated sign-in release. No changes needed: up to date with main, all checks green. Release order: publish this CLI before the server stops listing organizations on the code request, so non-interactive multi-organization logins (--org) keep working.

@xergioalex
xergioalex merged commit 718cd2c into main Nov 25, 2026
10 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-reviewed Passed AI code review Ready Trigger AI code review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants