From 43520d794346d06cb13600d2b7c29af758818182 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 13:46:55 +0000 Subject: [PATCH 01/19] test(tests): record the device-flow and standalone wire fixtures ## Summary One recorded response per new door and state (device start, every device-token state, the token pair body, refresh failures, the session 401 codes, the defensive 503, the deprecation field, org selection, /v1/organization/ with and without chat platforms and plan, and the channel-reference codes), plus a drift test against the frozen record. ## Change Log - tests/fixtures/device_flow/*.json: {door, status, headers, body}, fake ids only - tests/wire_fixture_loader.py: load_fixture / fixture_body / fixture_response - tests/wire_fixtures_test.py: shape, frozen values and no-real-identifier checks - docs/TESTING_GUIDE.md: fixtures location ## Risks - None: test data only Co-Authored-By: Claude Opus 5.5 --- docs/TESTING_GUIDE.md | 4 + .../auth_backend_unavailable_503.json | 11 + .../bearer_access_token_expired_401.json | 9 + .../bearer_invalid_credentials_401.json | 9 + .../bearer_session_revoked_401.json | 9 + .../device_flow/bearer_user_disabled_401.json | 9 + .../channel_reference_ambiguous_409.json | 9 + .../channel_reference_unknown_400.json | 9 + .../device_flow/device_start_200.json | 13 ++ .../device_start_invalid_client_400.json | 10 + .../device_start_method_not_allowed_405.json | 8 + .../device_start_not_found_404.json | 8 + .../device_token_access_denied_400.json | 10 + ...evice_token_authorization_pending_400.json | 10 + .../device_token_expired_token_400.json | 10 + .../device_token_invalid_client_400.json | 10 + .../device_token_invalid_grant_400.json | 10 + .../device_token_slow_down_400.json | 11 + .../device_flow/device_token_success_200.json | 28 +++ tests/fixtures/device_flow/logout_200.json | 8 + ...ganization_chat_platforms_no_plan_200.json | 44 ++++ .../device_flow/organization_legacy_200.json | 15 ++ .../device_flow/organization_native_200.json | 49 ++++ .../refresh_refresh_token_expired_401.json | 9 + .../refresh_session_revoked_401.json | 9 + .../device_flow/refresh_success_200.json | 28 +++ .../refresh_user_disabled_401.json | 9 + .../request_code_deprecation_200.json | 18 ++ ...nd_message_platform_not_connected_400.json | 9 + .../verify_code_deprecation_200.json | 23 ++ .../verify_code_deprecation_400.json | 18 ++ .../device_flow/verify_code_legacy_200.json | 13 ++ .../verify_code_org_selection_200.json | 22 ++ tests/wire_fixture_loader.py | 37 +++ tests/wire_fixtures_test.py | 218 ++++++++++++++++++ 35 files changed, 726 insertions(+) create mode 100644 tests/fixtures/device_flow/auth_backend_unavailable_503.json create mode 100644 tests/fixtures/device_flow/bearer_access_token_expired_401.json create mode 100644 tests/fixtures/device_flow/bearer_invalid_credentials_401.json create mode 100644 tests/fixtures/device_flow/bearer_session_revoked_401.json create mode 100644 tests/fixtures/device_flow/bearer_user_disabled_401.json create mode 100644 tests/fixtures/device_flow/channel_reference_ambiguous_409.json create mode 100644 tests/fixtures/device_flow/channel_reference_unknown_400.json create mode 100644 tests/fixtures/device_flow/device_start_200.json create mode 100644 tests/fixtures/device_flow/device_start_invalid_client_400.json create mode 100644 tests/fixtures/device_flow/device_start_method_not_allowed_405.json create mode 100644 tests/fixtures/device_flow/device_start_not_found_404.json create mode 100644 tests/fixtures/device_flow/device_token_access_denied_400.json create mode 100644 tests/fixtures/device_flow/device_token_authorization_pending_400.json create mode 100644 tests/fixtures/device_flow/device_token_expired_token_400.json create mode 100644 tests/fixtures/device_flow/device_token_invalid_client_400.json create mode 100644 tests/fixtures/device_flow/device_token_invalid_grant_400.json create mode 100644 tests/fixtures/device_flow/device_token_slow_down_400.json create mode 100644 tests/fixtures/device_flow/device_token_success_200.json create mode 100644 tests/fixtures/device_flow/logout_200.json create mode 100644 tests/fixtures/device_flow/organization_chat_platforms_no_plan_200.json create mode 100644 tests/fixtures/device_flow/organization_legacy_200.json create mode 100644 tests/fixtures/device_flow/organization_native_200.json create mode 100644 tests/fixtures/device_flow/refresh_refresh_token_expired_401.json create mode 100644 tests/fixtures/device_flow/refresh_session_revoked_401.json create mode 100644 tests/fixtures/device_flow/refresh_success_200.json create mode 100644 tests/fixtures/device_flow/refresh_user_disabled_401.json create mode 100644 tests/fixtures/device_flow/request_code_deprecation_200.json create mode 100644 tests/fixtures/device_flow/send_message_platform_not_connected_400.json create mode 100644 tests/fixtures/device_flow/verify_code_deprecation_200.json create mode 100644 tests/fixtures/device_flow/verify_code_deprecation_400.json create mode 100644 tests/fixtures/device_flow/verify_code_legacy_200.json create mode 100644 tests/fixtures/device_flow/verify_code_org_selection_200.json create mode 100644 tests/wire_fixture_loader.py create mode 100644 tests/wire_fixtures_test.py diff --git a/docs/TESTING_GUIDE.md b/docs/TESTING_GUIDE.md index 7981734d..45762f2b 100644 --- a/docs/TESTING_GUIDE.md +++ b/docs/TESTING_GUIDE.md @@ -78,6 +78,10 @@ tests/ ├── milestones_updates_test.py # milestone files/restore; project update detail, edit, delete, files ├── tasks_parent_attachments_test.py # attachments on comments, projects and goals (5 MiB, admin doors) ├── tasks_ai_review_fixes_test.py # AI review round 1: bulk preview shape, ETag grammar, ports, streamed download +├── wire_fixtures_test.py # recorded device-flow / standalone wire fixtures match the frozen record +├── wire_fixture_loader.py # load_fixture / fixture_body / fixture_response (mocked httpx.Response) +├── fixtures/device_flow/*.json # one recorded response per door and state: {door, status, headers, body}; +│ # fake identifiers only (00000000-0000-4000-8000-… uuids, @example.com) ├── tasks_inbox_filters_test.py # inbox --mentioned / --type on the list and the unread badge ├── tasks_favorites_views_test.py # board/view star|unstar (R3a), saved view get/update/delete (R3d) ├── tasks_ergonomics_sweep_test.py # walks every Tasks command: --json, example, TASK metavar, --dry-run diff --git a/tests/fixtures/device_flow/auth_backend_unavailable_503.json b/tests/fixtures/device_flow/auth_backend_unavailable_503.json new file mode 100644 index 00000000..48291385 --- /dev/null +++ b/tests/fixtures/device_flow/auth_backend_unavailable_503.json @@ -0,0 +1,11 @@ +{ + "door": "web-session doors (defensive)", + "status": 503, + "headers": { + "Retry-After": "2" + }, + "body": { + "detail": "Authentication is temporarily unavailable.", + "code": "auth_backend_unavailable" + } +} diff --git a/tests/fixtures/device_flow/bearer_access_token_expired_401.json b/tests/fixtures/device_flow/bearer_access_token_expired_401.json new file mode 100644 index 00000000..a76a4c42 --- /dev/null +++ b/tests/fixtures/device_flow/bearer_access_token_expired_401.json @@ -0,0 +1,9 @@ +{ + "door": "ANY /v1/* with Bearer dbc_at_", + "status": 401, + "headers": {}, + "body": { + "detail": "Example detail for access_token_expired.", + "code": "access_token_expired" + } +} diff --git a/tests/fixtures/device_flow/bearer_invalid_credentials_401.json b/tests/fixtures/device_flow/bearer_invalid_credentials_401.json new file mode 100644 index 00000000..24f17a76 --- /dev/null +++ b/tests/fixtures/device_flow/bearer_invalid_credentials_401.json @@ -0,0 +1,9 @@ +{ + "door": "ANY /v1/* with Bearer dbc_at_", + "status": 401, + "headers": {}, + "body": { + "detail": "Example detail for invalid_credentials.", + "code": "invalid_credentials" + } +} diff --git a/tests/fixtures/device_flow/bearer_session_revoked_401.json b/tests/fixtures/device_flow/bearer_session_revoked_401.json new file mode 100644 index 00000000..e584dddc --- /dev/null +++ b/tests/fixtures/device_flow/bearer_session_revoked_401.json @@ -0,0 +1,9 @@ +{ + "door": "ANY /v1/* with Bearer dbc_at_", + "status": 401, + "headers": {}, + "body": { + "detail": "Example detail for session_revoked.", + "code": "session_revoked" + } +} diff --git a/tests/fixtures/device_flow/bearer_user_disabled_401.json b/tests/fixtures/device_flow/bearer_user_disabled_401.json new file mode 100644 index 00000000..97319c76 --- /dev/null +++ b/tests/fixtures/device_flow/bearer_user_disabled_401.json @@ -0,0 +1,9 @@ +{ + "door": "ANY /v1/* with Bearer dbc_at_", + "status": 401, + "headers": {}, + "body": { + "detail": "Example detail for user_disabled.", + "code": "user_disabled" + } +} diff --git a/tests/fixtures/device_flow/channel_reference_ambiguous_409.json b/tests/fixtures/device_flow/channel_reference_ambiguous_409.json new file mode 100644 index 00000000..99d5558f --- /dev/null +++ b/tests/fixtures/device_flow/channel_reference_ambiguous_409.json @@ -0,0 +1,9 @@ +{ + "door": "POST /v1/send-message/", + "status": 409, + "headers": {}, + "body": { + "detail": "More than one installation matches.", + "code": "channel_reference_ambiguous" + } +} diff --git a/tests/fixtures/device_flow/channel_reference_unknown_400.json b/tests/fixtures/device_flow/channel_reference_unknown_400.json new file mode 100644 index 00000000..06838fd1 --- /dev/null +++ b/tests/fixtures/device_flow/channel_reference_unknown_400.json @@ -0,0 +1,9 @@ +{ + "door": "POST /v1/send-message/", + "status": 400, + "headers": {}, + "body": { + "detail": "Unknown platform or installation.", + "code": "channel_reference_unknown" + } +} diff --git a/tests/fixtures/device_flow/device_start_200.json b/tests/fixtures/device_flow/device_start_200.json new file mode 100644 index 00000000..9ed48c47 --- /dev/null +++ b/tests/fixtures/device_flow/device_start_200.json @@ -0,0 +1,13 @@ +{ + "door": "POST /v1/cli/auth/device/", + "status": 200, + "headers": {}, + "body": { + "device_code": "fake-device-code-00000000000000000000000000", + "user_code": "BCDF-GHJK", + "verification_uri": "https://app.example.com/auth/device", + "verification_uri_complete": "https://app.example.com/auth/device?user_code=BCDF-GHJK", + "expires_in": 600, + "interval": 5 + } +} diff --git a/tests/fixtures/device_flow/device_start_invalid_client_400.json b/tests/fixtures/device_flow/device_start_invalid_client_400.json new file mode 100644 index 00000000..de832dc8 --- /dev/null +++ b/tests/fixtures/device_flow/device_start_invalid_client_400.json @@ -0,0 +1,10 @@ +{ + "door": "POST /v1/cli/auth/device/", + "status": 400, + "headers": {}, + "body": { + "error": "invalid_client", + "code": "invalid_client", + "detail": "Example detail for invalid_client." + } +} diff --git a/tests/fixtures/device_flow/device_start_method_not_allowed_405.json b/tests/fixtures/device_flow/device_start_method_not_allowed_405.json new file mode 100644 index 00000000..f404387d --- /dev/null +++ b/tests/fixtures/device_flow/device_start_method_not_allowed_405.json @@ -0,0 +1,8 @@ +{ + "door": "POST /v1/cli/auth/device/", + "status": 405, + "headers": {}, + "body": { + "detail": "Method \"POST\" not allowed." + } +} diff --git a/tests/fixtures/device_flow/device_start_not_found_404.json b/tests/fixtures/device_flow/device_start_not_found_404.json new file mode 100644 index 00000000..87e185a3 --- /dev/null +++ b/tests/fixtures/device_flow/device_start_not_found_404.json @@ -0,0 +1,8 @@ +{ + "door": "POST /v1/cli/auth/device/", + "status": 404, + "headers": {}, + "body": { + "detail": "Not found." + } +} diff --git a/tests/fixtures/device_flow/device_token_access_denied_400.json b/tests/fixtures/device_flow/device_token_access_denied_400.json new file mode 100644 index 00000000..2ecae3c9 --- /dev/null +++ b/tests/fixtures/device_flow/device_token_access_denied_400.json @@ -0,0 +1,10 @@ +{ + "door": "POST /v1/cli/auth/device/token/", + "status": 400, + "headers": {}, + "body": { + "error": "access_denied", + "code": "access_denied", + "detail": "Example detail for access_denied." + } +} diff --git a/tests/fixtures/device_flow/device_token_authorization_pending_400.json b/tests/fixtures/device_flow/device_token_authorization_pending_400.json new file mode 100644 index 00000000..ab2e496a --- /dev/null +++ b/tests/fixtures/device_flow/device_token_authorization_pending_400.json @@ -0,0 +1,10 @@ +{ + "door": "POST /v1/cli/auth/device/token/", + "status": 400, + "headers": {}, + "body": { + "error": "authorization_pending", + "code": "authorization_pending", + "detail": "Example detail for authorization_pending." + } +} diff --git a/tests/fixtures/device_flow/device_token_expired_token_400.json b/tests/fixtures/device_flow/device_token_expired_token_400.json new file mode 100644 index 00000000..b4535dba --- /dev/null +++ b/tests/fixtures/device_flow/device_token_expired_token_400.json @@ -0,0 +1,10 @@ +{ + "door": "POST /v1/cli/auth/device/token/", + "status": 400, + "headers": {}, + "body": { + "error": "expired_token", + "code": "expired_token", + "detail": "Example detail for expired_token." + } +} diff --git a/tests/fixtures/device_flow/device_token_invalid_client_400.json b/tests/fixtures/device_flow/device_token_invalid_client_400.json new file mode 100644 index 00000000..25b2f6c4 --- /dev/null +++ b/tests/fixtures/device_flow/device_token_invalid_client_400.json @@ -0,0 +1,10 @@ +{ + "door": "POST /v1/cli/auth/device/token/", + "status": 400, + "headers": {}, + "body": { + "error": "invalid_client", + "code": "invalid_client", + "detail": "Example detail for invalid_client." + } +} diff --git a/tests/fixtures/device_flow/device_token_invalid_grant_400.json b/tests/fixtures/device_flow/device_token_invalid_grant_400.json new file mode 100644 index 00000000..bf863089 --- /dev/null +++ b/tests/fixtures/device_flow/device_token_invalid_grant_400.json @@ -0,0 +1,10 @@ +{ + "door": "POST /v1/cli/auth/device/token/", + "status": 400, + "headers": {}, + "body": { + "error": "invalid_grant", + "code": "invalid_grant", + "detail": "Example detail for invalid_grant." + } +} diff --git a/tests/fixtures/device_flow/device_token_slow_down_400.json b/tests/fixtures/device_flow/device_token_slow_down_400.json new file mode 100644 index 00000000..e8804b27 --- /dev/null +++ b/tests/fixtures/device_flow/device_token_slow_down_400.json @@ -0,0 +1,11 @@ +{ + "door": "POST /v1/cli/auth/device/token/", + "status": 400, + "headers": {}, + "body": { + "error": "slow_down", + "code": "slow_down", + "detail": "Example detail for slow_down.", + "interval": 10 + } +} diff --git a/tests/fixtures/device_flow/device_token_success_200.json b/tests/fixtures/device_flow/device_token_success_200.json new file mode 100644 index 00000000..9e15d74d --- /dev/null +++ b/tests/fixtures/device_flow/device_token_success_200.json @@ -0,0 +1,28 @@ +{ + "door": "POST /v1/cli/auth/device/token/", + "status": 200, + "headers": {}, + "body": { + "token_type": "Bearer", + "access": "dbc_at_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "expires_at": "2030-01-01T01:00:00Z", + "refresh": "dbc_rt_rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr", + "refresh_expires_at": "2030-04-01T00:00:00Z", + "user": { + "uuid": "00000000-0000-4000-8000-000000000010", + "email": "me@example.com", + "full_name": "Jane Doe" + }, + "organization": { + "id": 202, + "uuid": "00000000-0000-4000-8000-000000000002", + "name": "My Team", + "platform": "dailybot", + "plan": { + "tier": "free", + "effective_tier": "startup", + "is_trial": true + } + } + } +} diff --git a/tests/fixtures/device_flow/logout_200.json b/tests/fixtures/device_flow/logout_200.json new file mode 100644 index 00000000..edf4a6fa --- /dev/null +++ b/tests/fixtures/device_flow/logout_200.json @@ -0,0 +1,8 @@ +{ + "door": "POST /v1/cli/auth/logout/", + "status": 200, + "headers": {}, + "body": { + "detail": "Successfully logged out." + } +} diff --git a/tests/fixtures/device_flow/organization_chat_platforms_no_plan_200.json b/tests/fixtures/device_flow/organization_chat_platforms_no_plan_200.json new file mode 100644 index 00000000..36e74212 --- /dev/null +++ b/tests/fixtures/device_flow/organization_chat_platforms_no_plan_200.json @@ -0,0 +1,44 @@ +{ + "door": "GET /v1/organization/", + "status": 200, + "headers": {}, + "body": { + "uuid": "00000000-0000-4000-8000-000000000001", + "name": "My Team", + "timezone": "UTC", + "image": null, + "platform": "slack", + "chat_platform_data": {}, + "supported_domains": [], + "has_email_password_enabled": false, + "has_external_chat_platform": true, + "primary_chat_platform": { + "id": "00000000-0000-4000-8000-000000000021", + "platform": "slack", + "display_name": "My Team Slack", + "organization_external_id": "T00000000", + "is_primary": true, + "status": "connected", + "capabilities": { + "directory": true, + "reporting": true, + "direct_messages": true + } + }, + "chat_platforms": [ + { + "id": "00000000-0000-4000-8000-000000000021", + "platform": "slack", + "display_name": "My Team Slack", + "organization_external_id": "T00000000", + "is_primary": true, + "status": "connected", + "capabilities": { + "directory": true, + "reporting": true, + "direct_messages": true + } + } + ] + } +} diff --git a/tests/fixtures/device_flow/organization_legacy_200.json b/tests/fixtures/device_flow/organization_legacy_200.json new file mode 100644 index 00000000..1326f929 --- /dev/null +++ b/tests/fixtures/device_flow/organization_legacy_200.json @@ -0,0 +1,15 @@ +{ + "door": "GET /v1/organization/", + "status": 200, + "headers": {}, + "body": { + "uuid": "00000000-0000-4000-8000-000000000001", + "name": "My Team", + "timezone": "UTC", + "image": null, + "platform": "slack", + "chat_platform_data": {}, + "supported_domains": [], + "has_email_password_enabled": false + } +} diff --git a/tests/fixtures/device_flow/organization_native_200.json b/tests/fixtures/device_flow/organization_native_200.json new file mode 100644 index 00000000..6c3a4eca --- /dev/null +++ b/tests/fixtures/device_flow/organization_native_200.json @@ -0,0 +1,49 @@ +{ + "door": "GET /v1/organization/", + "status": 200, + "headers": {}, + "body": { + "uuid": "00000000-0000-4000-8000-000000000002", + "name": "My Team", + "timezone": "UTC", + "image": null, + "platform": "dailybot", + "chat_platform_data": {}, + "supported_domains": [], + "has_email_password_enabled": false, + "has_external_chat_platform": false, + "primary_chat_platform": { + "id": "00000000-0000-4000-8000-000000000020", + "platform": "dailybot", + "display_name": "My Team", + "organization_external_id": null, + "is_primary": true, + "status": "connected", + "capabilities": { + "directory": true, + "reporting": true, + "direct_messages": true + } + }, + "chat_platforms": [ + { + "id": "00000000-0000-4000-8000-000000000020", + "platform": "dailybot", + "display_name": "My Team", + "organization_external_id": null, + "is_primary": true, + "status": "connected", + "capabilities": { + "directory": true, + "reporting": true, + "direct_messages": true + } + } + ], + "plan": { + "tier": "free", + "effective_tier": "free", + "is_trial": false + } + } +} diff --git a/tests/fixtures/device_flow/refresh_refresh_token_expired_401.json b/tests/fixtures/device_flow/refresh_refresh_token_expired_401.json new file mode 100644 index 00000000..9f656ee4 --- /dev/null +++ b/tests/fixtures/device_flow/refresh_refresh_token_expired_401.json @@ -0,0 +1,9 @@ +{ + "door": "POST /v1/cli/auth/refresh/", + "status": 401, + "headers": {}, + "body": { + "detail": "Example detail for refresh_token_expired.", + "code": "refresh_token_expired" + } +} diff --git a/tests/fixtures/device_flow/refresh_session_revoked_401.json b/tests/fixtures/device_flow/refresh_session_revoked_401.json new file mode 100644 index 00000000..82db0423 --- /dev/null +++ b/tests/fixtures/device_flow/refresh_session_revoked_401.json @@ -0,0 +1,9 @@ +{ + "door": "POST /v1/cli/auth/refresh/", + "status": 401, + "headers": {}, + "body": { + "detail": "Example detail for session_revoked.", + "code": "session_revoked" + } +} diff --git a/tests/fixtures/device_flow/refresh_success_200.json b/tests/fixtures/device_flow/refresh_success_200.json new file mode 100644 index 00000000..43ee5890 --- /dev/null +++ b/tests/fixtures/device_flow/refresh_success_200.json @@ -0,0 +1,28 @@ +{ + "door": "POST /v1/cli/auth/refresh/", + "status": 200, + "headers": {}, + "body": { + "token_type": "Bearer", + "access": "dbc_at_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "expires_at": "2030-01-01T01:00:00Z", + "refresh": "dbc_rt_sssssssssssssssssssssssssssssssssssssssssss", + "refresh_expires_at": "2030-04-01T00:00:00Z", + "user": { + "uuid": "00000000-0000-4000-8000-000000000010", + "email": "me@example.com", + "full_name": "Jane Doe" + }, + "organization": { + "id": 202, + "uuid": "00000000-0000-4000-8000-000000000002", + "name": "My Team", + "platform": "dailybot", + "plan": { + "tier": "free", + "effective_tier": "startup", + "is_trial": true + } + } + } +} diff --git a/tests/fixtures/device_flow/refresh_user_disabled_401.json b/tests/fixtures/device_flow/refresh_user_disabled_401.json new file mode 100644 index 00000000..e0352244 --- /dev/null +++ b/tests/fixtures/device_flow/refresh_user_disabled_401.json @@ -0,0 +1,9 @@ +{ + "door": "POST /v1/cli/auth/refresh/", + "status": 401, + "headers": {}, + "body": { + "detail": "Example detail for user_disabled.", + "code": "user_disabled" + } +} diff --git a/tests/fixtures/device_flow/request_code_deprecation_200.json b/tests/fixtures/device_flow/request_code_deprecation_200.json new file mode 100644 index 00000000..40f201df --- /dev/null +++ b/tests/fixtures/device_flow/request_code_deprecation_200.json @@ -0,0 +1,18 @@ +{ + "door": "POST /v1/cli/auth/request-code/", + "status": 200, + "headers": { + "Deprecation": "true", + "Sunset": "Wed, 31 Mar 2027 00:00:00 GMT", + "Link": "; rel=\"deprecation\"" + }, + "body": { + "detail": "Verification code sent.", + "deprecation": { + "code": "cli_auth_deprecated", + "min_version": "3.29.0", + "sunset": "2027-03-31", + "detail": "This sign-in method is being retired. Update the Dailybot CLI to 3.29.0 or later and run `dailybot login`." + } + } +} diff --git a/tests/fixtures/device_flow/send_message_platform_not_connected_400.json b/tests/fixtures/device_flow/send_message_platform_not_connected_400.json new file mode 100644 index 00000000..986744da --- /dev/null +++ b/tests/fixtures/device_flow/send_message_platform_not_connected_400.json @@ -0,0 +1,9 @@ +{ + "door": "POST /v1/send-message/", + "status": 400, + "headers": {}, + "body": { + "detail": "Connect a chat platform first.", + "code": "platform_not_connected" + } +} diff --git a/tests/fixtures/device_flow/verify_code_deprecation_200.json b/tests/fixtures/device_flow/verify_code_deprecation_200.json new file mode 100644 index 00000000..4c6256fc --- /dev/null +++ b/tests/fixtures/device_flow/verify_code_deprecation_200.json @@ -0,0 +1,23 @@ +{ + "door": "POST /v1/cli/auth/verify-code/", + "status": 200, + "headers": { + "Deprecation": "true", + "Sunset": "Wed, 31 Mar 2027 00:00:00 GMT", + "Link": "; rel=\"deprecation\"" + }, + "body": { + "token": "legacy-test-token", + "organization": { + "id": 101, + "name": "My Team", + "uuid": "00000000-0000-4000-8000-000000000001" + }, + "deprecation": { + "code": "cli_auth_deprecated", + "min_version": "3.29.0", + "sunset": "2027-03-31", + "detail": "This sign-in method is being retired. Update the Dailybot CLI to 3.29.0 or later and run `dailybot login`." + } + } +} diff --git a/tests/fixtures/device_flow/verify_code_deprecation_400.json b/tests/fixtures/device_flow/verify_code_deprecation_400.json new file mode 100644 index 00000000..71f7bda2 --- /dev/null +++ b/tests/fixtures/device_flow/verify_code_deprecation_400.json @@ -0,0 +1,18 @@ +{ + "door": "POST /v1/cli/auth/verify-code/", + "status": 400, + "headers": { + "Deprecation": "true", + "Sunset": "Wed, 31 Mar 2027 00:00:00 GMT", + "Link": "; rel=\"deprecation\"" + }, + "body": { + "detail": "Invalid or expired code.", + "deprecation": { + "code": "cli_auth_deprecated", + "min_version": "3.29.0", + "sunset": "2027-03-31", + "detail": "This sign-in method is being retired. Update the Dailybot CLI to 3.29.0 or later and run `dailybot login`." + } + } +} diff --git a/tests/fixtures/device_flow/verify_code_legacy_200.json b/tests/fixtures/device_flow/verify_code_legacy_200.json new file mode 100644 index 00000000..cb86ed78 --- /dev/null +++ b/tests/fixtures/device_flow/verify_code_legacy_200.json @@ -0,0 +1,13 @@ +{ + "door": "POST /v1/cli/auth/verify-code/", + "status": 200, + "headers": {}, + "body": { + "token": "legacy-test-token", + "organization": { + "id": 101, + "name": "My Team", + "uuid": "00000000-0000-4000-8000-000000000001" + } + } +} diff --git a/tests/fixtures/device_flow/verify_code_org_selection_200.json b/tests/fixtures/device_flow/verify_code_org_selection_200.json new file mode 100644 index 00000000..69d71c26 --- /dev/null +++ b/tests/fixtures/device_flow/verify_code_org_selection_200.json @@ -0,0 +1,22 @@ +{ + "door": "POST /v1/cli/auth/verify-code/", + "status": 200, + "headers": {}, + "body": { + "requires_organization_selection": true, + "organizations": [ + { + "id": 101, + "name": "My Team (Slack)", + "uuid": "00000000-0000-4000-8000-000000000001" + }, + { + "id": 202, + "name": "My Team", + "uuid": "00000000-0000-4000-8000-000000000002", + "platform": "dailybot", + "standalone": true + } + ] + } +} diff --git a/tests/wire_fixture_loader.py b/tests/wire_fixture_loader.py new file mode 100644 index 00000000..7d5dbe9b --- /dev/null +++ b/tests/wire_fixture_loader.py @@ -0,0 +1,37 @@ +"""Load the recorded device-flow and standalone wire fixtures. + +Every fixture under ``tests/fixtures/device_flow/`` is one recorded response: +``{"door", "status", "headers", "body"}``. Tests build mocked ``httpx`` +responses from these files so a wire body has exactly one source. +""" + +import json +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock + +FIXTURES_DIR: Path = Path(__file__).parent / "fixtures" / "device_flow" + + +def load_fixture(name: str) -> dict[str, Any]: + """Return the whole recorded fixture (door, status, headers, body).""" + data: dict[str, Any] = json.loads((FIXTURES_DIR / f"{name}.json").read_text()) + return data + + +def fixture_body(name: str) -> dict[str, Any]: + """Return only the recorded JSON body.""" + body: dict[str, Any] = load_fixture(name)["body"] + return body + + +def fixture_response(name: str) -> MagicMock: + """Build a mocked ``httpx.Response`` that replays the recorded fixture.""" + recorded: dict[str, Any] = load_fixture(name) + response: MagicMock = MagicMock() + response.status_code = recorded["status"] + response.is_success = 200 <= recorded["status"] < 300 + response.headers = dict(recorded["headers"]) + response.json.return_value = recorded["body"] + response.text = json.dumps(recorded["body"]) + return response diff --git a/tests/wire_fixtures_test.py b/tests/wire_fixtures_test.py new file mode 100644 index 00000000..4bb3cb71 --- /dev/null +++ b/tests/wire_fixtures_test.py @@ -0,0 +1,218 @@ +"""The recorded wire fixtures match the checkpoint-1 frozen wire values. + +A fixture that drifts from the frozen record fails here, before any test +built on it can pass against a wrong body. +""" + +import json +import re +from pathlib import Path +from typing import Any + +import pytest + +from tests.wire_fixture_loader import FIXTURES_DIR, fixture_body, load_fixture + +USER_CODE_PATTERN: re.Pattern[str] = re.compile( + r"^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$" +) +UUID_PATTERN: re.Pattern[str] = re.compile( + r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" +) +TOKEN_ERROR_CODES: tuple[str, ...] = ( + "authorization_pending", + "slow_down", + "access_denied", + "expired_token", + "invalid_grant", + "invalid_client", +) +CHAT_PLATFORM_SUMMARY_KEYS: tuple[str, ...] = ( + "id", + "platform", + "display_name", + "organization_external_id", + "is_primary", + "status", + "capabilities", +) +CHAT_PLATFORMS: set[str] = {"dailybot", "slack", "msteams", "discord", "hangouts"} +TOKEN_BODY_KEYS: set[str] = { + "token_type", + "access", + "expires_at", + "refresh", + "refresh_expires_at", + "user", + "organization", +} + + +def _all_fixtures() -> list[Path]: + return sorted(FIXTURES_DIR.glob("*.json")) + + +class TestEveryFixture: + def test_the_folder_is_not_empty(self) -> None: + assert len(_all_fixtures()) >= 30 + + @pytest.mark.parametrize("path", _all_fixtures(), ids=lambda p: p.stem) + def test_the_recorded_shape(self, path: Path) -> None: + data: dict[str, Any] = json.loads(path.read_text()) + assert set(data) == {"door", "status", "headers", "body"} + assert isinstance(data["status"], int) + assert isinstance(data["body"], dict) + + @pytest.mark.parametrize("path", _all_fixtures(), ids=lambda p: p.stem) + def test_no_real_identifiers(self, path: Path) -> None: + text: str = path.read_text() + for uuid in re.findall( + r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", text + ): + assert uuid.startswith("00000000-0000-4000-8000-"), uuid + for email in re.findall(r"[\w.+-]+@[\w-]+\.[\w.]+", text): + assert email.endswith("@example.com"), email + assert "dailybot.com" not in text + + +class TestDeviceStart: + def test_the_start_body(self) -> None: + body: dict[str, Any] = fixture_body("device_start_200") + assert len(body["device_code"]) == 43 + assert USER_CODE_PATTERN.match(body["user_code"]) + assert body["verification_uri"].endswith("/auth/device") + assert body["verification_uri_complete"].endswith(f"?user_code={body['user_code']}") + assert body["expires_in"] == 600 + assert body["interval"] == 5 + + @pytest.mark.parametrize( + "name,status", + [ + ("device_start_not_found_404", 404), + ("device_start_method_not_allowed_405", 405), + ], + ) + def test_an_old_server(self, name: str, status: int) -> None: + assert load_fixture(name)["status"] == status + + +class TestDeviceToken: + @pytest.mark.parametrize("code", TOKEN_ERROR_CODES) + def test_every_state_is_a_400_with_error_equal_to_code(self, code: str) -> None: + recorded: dict[str, Any] = load_fixture(f"device_token_{code}_400") + assert recorded["status"] == 400 + assert recorded["body"]["error"] == recorded["body"]["code"] == code + + def test_slow_down_carries_the_new_interval(self) -> None: + assert fixture_body("device_token_slow_down_400")["interval"] > 5 + + @pytest.mark.parametrize("name", ["device_token_success_200", "refresh_success_200"]) + def test_the_token_success_body(self, name: str) -> None: + body: dict[str, Any] = fixture_body(name) + assert set(body) >= TOKEN_BODY_KEYS + assert body["token_type"] == "Bearer" + assert body["access"].startswith("dbc_at_") + assert body["refresh"].startswith("dbc_rt_") + assert set(body["user"]) == {"uuid", "email", "full_name"} + org: dict[str, Any] = body["organization"] + assert {"id", "uuid", "name", "platform", "plan"} <= set(org) + assert set(org["plan"]) == {"tier", "effective_tier", "is_trial"} + + +class TestSessionCodes: + @pytest.mark.parametrize("code", ["session_revoked", "refresh_token_expired", "user_disabled"]) + def test_refresh_failures(self, code: str) -> None: + recorded: dict[str, Any] = load_fixture(f"refresh_{code}_401") + assert recorded["status"] == 401 + assert recorded["body"]["code"] == code + + @pytest.mark.parametrize( + "code", ["access_token_expired", "session_revoked", "user_disabled", "invalid_credentials"] + ) + def test_bearer_failures(self, code: str) -> None: + recorded: dict[str, Any] = load_fixture(f"bearer_{code}_401") + assert recorded["status"] == 401 + assert recorded["body"]["code"] == code + + def test_the_503_carries_retry_after_inside_the_frozen_range(self) -> None: + recorded: dict[str, Any] = load_fixture("auth_backend_unavailable_503") + assert recorded["status"] == 503 + assert recorded["body"]["code"] == "auth_backend_unavailable" + assert 1 <= int(recorded["headers"]["Retry-After"]) <= 5 + + def test_logout_keeps_todays_bytes(self) -> None: + assert fixture_body("logout_200") == {"detail": "Successfully logged out."} + + +class TestDeprecation: + @pytest.mark.parametrize( + "name", + [ + "request_code_deprecation_200", + "verify_code_deprecation_200", + "verify_code_deprecation_400", + ], + ) + def test_a_field_never_an_error(self, name: str) -> None: + recorded: dict[str, Any] = load_fixture(name) + deprecation: dict[str, Any] = recorded["body"]["deprecation"] + assert set(deprecation) == {"code", "min_version", "sunset", "detail"} + assert deprecation["code"] == "cli_auth_deprecated" + assert deprecation["sunset"] == "2027-03-31" + assert "code" not in {k for k in recorded["body"] if k != "deprecation"} + assert recorded["headers"]["Deprecation"] == "true" + + +class TestStandalone: + def test_legacy_entries_keep_exactly_three_keys(self) -> None: + orgs: list[dict[str, Any]] = fixture_body("verify_code_org_selection_200")["organizations"] + legacy: list[dict[str, Any]] = [o for o in orgs if not o.get("standalone")] + native: list[dict[str, Any]] = [o for o in orgs if o.get("standalone")] + assert legacy and all(set(o) == {"id", "name", "uuid"} for o in legacy) + assert native and all( + o["standalone"] is True and o["platform"] == "dailybot" for o in native + ) + + def test_a_native_org_serves_channels_and_plan(self) -> None: + body: dict[str, Any] = fixture_body("organization_native_200") + assert body["platform"] == "dailybot" + assert body["has_external_chat_platform"] is False + assert body["chat_platforms"][0] == body["primary_chat_platform"] + assert UUID_PATTERN.match(body["primary_chat_platform"]["id"]) + assert set(body["plan"]) == {"tier", "effective_tier", "is_trial"} + + def test_the_plan_field_can_be_absent(self) -> None: + assert "plan" not in fixture_body("organization_chat_platforms_no_plan_200") + legacy: dict[str, Any] = fixture_body("organization_legacy_200") + assert not { + "plan", + "chat_platforms", + "primary_chat_platform", + "has_external_chat_platform", + } & set(legacy) + + @pytest.mark.parametrize( + "name", ["organization_native_200", "organization_chat_platforms_no_plan_200"] + ) + def test_every_platform_summary_is_the_exact_allowlist_in_order(self, name: str) -> None: + body: dict[str, Any] = fixture_body(name) + for summary in [body["primary_chat_platform"], *body["chat_platforms"]]: + assert list(summary) == list(CHAT_PLATFORM_SUMMARY_KEYS) + assert summary["platform"] in CHAT_PLATFORMS + assert summary["status"] in {"connected", "needs_reauth", "disabled"} + assert set(summary["capabilities"]) == {"directory", "reporting", "direct_messages"} + if summary["platform"] == "dailybot": + assert summary["organization_external_id"] is None + + @pytest.mark.parametrize( + "name,status,code", + [ + ("send_message_platform_not_connected_400", 400, "platform_not_connected"), + ("channel_reference_ambiguous_409", 409, "channel_reference_ambiguous"), + ("channel_reference_unknown_400", 400, "channel_reference_unknown"), + ], + ) + def test_channel_codes(self, name: str, status: int, code: str) -> None: + recorded: dict[str, Any] = load_fixture(name) + assert recorded["status"] == status + assert recorded["body"]["code"] == code From 7f5cbe58b953adc2e07e3c18d2b19afaf1f87486 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 13:48:51 +0000 Subject: [PATCH 02/19] feat(config): store the device-flow token pair additively in credentials.json ## Summary A browser (device-flow) session stores its access token in `token`, so every call path and older CLIs keep working, and adds `auth_method`, `refresh`, `expires_at` and `refresh_expires_at`. Legacy email-code sessions keep exactly the five legacy keys. ## Change Log - save_credentials(..., refresh=, expires_at=, refresh_expires_at=) - update_token_pair: rotate the pair in place, keep every other key, 0o600 - is_pair_session, get_refresh_token, get_refresh_token_for (host-bound) - docs/CONFIGURATION.md: the new keys and the no-migration note ## Risks - None for legacy files: keys are only added (Rule 16) Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/config.py | 101 ++++++++++++++++++++++++++++++++++----- docs/CONFIGURATION.md | 13 ++++- tests/config_test.py | 106 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 207 insertions(+), 13 deletions(-) diff --git a/dailybot_cli/config.py b/dailybot_cli/config.py index e5080b89..6dbfac80 100644 --- a/dailybot_cli/config.py +++ b/dailybot_cli/config.py @@ -119,29 +119,91 @@ def load_credentials() -> dict[str, Any] | None: return None +AUTH_METHOD_DEVICE: str = "device" +"""``credentials.json::auth_method`` for a device-flow session (access + refresh pair). + +A file without ``auth_method`` is a legacy email-code session: one opaque ``token`` +and no refresh. For a device session ``token`` holds the short-lived access token, +so every existing call path sends it unchanged and an older CLI still reads it. +""" + + def save_credentials( token: str, email: str, organization: str, organization_uuid: str, api_url: str = DEFAULT_API_URL, + *, + refresh: str | None = None, + expires_at: str | None = None, + refresh_expires_at: str | None = None, ) -> None: - """Save credentials to disk.""" + """Save credentials to disk. + + Without ``refresh`` the file keeps exactly the legacy keys. With it, the + device-flow pair keys are added (Rule 16: keys are only ever added). + """ creds_path: Path = _credentials_path() get_config_dir() - _write_secret_file( - creds_path, - json.dumps( + data: dict[str, Any] = { + "token": token, + "email": email, + "organization": organization, + "organization_uuid": organization_uuid, + "api_url": api_url, + } + if refresh: + data.update( { - "token": token, - "email": email, - "organization": organization, - "organization_uuid": organization_uuid, - "api_url": api_url, - }, - indent=2, - ), + "auth_method": AUTH_METHOD_DEVICE, + "refresh": refresh, + "expires_at": expires_at, + "refresh_expires_at": refresh_expires_at, + } + ) + _write_secret_file(creds_path, json.dumps(data, indent=2)) + + +def update_token_pair( + access: str, + refresh: str, + expires_at: str | None, + refresh_expires_at: str | None = None, +) -> bool: + """Replace the stored access/refresh pair after a rotation, keeping every other key. + + Returns ``False`` (and writes nothing) when there is no stored session. + """ + creds: dict[str, Any] | None = load_credentials() + if creds is None: + return False + creds.update( + { + "token": access, + "auth_method": AUTH_METHOD_DEVICE, + "refresh": refresh, + "expires_at": expires_at, + "refresh_expires_at": refresh_expires_at, + } ) + _write_secret_file(_credentials_path(), json.dumps(creds, indent=2)) + return True + + +def is_pair_session() -> bool: + """Whether the stored login is a device-flow session with a refresh token.""" + creds: dict[str, Any] | None = load_credentials() + return bool(creds and creds.get("auth_method") == AUTH_METHOD_DEVICE and creds.get("refresh")) + + +def get_refresh_token() -> str | None: + """The stored refresh token of a device-flow session, or ``None`` for a legacy one.""" + creds: dict[str, Any] | None = load_credentials() + if not creds or creds.get("auth_method") != AUTH_METHOD_DEVICE: + return None + refresh: Any = creds.get("refresh") + return str(refresh) if refresh else None def clear_credentials() -> None: @@ -245,6 +307,21 @@ def get_login_token_for(api_url: str) -> str | None: return str(token) if token else None +def get_refresh_token_for(api_url: str) -> str | None: + """The stored refresh token, only when ``api_url`` is the host that issued it. + + Same binding as :func:`get_login_token_for`: a refresh token never travels to + another host, not even to rotate the pair. + """ + creds: dict[str, Any] | None = load_credentials() + if not creds: + return None + issued_by: str = str(creds.get("api_url") or DEFAULT_API_URL) + if _origin(issued_by) != _origin(api_url): + return None + return get_refresh_token() + + def login_token_origin_url() -> str: """The API URL that issued the stored login session (the default for legacy files).""" creds: dict[str, Any] | None = load_credentials() diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 1d44be19..5f55d0f2 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -6,7 +6,7 @@ The Dailybot CLI persists state in `~/.config/dailybot/` by default. The path ca | File | Owner | Contents | Permissions | |------|-------|----------|-------------| -| `credentials.json` | `dailybot login` | `{ token, email, organization, organization_uuid, api_url }` | `0o600` | +| `credentials.json` | `dailybot login` | `{ token, email, organization, organization_uuid, api_url }`, plus `{ auth_method, refresh, expires_at, refresh_expires_at }` for a browser (device-flow) session | `0o600` | | `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` | | `org_cache.json` | `dailybot login --email` (step 1) | `{ email, organizations: [...] }` | (no chmod — non-secret) | @@ -19,6 +19,17 @@ The Dailybot CLI persists state in `~/.config/dailybot/` by default. The path ca **`credentials.json`** — created by `save_credentials(...)`. Backwards-compatible additions are safe; `load_credentials()` treats missing keys as absent. The `api_url` field captures which API the user authenticated against, so re-running commands from a different default URL doesn't accidentally use the wrong one. + **Browser (device-flow) sessions** add four keys and rename or remove none (Rule 16): + + | Key | Meaning | + |---|---| + | `auth_method` | `"device"`. Absent means a legacy email-code session: one opaque 90-day `token`, no refresh. | + | `token` | For a device session, the short-lived access token (`dbc_at_…`, about 1 hour). Every call path sends it as before, and an older CLI still reads it. | + | `refresh` | The refresh token (`dbc_rt_…`). It rotates on every refresh, and the new pair replaces the old one in place (`update_token_pair`). | + | `expires_at`, `refresh_expires_at` | ISO-8601 expiries of the access and refresh tokens, as the server sent them. | + + Migration: none is needed. A legacy file keeps loading and authenticating unchanged, and `--email --code` still writes exactly the five legacy keys. The refresh token is bound to the issuing `api_url` like the access token (`get_refresh_token_for`), so it never travels to another host. An older CLI reading a device-session file uses the access token until it expires, then asks for `dailybot login` again. + **`config.json`** — extended via `save_config({...})`. Setting a key to `None` removes it. Accessed only through `load_config()` / `save_config()` — never read directly elsewhere. **`agents.json`** — `default` points to a profile slug under `profiles`. Slugs are derived from the agent name via `_slugify` (lowercase, alphanumeric + hyphens). When `save_agent_profile` is called and `default` is unset, the new profile becomes the default automatically. diff --git a/tests/config_test.py b/tests/config_test.py index 8c9ce8e9..4095e4da 100644 --- a/tests/config_test.py +++ b/tests/config_test.py @@ -1,5 +1,6 @@ """Tests for config module.""" +import json import os from pathlib import Path from typing import Any @@ -296,3 +297,108 @@ def _spy_fdopen(fd: int, *args: Any, **kwargs: Any) -> Any: token="test-token", email="me@example.com", organization="O", organization_uuid="org-1" ) assert modes_at_write == [0o600] + + +class TestTokenPairCredentials: + """PLAN_002 T-credentials-keys: the device-flow pair is stored additively (Rule 16).""" + + LEGACY_KEYS: frozenset[str] = frozenset( + {"token", "email", "organization", "organization_uuid", "api_url"} + ) + + def _save_pair(self) -> None: + from dailybot_cli.config import save_credentials + + save_credentials( + token="dbc_at_test-access", + email="me@example.com", + organization="My Team", + organization_uuid="org-1", + refresh="dbc_rt_test-refresh", + expires_at="2030-01-01T01:00:00Z", + refresh_expires_at="2030-04-01T00:00:00Z", + ) + + def test_a_legacy_file_is_written_byte_for_byte_as_before(self, tmp_config: Path) -> None: + save_credentials( + token="test-token", email="me@example.com", organization="O", organization_uuid="org-1" + ) + raw: dict[str, Any] = json.loads((tmp_config / "credentials.json").read_text()) + assert set(raw) == self.LEGACY_KEYS + + def test_a_legacy_file_loads_as_a_legacy_session(self, tmp_config: Path) -> None: + from dailybot_cli.config import get_refresh_token, is_pair_session + + tmp_config.mkdir(parents=True) + (tmp_config / "credentials.json").write_text( + json.dumps({"token": "test-token", "email": "e", "organization": "o"}) + ) + assert get_token() == "test-token" + assert get_refresh_token() is None + assert is_pair_session() is False + + def test_a_pair_round_trips_and_only_adds_keys(self, tmp_config: Path) -> None: + from dailybot_cli.config import get_refresh_token, is_pair_session + + self._save_pair() + raw: dict[str, Any] = json.loads((tmp_config / "credentials.json").read_text()) + assert set(raw) >= self.LEGACY_KEYS + assert raw["token"] == "dbc_at_test-access" + assert raw["refresh"] == "dbc_rt_test-refresh" + assert raw["expires_at"] == "2030-01-01T01:00:00Z" + assert raw["refresh_expires_at"] == "2030-04-01T00:00:00Z" + assert raw["auth_method"] == "device" + assert get_token() == "dbc_at_test-access" + assert get_refresh_token() == "dbc_rt_test-refresh" + assert is_pair_session() is True + + def test_rotating_the_pair_keeps_every_other_key(self, tmp_config: Path) -> None: + from dailybot_cli.config import get_refresh_token, update_token_pair + + self._save_pair() + update_token_pair( + access="dbc_at_rotated", + refresh="dbc_rt_rotated", + expires_at="2030-01-01T02:00:00Z", + refresh_expires_at="2030-04-01T01:00:00Z", + ) + raw: dict[str, Any] = json.loads((tmp_config / "credentials.json").read_text()) + assert raw["token"] == "dbc_at_rotated" + assert get_refresh_token() == "dbc_rt_rotated" + assert raw["email"] == "me@example.com" + assert raw["organization_uuid"] == "org-1" + assert raw["auth_method"] == "device" + + def test_rotating_without_a_session_writes_nothing(self, tmp_config: Path) -> None: + from dailybot_cli.config import update_token_pair + + assert update_token_pair(access="a", refresh="r", expires_at=None) is False + assert not (tmp_config / "credentials.json").exists() + + def test_the_pair_is_0600_from_the_first_byte( + self, tmp_config: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + from dailybot_cli.config import update_token_pair + + monkeypatch.setattr("dailybot_cli.config.os.chmod", lambda *_a, **_k: None) + previous: int = os.umask(0) + try: + self._save_pair() + update_token_pair(access="dbc_at_x", refresh="dbc_rt_y", expires_at=None) + finally: + os.umask(previous) + assert (tmp_config / "credentials.json").stat().st_mode & 0o777 == 0o600 + + def test_the_access_token_keeps_the_host_binding(self, tmp_config: Path) -> None: + from dailybot_cli.config import get_login_token_for + + self._save_pair() + assert get_login_token_for("https://api.dailybot.com") == "dbc_at_test-access" + assert get_login_token_for("http://localhost:8000") is None + + def test_the_refresh_token_keeps_the_host_binding(self, tmp_config: Path) -> None: + from dailybot_cli.config import get_refresh_token_for + + self._save_pair() + assert get_refresh_token_for("https://api.dailybot.com") == "dbc_rt_test-refresh" + assert get_refresh_token_for("http://localhost:8000") is None From f69f7d1169b0b0528b7bff73b497955cfe2990a2 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 13:50:58 +0000 Subject: [PATCH 03/19] feat(client): add the device-flow and refresh doors to DailyBotClient ## Summary start_device_authorization, poll_device_token and refresh_token_pair send the frozen checkpoint-1 requests without any credential. Device-token states surface as APIError.code (slow_down's interval in extra) and are never retried as authentication failures. ## Change Log - DEVICE_CLIENT_ID / DEVICE_GRANT_TYPE constants - poll timeout message says polling again is safe - tests built on the recorded fixtures; docs/API_REFERENCE.md rows ## Risks - None: new methods only, nothing calls them yet Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 80 +++++++++++++++++ docs/API_REFERENCE.md | 3 + tests/api_client_test.py | 171 ++++++++++++++++++++++++++++++++++++- 3 files changed, 253 insertions(+), 1 deletion(-) diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index a780e563..e5f14e74 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -72,6 +72,10 @@ def _base_headers() -> dict[str, str]: # session work seamlessly regardless of which convention the server uses. _AUTH_RETRY_STATUS_CODES: frozenset[int] = frozenset({401, 403}) +# RFC 8628 device flow (PLAN_002, frozen at checkpoint 1: DEVICE_FLOW_WIRE). +DEVICE_CLIENT_ID: str = "dailybot-cli" +DEVICE_GRANT_TYPE: str = "urn:ietf:params:oauth:grant-type:device_code" + # The person-shaped Tasks doors have a third refusal shape: `400 actor_required`, # meaning "this credential is an organization with nobody to be". It is the same # condition as a 401 — the wrong *kind* of credential was presented — but it does @@ -393,6 +397,15 @@ def __init__( super().__init__(f"API error {status_code}: {detail}") +def _json_field(response: httpx.Response, key: str) -> Any: + """One top-level field of a JSON body, or ``None`` when the body is not a JSON object.""" + try: + body: Any = response.json() + except Exception: + return None + return body.get(key) if isinstance(body, dict) else None + + def _invalid_identifier() -> APIError: """The refusal for an identifier that would change which door a path reaches. @@ -1034,6 +1047,73 @@ def verify_code( ) return self._handle_response(response) + def start_device_authorization(self) -> dict[str, Any]: + """POST /v1/cli/auth/device/ — start an RFC 8628 device authorization. + + Unauthenticated: the CLI has no credential yet. A 404 or 405 means the + server predates the device flow; the caller falls back to the email code. + """ + response: httpx.Response = self._guard_transport( + lambda: httpx.post( + f"{self.api_url}/v1/cli/auth/device/", + json={"client_id": DEVICE_CLIENT_ID, "client_version": __version__}, + headers=self._headers(authenticated=False), + timeout=self.timeout, + ), + method="POST", + timeout_message="The request timed out. Run `dailybot login` again.", + ) + return self._handle_response(response) + + def poll_device_token(self, device_code: str) -> dict[str, Any]: + """POST /v1/cli/auth/device/token/ — redeem an approved device code. + + Each pending state is a 400 whose ``code`` names it (``authorization_pending``, + ``slow_down``, ``access_denied``, ``expired_token``, ``invalid_grant``, + ``invalid_client``). They are never retried as authentication failures; a + ``slow_down`` carries the new polling interval in ``APIError.extra["interval"]``. + """ + response: httpx.Response = self._guard_transport( + lambda: httpx.post( + f"{self.api_url}/v1/cli/auth/device/token/", + json={ + "grant_type": DEVICE_GRANT_TYPE, + "device_code": device_code, + "client_id": DEVICE_CLIENT_ID, + }, + headers=self._headers(authenticated=False), + timeout=self.timeout, + ), + method="POST", + # A poll changes nothing until the approval exists, and a code that was + # redeemed answers invalid_grant: polling again is always safe. + timeout_message="The request timed out. Polling again is safe; the code is still valid.", + ) + try: + return self._handle_response(response) + except APIError as error: + interval: Any = _json_field(response, "interval") + if isinstance(interval, int) and not isinstance(interval, bool): + error.extra["interval"] = interval + raise + + def refresh_token_pair(self, refresh: str) -> dict[str, Any]: + """POST /v1/cli/auth/refresh/ — rotate a device-flow session's token pair. + + Unauthenticated: the refresh token in the body is the proof. Failures keep + their ``code`` (``session_revoked``, ``refresh_token_expired``, ``user_disabled``). + """ + response: httpx.Response = self._guard_transport( + lambda: httpx.post( + f"{self.api_url}/v1/cli/auth/refresh/", + json={"refresh": refresh}, + headers=self._headers(authenticated=False), + timeout=self.timeout, + ), + method="POST", + ) + return self._handle_response(response) + def auth_status(self) -> dict[str, Any]: """GET /v1/cli/auth/status/""" response: httpx.Response = self._request("GET", f"{self.api_url}/v1/cli/auth/status/") diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index bbeb0387..ea69a745 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -660,6 +660,9 @@ All endpoints are POSTed to `{api_url}/v1/...`. The default `api_url` is `https: | `POST` | `/v1/cli/auth/verify-code/` | `{ email, code, organization_id? }` | `{ token, organization: {name, uuid} }` or `{ requires_organization_selection: true, organizations: [...] }` | No auth | | `GET` | `/v1/cli/auth/status/` | — | `{ user: {email}, organization: {name, uuid} }` | Bearer | | `POST` | `/v1/cli/auth/logout/` | — | `{ detail }` | Bearer | +| `POST` | `/v1/cli/auth/device/` | `{ client_id: "dailybot-cli", client_version }` | `{ device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval }` | No auth. `start_device_authorization()`. A 404/405 means the server predates the device flow. | +| `POST` | `/v1/cli/auth/device/token/` | `{ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code, client_id }` | `{ token_type, access, expires_at, refresh, refresh_expires_at, user, organization }` | No auth. `poll_device_token()`. Pending states are `400` with `code` = `authorization_pending`, `slow_down` (body `interval` → `APIError.extra["interval"]`), `access_denied`, `expired_token`, `invalid_grant`, `invalid_client`. | +| `POST` | `/v1/cli/auth/refresh/` | `{ refresh }` | the same token body (a rotated pair) | No auth. `refresh_token_pair()`. `401` codes: `session_revoked`, `refresh_token_expired`, `user_disabled`. | ### CLI-personal (X-API-KEY *or* Bearer) diff --git a/tests/api_client_test.py b/tests/api_client_test.py index e2d4a8d5..41ca6a3f 100644 --- a/tests/api_client_test.py +++ b/tests/api_client_test.py @@ -6,7 +6,15 @@ import httpx import pytest -from dailybot_cli.api_client import APIError, DailyBotClient +from dailybot_cli import __version__ +from dailybot_cli.api_client import ( + DEVICE_CLIENT_ID, + DEVICE_GRANT_TYPE, + APIError, + DailyBotClient, + TransportError, +) +from tests.wire_fixture_loader import fixture_body, fixture_response @pytest.fixture @@ -2208,3 +2216,164 @@ def test_success_after_one_retry(self, client: DailyBotClient) -> None: assert send.call_count == 2 assert sleep.call_count == 1 assert out.status_code == 200 + + +# --- PLAN_002 T-device-client: device-flow doors against the recorded fixtures --- + +DEVICE_API: str = "https://api.example.com" + + +@pytest.fixture +def device_client() -> DailyBotClient: + return DailyBotClient(api_url=DEVICE_API, token="dbc_at_existing", api_key="test-key") + + +class TestDeviceStartAuthorization: + def test_the_frozen_request_without_credentials(self, device_client: DailyBotClient) -> None: + with patch( + "dailybot_cli.api_client.httpx.post", return_value=fixture_response("device_start_200") + ) as post: + result: dict[str, Any] = device_client.start_device_authorization() + assert result == fixture_body("device_start_200") + url: str = post.call_args.args[0] + assert url == f"{DEVICE_API}/v1/cli/auth/device/" + assert post.call_args.kwargs["json"] == { + "client_id": "dailybot-cli", + "client_version": __version__, + } + headers: dict[str, str] = post.call_args.kwargs["headers"] + assert "Authorization" not in headers + assert "X-API-KEY" not in headers + + @pytest.mark.parametrize( + "name,status", + [("device_start_not_found_404", 404), ("device_start_method_not_allowed_405", 405)], + ) + def test_an_old_server_surfaces_its_status( + self, device_client: DailyBotClient, name: str, status: int + ) -> None: + with ( + patch("dailybot_cli.api_client.httpx.post", return_value=fixture_response(name)), + pytest.raises(APIError) as caught, + ): + device_client.start_device_authorization() + assert caught.value.status_code == status + + def test_invalid_client(self, device_client: DailyBotClient) -> None: + with ( + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("device_start_invalid_client_400"), + ), + pytest.raises(APIError) as caught, + ): + device_client.start_device_authorization() + assert caught.value.code == "invalid_client" + + +class TestPollDeviceToken: + def test_the_frozen_request_without_credentials(self, device_client: DailyBotClient) -> None: + with patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("device_token_success_200"), + ) as post: + result: dict[str, Any] = device_client.poll_device_token("the-device-code") + assert result == fixture_body("device_token_success_200") + assert post.call_args.args[0] == f"{DEVICE_API}/v1/cli/auth/device/token/" + assert post.call_args.kwargs["json"] == { + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + "device_code": "the-device-code", + "client_id": "dailybot-cli", + } + headers: dict[str, str] = post.call_args.kwargs["headers"] + assert "Authorization" not in headers + assert "X-API-KEY" not in headers + + @pytest.mark.parametrize( + "code", + [ + "authorization_pending", + "slow_down", + "access_denied", + "expired_token", + "invalid_grant", + "invalid_client", + ], + ) + def test_each_state_is_its_code_and_never_an_auth_retry( + self, device_client: DailyBotClient, code: str + ) -> None: + with ( + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response(f"device_token_{code}_400"), + ) as post, + pytest.raises(APIError) as caught, + ): + device_client.poll_device_token("the-device-code") + assert caught.value.code == code + assert caught.value.status_code == 400 + assert post.call_count == 1 + + def test_slow_down_carries_the_new_interval(self, device_client: DailyBotClient) -> None: + with ( + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("device_token_slow_down_400"), + ), + pytest.raises(APIError) as caught, + ): + device_client.poll_device_token("the-device-code") + assert caught.value.extra["interval"] == 10 + + def test_a_timeout_does_not_say_the_code_is_spent(self, device_client: DailyBotClient) -> None: + with ( + patch("dailybot_cli.api_client.httpx.post", side_effect=httpx.ReadTimeout("slow")), + pytest.raises(TransportError) as caught, + ): + device_client.poll_device_token("the-device-code") + assert "again" in str(caught.value).lower() + + +class TestDeviceRefreshTokenPair: + def test_the_frozen_request_without_credentials(self, device_client: DailyBotClient) -> None: + with patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ) as post: + result: dict[str, Any] = device_client.refresh_token_pair("dbc_rt_old") + assert result == fixture_body("refresh_success_200") + assert post.call_args.args[0] == f"{DEVICE_API}/v1/cli/auth/refresh/" + assert post.call_args.kwargs["json"] == {"refresh": "dbc_rt_old"} + headers: dict[str, str] = post.call_args.kwargs["headers"] + assert "Authorization" not in headers + assert "X-API-KEY" not in headers + + @pytest.mark.parametrize("code", ["session_revoked", "refresh_token_expired", "user_disabled"]) + def test_failures_keep_their_code(self, device_client: DailyBotClient, code: str) -> None: + with ( + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response(f"refresh_{code}_401"), + ) as post, + pytest.raises(APIError) as caught, + ): + device_client.refresh_token_pair("dbc_rt_old") + assert caught.value.code == code + assert post.call_count == 1 + + +def test_device_constants_are_the_frozen_values() -> None: + assert DEVICE_CLIENT_ID == "dailybot-cli" + assert DEVICE_GRANT_TYPE == "urn:ietf:params:oauth:grant-type:device_code" + + +def test_device_refresh_tokens_never_reach_the_error_text(device_client: DailyBotClient) -> None: + response: MagicMock = fixture_response("refresh_session_revoked_401") + with ( + patch("dailybot_cli.api_client.httpx.post", return_value=response), + pytest.raises(APIError) as caught, + ): + device_client.refresh_token_pair("dbc_rt_secret-value") + assert "dbc_rt_secret-value" not in str(caught.value) + assert "dbc_rt_secret-value" not in caught.value.detail From 2dda26739eb8cb38a3f1f536d90dbf049ea95e3f Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 13:52:28 +0000 Subject: [PATCH 04/19] feat(client): send the X-Dailybot-Client telemetry headers ## Summary Every request to the Dailybot API now carries `X-Dailybot-Client: cli` and `X-Dailybot-Client-Version: ` beside the User-Agent, so the server can classify CLI traffic. Presigned storage uploads and downloads carry neither. ## Change Log - CLIENT_HEADER / CLIENT_VERSION_HEADER / CLIENT_HEADER_VALUE in _base_headers - tests on unauthenticated, user, agent and storage paths ## Risks - None: telemetry only, never used for authorization Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 10 +++++++++ tests/user_agent_test.py | 46 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index e5f14e74..2f5822a8 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -55,12 +55,22 @@ def user_agent() -> str: return f"{USER_AGENT_PRODUCT}/{__version__} (python/{python}; {os_name}; {method})" +# Telemetry headers (DEVICE_FLOW_WIRE, W1): the server counts clients and versions +# from them. They never affect authorization, throttling or responses, and they go +# only to the Dailybot API (never to a presigned storage host). +CLIENT_HEADER: str = "X-Dailybot-Client" +CLIENT_VERSION_HEADER: str = "X-Dailybot-Client-Version" +CLIENT_HEADER_VALUE: str = "cli" + + def _base_headers() -> dict[str, str]: """The headers every Dailybot API request carries, before any credential.""" return { "Content-Type": "application/json", "Accept": "application/json", "User-Agent": user_agent(), + CLIENT_HEADER: CLIENT_HEADER_VALUE, + CLIENT_VERSION_HEADER: __version__, } diff --git a/tests/user_agent_test.py b/tests/user_agent_test.py index 16634623..6bc0b7d4 100644 --- a/tests/user_agent_test.py +++ b/tests/user_agent_test.py @@ -164,6 +164,52 @@ def test_streamed_downloads_from_the_api_and_from_storage(self) -> None: assert "Authorization" not in headers and "X-API-KEY" not in headers +class TestClientTelemetryHeaders: + """PLAN_002 T-client-header: X-Dailybot-Client / -Version on every API request (W1).""" + + def _assert_client_headers(self, headers: dict[str, str]) -> None: + assert headers["X-Dailybot-Client"] == "cli" + assert headers["X-Dailybot-Client-Version"] == __version__ + + def test_client_headers_on_unauthenticated_auth_doors(self) -> None: + client: DailyBotClient = DailyBotClient(api_url=API_URL) + with patch( + "dailybot_cli.api_client.httpx.post", return_value=_response(body={"ok": True}) + ) as post: + client.start_device_authorization() + self._assert_client_headers(_sent_headers(post)) + with patch("dailybot_cli.api_client.httpx.post", return_value=_response(body={})) as post: + client.request_code("me@example.com") + self._assert_client_headers(_sent_headers(post)) + + def test_client_headers_on_user_and_agent_requests(self) -> None: + client: DailyBotClient = DailyBotClient(api_url=API_URL, token="test-token") + with patch("dailybot_cli.api_client.httpx.get", return_value=_response(body={})) as get: + client.get_status() + self._assert_client_headers(_sent_headers(get)) + keyed: DailyBotClient = DailyBotClient(api_url=API_URL, api_key="test-key") + with patch( + "dailybot_cli.api_client.httpx.request", return_value=_response(body={}) + ) as request: + keyed.get_agent_health(agent_name="a") + self._assert_client_headers(_sent_headers(request)) + + def test_client_headers_never_reach_a_presigned_upload(self) -> None: + client: DailyBotClient = DailyBotClient(api_url=API_URL, token="test-token") + presign: dict[str, Any] = {"upload_url": STORAGE_URL, "method": "PUT", "headers": {}} + with patch("dailybot_cli.api_client.httpx.request", return_value=_response()) as request: + client.upload_attachment_bytes(presign, b"hello") + headers: dict[str, str] = _sent_headers(request) + assert "X-Dailybot-Client" not in headers + assert "X-Dailybot-Client-Version" not in headers + + def test_client_headers_never_reach_a_storage_download(self) -> None: + with patch("dailybot_cli.api_client.httpx.stream", return_value=_Stream()) as stream: + DailyBotClient._download_from_storage(STORAGE_URL) + headers: dict[str, str] = stream.call_args.kwargs["headers"] + assert "X-Dailybot-Client" not in headers + + @pytest.fixture(autouse=True) def _fresh_user_agent() -> Any: user_agent.cache_clear() From 185c6f6feedfe1d2d02b8de3a9ad8eb0367925de Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 13:59:59 +0000 Subject: [PATCH 05/19] feat(auth): add browser sign-in with `dailybot login --device` ## Summary The RFC 8628 device flow: the CLI prints a Dailybot link and a short code, polls at the server's interval (adopting slow_down's interval, capped at 30 s), stops cleanly on denial, expiry and invalid requests, and saves the access/refresh pair, the org and its effective tier. A 404/405 on the start door falls back to the email code. The flow is opt-in for now (DEVICE_LOGIN_IS_DEFAULT = False) until the API doors are live; the email-code paths are unchanged. ## Change Log - commands/_device_login.py: start, poll loop, terminal states, save - display.print_device_login_instructions (server text neutralized) - login: --device flag; email is prompted only on the email path - README and CLI_COMMAND_BEST_PRACTICES login sections ## Risks - Nothing is written until the pair arrives; Ctrl-C leaves the stored session untouched Co-Authored-By: Claude Opus 5.5 --- README.md | 9 +- dailybot_cli/commands/_device_login.py | 165 +++++++++++++ dailybot_cli/commands/auth.py | 42 +++- dailybot_cli/display.py | 18 ++ docs/CLI_COMMAND_BEST_PRACTICES.md | 4 + tests/device_login_test.py | 306 +++++++++++++++++++++++++ 6 files changed, 536 insertions(+), 8 deletions(-) create mode 100644 dailybot_cli/commands/_device_login.py create mode 100644 tests/device_login_test.py diff --git a/README.md b/README.md index 36b0d202..9fde3539 100644 --- a/README.md +++ b/README.md @@ -154,6 +154,9 @@ Authenticate once with your Dailybot email, then submit updates, complete check- # Log in (interactive, email OTP) dailybot login +# Or sign in through the browser: approve a short code at a Dailybot link +dailybot login --device + # See what check-ins are waiting for you dailybot status @@ -622,6 +625,10 @@ dailybot config key=your-key dailybot login ``` +### Browser sign-in (`--device`) + +`dailybot login --device` prints a Dailybot link and a short code such as `BCDF-GHJK`. Open the link in any browser where you use Dailybot (it does not have to be on the same machine, so it works over SSH), check that the page shows the same code, and approve it. The CLI waits at the interval the server asks for and saves the session as soon as you approve. The session renews itself while you use the CLI, so you do not have to log in again every few hours. Denying the request in the browser, or letting the code expire (10 minutes), stops the command without changing your stored session. On a Dailybot server that does not offer browser sign-in yet, the command continues with the email code. + ### Non-interactive login AI agents (e.g. Claude Code) and scripts can log in without interactive prompts using a two-step flow: @@ -838,7 +845,7 @@ Replies to agent emails land as messages retrievable via `dailybot agent message | Command | Description | |---------|-------------| -| `dailybot login` | Authenticate with email OTP | +| `dailybot login` | Authenticate with email OTP, or in the browser with `--device` | | `dailybot logout` | Log out and revoke token | | `dailybot status` | Show pending check-ins and auth status | | `dailybot me` | Show the authenticated user and org context (`--include-email`, `--json`) | diff --git a/dailybot_cli/commands/_device_login.py b/dailybot_cli/commands/_device_login.py new file mode 100644 index 00000000..1f3d8e4b --- /dev/null +++ b/dailybot_cli/commands/_device_login.py @@ -0,0 +1,165 @@ +"""Browser sign-in for `dailybot login` (RFC 8628 device flow, PLAN_002). + +Start a device authorization, show the link and code, poll the token door at the +server's interval, and save the access/refresh pair. The values are frozen at +checkpoint 1 (DEVICE_FLOW_WIRE): a 404 or 405 on the start door means the server +predates the flow, and the caller falls back to the email code. +""" + +import time +from typing import Any + +from dailybot_cli.api_client import APIError, DailyBotClient, TransportError +from dailybot_cli.config import save_credentials, save_org_plan +from dailybot_cli.display import ( + console, + print_device_login_instructions, + print_error, + print_success, +) + +# Hand-off T31: the browser flow stays opt-in (`--device`) until the API doors are +# live. Flipping this makes a bare `dailybot login` start it, keeping the fallback. +DEVICE_LOGIN_IS_DEFAULT: bool = False + +DEFAULT_POLL_INTERVAL_SECS: int = 5 +SLOW_DOWN_INCREMENT_SECS: int = 5 +MAX_POLL_INTERVAL_SECS: int = 30 +DEFAULT_EXPIRES_IN_SECS: int = 600 +OLD_SERVER_STATUS_CODES: frozenset[int] = frozenset({404, 405}) + +CODE_AUTHORIZATION_PENDING: str = "authorization_pending" +CODE_SLOW_DOWN: str = "slow_down" +HTTP_TOO_MANY_REQUESTS: int = 429 + + +class DeviceFlowUnsupported(Exception): + """The server answered 404/405 on the start door: use the email code instead.""" + + +def login_command() -> str: + """The command that starts a browser sign-in, as the user should type it.""" + return "dailybot login" if DEVICE_LOGIN_IS_DEFAULT else "dailybot login --device" + + +def _terminal_message(code: str | None) -> str | None: + """The message for a poll answer that ends the sign-in, or ``None`` to keep polling.""" + restart: str = f"Run `{login_command()}` to start again." + messages: dict[str, str] = { + "access_denied": "The sign-in was denied in the browser.", + "expired_token": f"The sign-in code expired before it was approved. {restart}", + "invalid_grant": f"This sign-in request is no longer valid. {restart}", + "invalid_client": "The server refused this sign-in request. Update the Dailybot CLI " + "(`dailybot upgrade`) and try again.", + } + return messages.get(code or "") + + +def next_interval(current: int, server_interval: Any) -> int: + """The polling interval after a ``slow_down``: the server's value, else +5, capped at 30.""" + proposed: int = ( + server_interval + if isinstance(server_interval, int) + and not isinstance(server_interval, bool) + and server_interval > current + else current + SLOW_DOWN_INCREMENT_SECS + ) + return min(proposed, MAX_POLL_INTERVAL_SECS) + + +def _positive_int(value: Any, default: int) -> int: + if isinstance(value, int) and not isinstance(value, bool) and value > 0: + return value + return default + + +def _poll_until_approved(client: DailyBotClient, start: dict[str, Any]) -> dict[str, Any]: + """Poll the token door until it answers the pair, or raise ``SystemExit(1)``.""" + device_code: str = str(start.get("device_code") or "") + interval: int = min( + _positive_int(start.get("interval"), DEFAULT_POLL_INTERVAL_SECS), MAX_POLL_INTERVAL_SECS + ) + expires_in: int = _positive_int(start.get("expires_in"), DEFAULT_EXPIRES_IN_SECS) + deadline: float = time.monotonic() + expires_in + with console.status("Waiting for you to approve the sign-in in the browser..."): + while True: + if time.monotonic() + interval > deadline: + break + time.sleep(interval) + try: + return client.poll_device_token(device_code) + except TransportError: + continue # Polling is idempotent until approval: a blip is not an answer. + except APIError as error: + if error.code == CODE_AUTHORIZATION_PENDING: + continue + if error.code == CODE_SLOW_DOWN: + interval = next_interval(interval, error.extra.get("interval")) + continue + if error.status_code == HTTP_TOO_MANY_REQUESTS: + interval = next_interval(interval, None) + continue + message: str | None = _terminal_message(error.code) + print_error(message or error.detail) + raise SystemExit(1) from None + print_error(_terminal_message("expired_token") or "The sign-in code expired.") + raise SystemExit(1) + + +def _save_pair(client: DailyBotClient, token: dict[str, Any]) -> tuple[str, str]: + """Save the pair, the org and its effective tier; return (email, org name).""" + access: Any = token.get("access") + refresh: Any = token.get("refresh") + if not isinstance(access, str) or not access or not isinstance(refresh, str) or not refresh: + print_error("Authentication failed: no token received.") + raise SystemExit(1) + user: Any = token.get("user") + org: Any = token.get("organization") + user = user if isinstance(user, dict) else {} + org = org if isinstance(org, dict) else {} + email: str = str(user.get("email") or "") + org_name: str = str(org.get("name") or "") + org_uuid: str = str(org.get("uuid") or "") + save_credentials( + token=access, + email=email, + organization=org_name, + organization_uuid=org_uuid, + api_url=client.api_url, + refresh=refresh, + expires_at=token.get("expires_at"), + refresh_expires_at=token.get("refresh_expires_at"), + ) + plan: Any = org.get("plan") + tier: Any = None + if isinstance(plan, dict): + tier = plan.get("effective_tier") or plan.get("tier") + if isinstance(tier, str) and tier and org_uuid: + save_org_plan(org_uuid, tier) + return email, org_name + + +def device_login(client: DailyBotClient) -> None: + """Run the browser sign-in end to end. + + Raises :class:`DeviceFlowUnsupported` on a 404/405 start (an older server), and + ``SystemExit(1)`` on any other refusal. Nothing is written until the pair arrives, + so an interrupted sign-in leaves the stored session untouched. + """ + try: + with console.status("Starting the sign-in..."): + start: dict[str, Any] = client.start_device_authorization() + except APIError as error: + if error.status_code in OLD_SERVER_STATUS_CODES: + raise DeviceFlowUnsupported from error + print_error(_terminal_message(error.code) or error.detail) + raise SystemExit(1) from None + + print_device_login_instructions( + verification_uri=str(start.get("verification_uri") or ""), + user_code=str(start.get("user_code") or ""), + verification_uri_complete=start.get("verification_uri_complete"), + ) + token: dict[str, Any] = _poll_until_approved(client, start) + email, org_name = _save_pair(client, token) + print_success(f"Logged in as {email} ({org_name})") diff --git a/dailybot_cli/commands/auth.py b/dailybot_cli/commands/auth.py index 79fedef3..2e430226 100644 --- a/dailybot_cli/commands/auth.py +++ b/dailybot_cli/commands/auth.py @@ -7,6 +7,7 @@ import questionary from dailybot_cli.api_client import APIError, DailyBotClient +from dailybot_cli.commands import _device_login from dailybot_cli.config import ( RepoEnvError, clear_credentials, @@ -278,7 +279,7 @@ def _verify_non_interactive(email: str, code: str, org_uuid: str | None) -> None @click.command() -@click.option("--email", prompt="Email", help="Your Dailybot account email.") +@click.option("--email", default=None, help="Your Dailybot account email (email-code sign-in).") @click.option( "--code", default=None, @@ -291,9 +292,20 @@ def _verify_non_interactive(email: str, code: str, org_uuid: str | None) -> None type=str, help="Organization UUID to log in to (for multi-org accounts). Shown after requesting a code.", ) -@click.pass_context -def login(ctx: click.Context, email: str, code: str | None, org_uuid: str | None) -> None: - """Authenticate with Dailybot via email OTP. +@click.option( + "--device", + "use_device", + is_flag=True, + default=False, + help="Sign in through the browser: approve a short code at a Dailybot link. " + "Falls back to the email code on servers that do not offer it yet.", +) +def login(email: str | None, code: str | None, org_uuid: str | None, use_device: bool) -> None: + """Authenticate with Dailybot via email OTP, or in the browser with --device. + + \b + Browser sign-in (prints a link and a code to approve; works over SSH): + dailybot login --device \b Non-interactive usage (for scripts and AI agents): @@ -304,12 +316,28 @@ def login(ctx: click.Context, email: str, code: str | None, org_uuid: str | None Multi-org: pass --org with the UUID shown in step 1 dailybot login --email=user@example.com --code=123456 --org=abc-123 """ - email_from_flag: bool = ( - ctx.get_parameter_source("email") == click.core.ParameterSource.COMMANDLINE - ) + if use_device and (code is not None or org_uuid is not None): + raise click.UsageError("--device cannot be combined with --code or --org.") _warn_if_env_json_redirects_login() + browser: bool = use_device or ( + _device_login.DEVICE_LOGIN_IS_DEFAULT and email is None and code is None + ) + if browser: + try: + _device_login.device_login(DailyBotClient()) + return + except _device_login.DeviceFlowUnsupported: + print_info( + "This Dailybot server does not offer browser sign-in yet. " + "Continuing with an email code." + ) + + email_from_flag: bool = email is not None + if email is None: + email = click.prompt("Email", type=str) + if code is not None: # Non-interactive step 2: verify code directly _verify_non_interactive(email, code, org_uuid) diff --git a/dailybot_cli/display.py b/dailybot_cli/display.py index e8435667..46633d66 100644 --- a/dailybot_cli/display.py +++ b/dailybot_cli/display.py @@ -44,6 +44,24 @@ def print_info(message: str) -> None: console.print(f"[dim]{escape(message)}[/dim]") +def print_device_login_instructions( + verification_uri: str, user_code: str, verification_uri_complete: str | None = None +) -> None: + """Show where to approve a browser (device-flow) sign-in and the code to compare. + + The URL and code are server text: neutralized and escaped. The link is printed + for copying, never opened automatically, so a remote or headless shell works. + """ + link: str = verification_uri_complete or verification_uri + console.print("To sign in, open this link in a browser where you use Dailybot:") + console.print(f" [bold cyan]{safe_text(link)}[/bold cyan]") + console.print( + f"Check that the page shows the code [bold]{safe_text(user_code)}[/bold], then approve it." + ) + if verification_uri_complete and verification_uri_complete != verification_uri: + print_info(f"Or open {plain_text(verification_uri)} and enter the code yourself.") + + def print_raw_value(value: str) -> None: """Print one bare value for a shell variable: no styling, no wrapping, stdout.""" click.echo(value) diff --git a/docs/CLI_COMMAND_BEST_PRACTICES.md b/docs/CLI_COMMAND_BEST_PRACTICES.md index 7b3b1a20..8658f748 100644 --- a/docs/CLI_COMMAND_BEST_PRACTICES.md +++ b/docs/CLI_COMMAND_BEST_PRACTICES.md @@ -135,6 +135,10 @@ Every command that talks to an authenticated endpoint must resolve credentials t For the resolution order specifics, see [CONFIGURATION.md](CONFIGURATION.md). +### Login paths + +`dailybot login` has two paths. The email code (`--email`, `--code`, `--org`) is unchanged and stays the scriptable two-step flow. The browser sign-in (`--device`, RFC 8628) lives in `commands/_device_login.py`, outside the Click callback: it starts the device authorization, prints the link and code through `display.print_device_login_instructions`, polls at the server's `interval` (a `slow_down` adopts the body's `interval`, capped at 30 s), and writes credentials only when the pair arrives. A 404 or 405 on the start door raises `DeviceFlowUnsupported`, and the callback continues with the email code. `DEVICE_LOGIN_IS_DEFAULT` decides whether a bare `dailybot login` starts the browser path; it stays `False` until the API doors are live everywhere, and `interactive.py` follows the same default. + ## Spinner Usage Wrap every `client.*` call in a `console.status(...)`: diff --git a/tests/device_login_test.py b/tests/device_login_test.py new file mode 100644 index 00000000..f4ea89cb --- /dev/null +++ b/tests/device_login_test.py @@ -0,0 +1,306 @@ +"""`dailybot login --device`: the RFC 8628 browser sign-in (PLAN_002 T-device-login). + +HTTP is mocked at the call site with the recorded fixtures, so the real +DailyBotClient builds every request. Sleeping is patched out. +""" + +import json +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.commands import _device_login +from dailybot_cli.config import get_org_plan, load_credentials +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_body, fixture_response + +POST: str = "dailybot_cli.api_client.httpx.post" +SLEEP: str = "dailybot_cli.commands._device_login.time.sleep" + + +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +@pytest.fixture +def sleeps() -> Any: + with patch(SLEEP) as sleep: + yield sleep + + +def _login(runner: CliRunner, *args: str, input: str | None = None) -> Result: + return runner.invoke(cli, ["login", "--device", *args], input=input) + + +def _credentials_file(config_dir: Path) -> Path: + return config_dir / "credentials.json" + + +class TestHappyPath: + def test_prints_the_link_and_code_then_saves_the_pair( + self, runner: CliRunner, sleeps: MagicMock, _isolated_environment: Path + ) -> None: + responses: list[MagicMock] = [ + fixture_response("device_start_200"), + fixture_response("device_token_success_200"), + ] + with patch(POST, side_effect=responses): + result: Result = _login(runner) + assert result.exit_code == 0, result.output + start: dict[str, Any] = fixture_body("device_start_200") + assert start["verification_uri_complete"] in result.output + assert start["user_code"] in result.output + assert "Logged in as me@example.com (My Team)" in result.output + + creds: dict[str, Any] | None = load_credentials() + token: dict[str, Any] = fixture_body("device_token_success_200") + assert creds is not None + assert creds["token"] == token["access"] + assert creds["refresh"] == token["refresh"] + assert creds["expires_at"] == token["expires_at"] + assert creds["refresh_expires_at"] == token["refresh_expires_at"] + assert creds["auth_method"] == "device" + assert creds["email"] == "me@example.com" + assert creds["organization"] == "My Team" + assert creds["organization_uuid"] == token["organization"]["uuid"] + + def test_caches_the_effective_tier(self, runner: CliRunner, sleeps: MagicMock) -> None: + with patch( + POST, + side_effect=[ + fixture_response("device_start_200"), + fixture_response("device_token_success_200"), + ], + ): + _login(runner) + org: dict[str, Any] = fixture_body("device_token_success_200")["organization"] + assert get_org_plan(org["uuid"]) == org["plan"]["effective_tier"] == "startup" + + def test_the_tokens_never_reach_the_output(self, runner: CliRunner, sleeps: MagicMock) -> None: + with patch( + POST, + side_effect=[ + fixture_response("device_start_200"), + fixture_response("device_token_success_200"), + ], + ): + result: Result = _login(runner) + token: dict[str, Any] = fixture_body("device_token_success_200") + assert token["access"] not in result.output + assert token["refresh"] not in result.output + assert fixture_body("device_start_200")["device_code"] not in result.output + + +class TestPolling: + def test_pending_then_success_waits_the_server_interval( + self, runner: CliRunner, sleeps: MagicMock + ) -> None: + with patch( + POST, + side_effect=[ + fixture_response("device_start_200"), + fixture_response("device_token_authorization_pending_400"), + fixture_response("device_token_authorization_pending_400"), + fixture_response("device_token_success_200"), + ], + ) as post: + result: Result = _login(runner) + assert result.exit_code == 0, result.output + assert post.call_count == 4 + assert [c.args[0] for c in sleeps.call_args_list] == [5, 5, 5] + + def test_slow_down_adopts_the_body_interval(self, runner: CliRunner, sleeps: MagicMock) -> None: + with patch( + POST, + side_effect=[ + fixture_response("device_start_200"), + fixture_response("device_token_slow_down_400"), + fixture_response("device_token_authorization_pending_400"), + fixture_response("device_token_success_200"), + ], + ): + result: Result = _login(runner) + assert result.exit_code == 0, result.output + assert [c.args[0] for c in sleeps.call_args_list] == [5, 10, 10] + + def test_slow_down_without_an_interval_adds_five_and_caps_at_thirty(self) -> None: + assert _device_login.next_interval(5, None) == 10 + assert _device_login.next_interval(28, None) == 30 + assert _device_login.next_interval(5, 120) == 30 + assert _device_login.next_interval(5, 0) == 10 + + def test_a_transport_failure_keeps_polling(self, runner: CliRunner, sleeps: MagicMock) -> None: + import httpx + + with patch( + POST, + side_effect=[ + fixture_response("device_start_200"), + httpx.ConnectError("offline"), + fixture_response("device_token_success_200"), + ], + ): + result: Result = _login(runner) + assert result.exit_code == 0, result.output + assert load_credentials() is not None + + def test_the_local_deadline_stops_a_silent_server( + self, runner: CliRunner, sleeps: MagicMock + ) -> None: + clock: list[float] = [0.0] + + def tick(seconds: float) -> None: + clock[0] += seconds + + sleeps.side_effect = tick + pending: list[MagicMock] = [ + fixture_response("device_token_authorization_pending_400") for _ in range(200) + ] + with ( + patch( + "dailybot_cli.commands._device_login.time.monotonic", side_effect=lambda: clock[0] + ), + patch(POST, side_effect=[fixture_response("device_start_200"), *pending]), + ): + result: Result = _login(runner) + assert result.exit_code == 1 + assert "expired" in result.output.lower() + assert clock[0] <= 600 + 5 + assert load_credentials() is None + + +class TestTerminalStates: + @pytest.mark.parametrize( + "code,phrase", + [ + ("access_denied", "denied"), + ("expired_token", "expired"), + ("invalid_grant", "no longer valid"), + ("invalid_client", "update the dailybot cli"), + ], + ) + def test_each_stops_without_writing_credentials( + self, runner: CliRunner, sleeps: MagicMock, code: str, phrase: str + ) -> None: + with patch( + POST, + side_effect=[ + fixture_response("device_start_200"), + fixture_response(f"device_token_{code}_400"), + ], + ) as post: + result: Result = _login(runner) + assert result.exit_code == 1 + assert phrase in result.output.lower() + assert post.call_count == 2 + assert load_credentials() is None + + def test_ctrl_c_aborts_without_writing_credentials( + self, runner: CliRunner, sleeps: MagicMock + ) -> None: + sleeps.side_effect = KeyboardInterrupt + with patch(POST, side_effect=[fixture_response("device_start_200")]): + result: Result = _login(runner) + assert result.exit_code != 0 + assert load_credentials() is None + + +class TestOldServerFallback: + @pytest.mark.parametrize( + "name", ["device_start_not_found_404", "device_start_method_not_allowed_405"] + ) + def test_falls_back_to_the_email_code( + self, runner: CliRunner, sleeps: MagicMock, name: str + ) -> None: + with patch( + POST, + side_effect=[ + fixture_response(name), + fixture_response("request_code_deprecation_200"), + fixture_response("verify_code_legacy_200"), + ], + ) as post: + result: Result = _login(runner, input="me@example.com\n123456\n") + assert result.exit_code == 0, result.output + assert "email" in result.output.lower() + urls: list[str] = [c.args[0] for c in post.call_args_list] + assert urls[0].endswith("/v1/cli/auth/device/") + assert urls[1].endswith("/v1/cli/auth/request-code/") + assert urls[2].endswith("/v1/cli/auth/verify-code/") + creds: dict[str, Any] | None = load_credentials() + assert creds is not None + assert creds["token"] == "legacy-test-token" + assert "auth_method" not in creds + + def test_a_server_error_on_start_is_not_a_fallback( + self, runner: CliRunner, sleeps: MagicMock + ) -> None: + with patch(POST, side_effect=[fixture_response("device_start_invalid_client_400")]) as post: + result: Result = _login(runner) + assert result.exit_code == 1 + assert post.call_count == 1 + + +class TestFlags: + def test_device_with_code_is_a_usage_error(self, runner: CliRunner) -> None: + result: Result = runner.invoke(cli, ["login", "--device", "--code", "123456"]) + assert result.exit_code == 2 + + def test_device_login_is_opt_in_until_the_api_doors_are_live(self) -> None: + # Hand-off T31: the device flow stays opt-in. Flipping this constant makes a + # bare `dailybot login` start the browser flow (with the 404/405 fallback). + assert _device_login.DEVICE_LOGIN_IS_DEFAULT is False + + def test_bare_login_keeps_the_email_code_by_default( + self, runner: CliRunner, sleeps: MagicMock + ) -> None: + with patch( + POST, + side_effect=[ + fixture_response("request_code_deprecation_200"), + fixture_response("verify_code_legacy_200"), + ], + ) as post: + result: Result = runner.invoke(cli, ["login"], input="me@example.com\n123456\n") + assert result.exit_code == 0, result.output + assert post.call_args_list[0].args[0].endswith("/v1/cli/auth/request-code/") + + def test_when_the_default_flips_a_bare_login_uses_the_browser( + self, runner: CliRunner, sleeps: MagicMock, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setattr(_device_login, "DEVICE_LOGIN_IS_DEFAULT", True) + with patch( + POST, + side_effect=[ + fixture_response("device_start_200"), + fixture_response("device_token_success_200"), + ], + ) as post: + result: Result = runner.invoke(cli, ["login"]) + assert result.exit_code == 0, result.output + assert post.call_args_list[0].args[0].endswith("/v1/cli/auth/device/") + + def test_when_the_default_flips_an_explicit_email_keeps_the_code_path( + self, runner: CliRunner, sleeps: MagicMock, monkeypatch: pytest.MonkeyPatch + ) -> None: + monkeypatch.setattr(_device_login, "DEVICE_LOGIN_IS_DEFAULT", True) + with patch(POST, side_effect=[fixture_response("request_code_deprecation_200")]) as post: + result: Result = runner.invoke(cli, ["login", "--email", "me@example.com"]) + assert result.exit_code == 0, result.output + assert post.call_args_list[0].args[0].endswith("/v1/cli/auth/request-code/") + + +def test_a_legacy_login_still_writes_exactly_the_legacy_keys( + runner: CliRunner, _isolated_environment: Path +) -> None: + with patch(POST, side_effect=[fixture_response("verify_code_legacy_200")]): + result: Result = runner.invoke( + cli, ["login", "--email", "me@example.com", "--code", "123456"] + ) + assert result.exit_code == 0, result.output + raw: dict[str, Any] = json.loads(_credentials_file(_isolated_environment).read_text()) + assert set(raw) == {"token", "email", "organization", "organization_uuid", "api_url"} From f903b5f4380d4704f98a55f9fddb7bfdbeb73e0b Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:02:54 +0000 Subject: [PATCH 06/19] feat(client): refresh a browser session on 401 access_token_expired ## Summary A device-flow session refreshes its pair only when a Bearer request is refused with `401 access_token_expired`: one refresh, one replay. The rotated pair is written atomically (0o600 temp file + os.replace). A pair already rotated by another CLI process is adopted; on `session_revoked` the file is re-read once (L36). Other 401 codes, 403s, legacy tokens and DAILYBOT_CLI_TOKEN never refresh. A transport failure or a non-401 on the refresh door is raised, never turned into an API-key fallback. ## Change Log - DailyBotClient._needs_refresh / _refresh_session in _request and _agent_request - config.update_token_pair: atomic replace - docs: CONFIGURATION.md refresh lifecycle, SECURITY.md refresh-token handling ## Risks - Rule 14 order and the host binding are unchanged; tests pin both Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 85 ++++++++ dailybot_cli/config.py | 11 +- docs/CONFIGURATION.md | 2 + docs/SECURITY.md | 12 +- tests/config_test.py | 24 ++ tests/credentials_refresh_test.py | 349 ++++++++++++++++++++++++++++++ 6 files changed, 481 insertions(+), 2 deletions(-) create mode 100644 tests/credentials_refresh_test.py diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 2f5822a8..84edb39b 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -1,6 +1,7 @@ """HTTP client for Dailybot CLI API endpoints.""" import functools +import os import platform import re import time @@ -22,6 +23,8 @@ get_api_key_source, get_api_url, get_login_token_for, + get_refresh_token_for, + update_token_pair, ) from dailybot_cli.install_method import detect_install_method @@ -85,6 +88,12 @@ def _base_headers() -> dict[str, str]: # RFC 8628 device flow (PLAN_002, frozen at checkpoint 1: DEVICE_FLOW_WIRE). DEVICE_CLIENT_ID: str = "dailybot-cli" DEVICE_GRANT_TYPE: str = "urn:ietf:params:oauth:grant-type:device_code" +# The only 401 that refreshes a device-flow pair (L36). Every other 401 code +# (refresh_token_expired, user_disabled, invalid_credentials, session_revoked) +# keeps the long-standing behaviour: no refresh loop. +ACCESS_TOKEN_EXPIRED_CODE: str = "access_token_expired" +SESSION_REVOKED_CODE: str = "session_revoked" +HTTP_UNAUTHORIZED: int = 401 # The person-shaped Tasks doors have a third refusal shape: `400 actor_required`, # meaning "this credential is an organization with nobody to be". It is the same @@ -614,6 +623,12 @@ def _agent_request( lambda: httpx.request(method, url, **kwargs), method=method ) + if self._needs_refresh(response) and self._refresh_session(): + kwargs["headers"] = self._agent_headers() + response = self._guard_transport( + lambda: httpx.request(method, url, **kwargs), method=method + ) + if _is_auth_retryable(response): alt: dict[str, str] | None = self._alt_auth_headers() if alt is not None: @@ -684,6 +699,15 @@ def _request( response: httpx.Response = self._dispatch_guarded(method, url, **kwargs) + if self._needs_refresh(response) and self._refresh_session(): + replay_headers: dict[str, str] = self._headers() + if files is not None or content is not None: + replay_headers.pop("Content-Type", None) + if extra_headers: + replay_headers.update(extra_headers) + kwargs["headers"] = replay_headers + response = self._dispatch_guarded(method, url, **kwargs) + if _is_auth_retryable(response) and not self._is_final_person_refusal(url, response): alt: dict[str, str] | None = self._alt_auth_headers() if alt is not None: @@ -699,6 +723,67 @@ def _request( return response + def _needs_refresh(self, response: httpx.Response) -> bool: + """A Bearer request refused with ``401 access_token_expired`` (and nothing else).""" + return ( + response.status_code == HTTP_UNAUTHORIZED + and self._agent_auth_mode == "bearer" + and _json_field(response, "code") == ACCESS_TOKEN_EXPIRED_CODE + ) + + def _refresh_session(self) -> bool: + """Rotate the stored device-flow pair once; ``True`` when a new access is in hand. + + Only the session ``dailybot login`` stored for this host refreshes: a legacy + token, a ``DAILYBOT_CLI_TOKEN`` and a pair issued by another host never do. + If another CLI process already rotated the file, its access is adopted + without a second refresh. On ``session_revoked`` the file is re-read once and + the refresh found there is tried if it differs (L36). Any other refusal + returns ``False``, so the caller keeps today's 401 handling. A transport + failure or a non-401 answer is raised instead: an infrastructure problem is + never a reason to fall back to another credential or to touch the session. + """ + if os.environ.get("DAILYBOT_CLI_TOKEN"): + return False + refresh: str | None = get_refresh_token_for(self.api_url) + if not refresh: + return False + stored_access: str | None = get_login_token_for(self.api_url) + if stored_access and stored_access != self.token: + self.token = stored_access + return True + try: + pair: dict[str, Any] = self.refresh_token_pair(refresh) + except APIError as error: + if error.status_code != HTTP_UNAUTHORIZED: + raise + if error.code != SESSION_REVOKED_CODE: + return False + reread: str | None = get_refresh_token_for(self.api_url) + if not reread or reread == refresh: + return False + try: + pair = self.refresh_token_pair(reread) + except APIError as second: + if second.status_code != HTTP_UNAUTHORIZED: + raise + return False + finally: + # The refresh door is unauthenticated; the replay is a Bearer request again. + self._agent_auth_mode = "bearer" + access: Any = pair.get("access") + new_refresh: Any = pair.get("refresh") + if not isinstance(access, str) or not access or not isinstance(new_refresh, str): + return False + update_token_pair( + access=access, + refresh=new_refresh, + expires_at=pair.get("expires_at"), + refresh_expires_at=pair.get("refresh_expires_at"), + ) + self.token = access + return True + def _is_final_person_refusal(self, url: str, response: httpx.Response) -> bool: """A Tasks door that refused the signed-in person keeps that answer. diff --git a/dailybot_cli/config.py b/dailybot_cli/config.py index 6dbfac80..da1cd2e2 100644 --- a/dailybot_cli/config.py +++ b/dailybot_cli/config.py @@ -187,7 +187,16 @@ def update_token_pair( "refresh_expires_at": refresh_expires_at, } ) - _write_secret_file(_credentials_path(), json.dumps(creds, indent=2)) + # Atomic: a concurrent CLI process reads either the old pair or the new one, + # never a truncated file. The temporary file is 0o600 from its first byte. + target: Path = _credentials_path() + staging: Path = target.with_name(f"{target.name}.{os.getpid()}.tmp") + try: + _write_secret_file(staging, json.dumps(creds, indent=2)) + os.replace(staging, target) + finally: + if staging.exists(): + staging.unlink() return True diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5f55d0f2..4c0a5ac0 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -30,6 +30,8 @@ The Dailybot CLI persists state in `~/.config/dailybot/` by default. The path ca Migration: none is needed. A legacy file keeps loading and authenticating unchanged, and `--email --code` still writes exactly the five legacy keys. The refresh token is bound to the issuing `api_url` like the access token (`get_refresh_token_for`), so it never travels to another host. An older CLI reading a device-session file uses the access token until it expires, then asks for `dailybot login` again. + Refresh lifecycle: the CLI refreshes a device-flow session only when a request is refused with `401 access_token_expired`. It rotates the pair once through `POST /v1/cli/auth/refresh/`, writes the new `token`, `refresh`, `expires_at` and `refresh_expires_at` in place (atomically, `0o600`), and replays the request once. The refresh token lasts 90 days from its last use and at most 365 days from the first sign-in; after that, `dailybot login --device` again. Details and failure handling: `docs/SECURITY.md` § Bearer Token Lifecycle. + **`config.json`** — extended via `save_config({...})`. Setting a key to `None` removes it. Accessed only through `load_config()` / `save_config()` — never read directly elsewhere. **`agents.json`** — `default` points to a profile slug under `profiles`. Slugs are derived from the agent name via `_slugify` (lowercase, alphanumeric + hyphens). When `save_agent_profile` is called and `default` is unset, the new profile becomes the default automatically. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 29a5045b..2904a7d9 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -282,7 +282,17 @@ The `org_cache.json` is cleared after a successful verify. - Revoked by `dailybot logout` (best-effort `POST /v1/cli/auth/logout/` + local file removal). - Treated as expired/invalid on a 401 from a Bearer-mode call → `_handle_response` rewrites the error to "Session expired. Run 'dailybot login' to re-authenticate." A 403 is an authorization refusal, not a dead session: it keeps the server's `detail` and `code`, and the command maps the code to a message. -There is no automatic refresh. Tokens have a server-defined lifetime; the user is expected to re-run `dailybot login` when prompted. +A legacy email-code session (`--email --code`) has no automatic refresh: its single token has a server-defined lifetime (90 days), and the user re-runs `dailybot login` when prompted. + +### Browser (device-flow) sessions: the refresh token + +`dailybot login --device` stores a short-lived access token (`dbc_at_…`, about 1 hour) in `token` and a refresh token (`dbc_rt_…`) in `refresh`, both in the same `0o600` `credentials.json`. Neither is ever printed, logged or put in an error message. + +- **When it refreshes.** Only a Bearer request answered `401` with `code: access_token_expired` refreshes (`DailyBotClient._refresh_session`): one `POST /v1/cli/auth/refresh/`, then one replay of the original request. Every other `401` code (`refresh_token_expired`, `user_disabled`, `invalid_credentials`, `session_revoked`) and every `403` keeps the behaviour above. A legacy token and a `DAILYBOT_CLI_TOKEN` are never refreshed. +- **Where it travels.** The refresh token is bound to the host that issued it, like the access token (`get_refresh_token_for`). The refresh door is unauthenticated: the refresh token in the body is the only credential sent, and no API key rides along. +- **Rotation.** Every refresh rotates the pair. The new pair replaces the old one atomically (a `0o600` temporary file, then `os.replace`), so a concurrent CLI process never reads a half-written file. If another process already rotated the file, its access token is adopted without a second refresh. On `session_revoked` the CLI re-reads the file once and retries with the refresh it finds there if it differs (the server returns the current pair for a refresh reused within 60 seconds); otherwise the user is asked to log in again. +- **Failures are not logouts.** A transport failure or a non-`401` answer on the refresh door (for example a `503`) is reported as such. It never falls back to the API key, never clears the stored session and never rewrites it. +- **Logout** revokes the whole pair (see `dailybot logout`). ## User-Scoped Commands — Privacy Considerations diff --git a/tests/config_test.py b/tests/config_test.py index 4095e4da..0dcd75e7 100644 --- a/tests/config_test.py +++ b/tests/config_test.py @@ -402,3 +402,27 @@ def test_the_refresh_token_keeps_the_host_binding(self, tmp_config: Path) -> Non self._save_pair() assert get_refresh_token_for("https://api.dailybot.com") == "dbc_rt_test-refresh" assert get_refresh_token_for("http://localhost:8000") is None + + +def test_rotating_the_pair_replaces_the_file_atomically( + tmp_config: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from dailybot_cli.config import update_token_pair + + save_credentials( + token="dbc_at_a", email="e", organization="o", organization_uuid="u", refresh="dbc_rt_a" + ) + replaced: list[tuple[str, str]] = [] + real_replace: Any = os.replace + + def spy(src: Any, dst: Any) -> None: + replaced.append((Path(src).name, Path(dst).name)) + real_replace(src, dst) + + monkeypatch.setattr("dailybot_cli.config.os.replace", spy) + update_token_pair(access="dbc_at_b", refresh="dbc_rt_b", expires_at=None) + assert replaced and replaced[0][1] == "credentials.json" + assert replaced[0][0].endswith(".tmp") + assert sorted(p.name for p in tmp_config.iterdir() if p.name.startswith("credentials")) == [ + "credentials.json" + ] diff --git a/tests/credentials_refresh_test.py b/tests/credentials_refresh_test.py new file mode 100644 index 00000000..43d8a620 --- /dev/null +++ b/tests/credentials_refresh_test.py @@ -0,0 +1,349 @@ +"""Refresh on `401 access_token_expired` (PLAN_002 T-refresh-on-401, frozen rule L36). + +The client refreshes a device-flow pair once and replays the request once. Only +that code refreshes; other 401s, 403s and legacy sessions keep today's behaviour. +HTTP is mocked at the call site with the recorded fixtures. +""" + +import json +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import httpx +import pytest + +from dailybot_cli.api_client import APIError, DailyBotClient, TransportError +from dailybot_cli.config import load_credentials, save_credentials +from tests.wire_fixture_loader import fixture_body, fixture_response + +API: str = "https://api.example.com" +OLD_ACCESS: str = "dbc_at_old-access" +OLD_REFRESH: str = "dbc_rt_old-refresh" +NEW: dict[str, Any] = fixture_body("refresh_success_200") + + +@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 _save_pair(access: str = OLD_ACCESS, refresh: str = OLD_REFRESH) -> None: + save_credentials( + token=access, + email="me@example.com", + organization="My Team", + organization_uuid="org-1", + api_url=API, + refresh=refresh, + expires_at="2030-01-01T00:00:00Z", + refresh_expires_at="2030-04-01T00:00:00Z", + ) + + +def _ok(body: dict[str, Any] | None = None) -> MagicMock: + response: MagicMock = MagicMock() + response.status_code = 200 + response.headers = {} + response.json.return_value = body if body is not None else {"ok": True} + return response + + +def _plain(status: int, body: dict[str, Any]) -> MagicMock: + response: MagicMock = MagicMock() + response.status_code = status + response.headers = {} + response.json.return_value = body + response.text = json.dumps(body) + return response + + +def _bearer(call: Any) -> str | None: + return call.kwargs["headers"].get("Authorization") + + +class TestRefreshThenReplay: + def test_a_user_request_refreshes_once_and_replays_once( + self, _isolated_environment: Path + ) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[fixture_response("bearer_access_token_expired_401"), _ok()], + ) as get, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ) as post, + ): + assert client.get_status() == {"ok": True} + assert post.call_count == 1 + assert post.call_args.args[0] == f"{API}/v1/cli/auth/refresh/" + assert post.call_args.kwargs["json"] == {"refresh": OLD_REFRESH} + assert [_bearer(c) for c in get.call_args_list] == [ + f"Bearer {OLD_ACCESS}", + f"Bearer {NEW['access']}", + ] + creds: dict[str, Any] | None = load_credentials() + assert creds is not None + assert creds["token"] == NEW["access"] + assert creds["refresh"] == NEW["refresh"] + assert creds["expires_at"] == NEW["expires_at"] + assert creds["email"] == "me@example.com" + mode: int = (_isolated_environment / "credentials.json").stat().st_mode & 0o777 + assert mode == 0o600 + + def test_an_agent_request_refreshes_too(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.request", + side_effect=[fixture_response("bearer_access_token_expired_401"), _ok()], + ) as request, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ), + ): + client.get_agent_health(agent_name="a") + assert _bearer(request.call_args_list[1]) == f"Bearer {NEW['access']}" + + def test_a_second_expiry_after_the_replay_does_not_loop(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[ + fixture_response("bearer_access_token_expired_401"), + fixture_response("bearer_access_token_expired_401"), + ], + ) as get, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ) as post, + pytest.raises(APIError), + ): + client.get_status() + assert post.call_count == 1 + assert get.call_count == 2 + + +class TestNoRefresh: + @pytest.mark.parametrize("code", ["session_revoked", "user_disabled", "invalid_credentials"]) + def test_other_401_codes_never_refresh(self, code: str) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response(f"bearer_{code}_401"), + ), + patch("dailybot_cli.api_client.httpx.post") as post, + pytest.raises(APIError) as caught, + ): + client.get_status() + post.assert_not_called() + assert caught.value.status_code == 401 + + def test_a_403_never_refreshes(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=_plain(403, {"detail": "no", "code": "access_token_expired"}), + ), + patch("dailybot_cli.api_client.httpx.post") as post, + pytest.raises(APIError), + ): + client.get_status() + post.assert_not_called() + + def test_a_legacy_session_is_never_refreshed(self) -> None: + save_credentials( + token="legacy-test-token", + email="me@example.com", + organization="O", + organization_uuid="org-1", + api_url=API, + ) + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ), + patch("dailybot_cli.api_client.httpx.post") as post, + pytest.raises(APIError), + ): + client.get_status() + post.assert_not_called() + + def test_an_explicit_env_token_is_never_refreshed( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + _save_pair() + monkeypatch.setenv("DAILYBOT_CLI_TOKEN", "dbc_at_from-env") + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ), + patch("dailybot_cli.api_client.httpx.post") as post, + pytest.raises(APIError), + ): + client.get_status() + post.assert_not_called() + + def test_a_pair_from_another_host_is_never_refreshed(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url="http://localhost:8000", token=OLD_ACCESS) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ), + patch("dailybot_cli.api_client.httpx.post") as post, + pytest.raises(APIError), + ): + client.get_status() + post.assert_not_called() + + +class TestRefreshFailures: + @pytest.mark.parametrize("code", ["refresh_token_expired", "user_disabled"]) + def test_a_refused_refresh_keeps_todays_fallback(self, code: str) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") + with ( + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[fixture_response("bearer_access_token_expired_401"), _ok()], + ) as get, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response(f"refresh_{code}_401"), + ), + ): + 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 + + def test_a_transport_failure_never_falls_back_or_changes_credentials(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ) as get, + patch("dailybot_cli.api_client.httpx.post", side_effect=httpx.ConnectError("offline")), + pytest.raises(TransportError), + ): + client.get_status() + assert get.call_count == 1 + creds: dict[str, Any] | None = load_credentials() + assert creds is not None and creds["refresh"] == OLD_REFRESH + + def test_a_503_on_refresh_never_falls_back(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ) as get, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("auth_backend_unavailable_503"), + ), + pytest.raises(APIError) as caught, + ): + client.get_status() + assert caught.value.status_code == 503 + assert get.call_count == 1 + + +class TestTwoProcesses: + def test_session_revoked_rereads_the_file_once(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + sent: list[dict[str, Any]] = [] + + def refresh_door(url: str, **kwargs: Any) -> MagicMock: + sent.append(kwargs["json"]) + if len(sent) == 1: + # Another CLI process won the race and rotated the file meanwhile. + _save_pair(access="dbc_at_winner", refresh="dbc_rt_winner") + return fixture_response("refresh_session_revoked_401") + return fixture_response("refresh_success_200") + + with ( + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[fixture_response("bearer_access_token_expired_401"), _ok()], + ), + patch("dailybot_cli.api_client.httpx.post", side_effect=refresh_door), + ): + assert client.get_status() == {"ok": True} + assert sent == [{"refresh": OLD_REFRESH}, {"refresh": "dbc_rt_winner"}] + + def test_session_revoked_with_an_unchanged_file_stops(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ), + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_session_revoked_401"), + ) as post, + pytest.raises(APIError), + ): + client.get_status() + assert post.call_count == 1 + + def test_a_pair_already_rotated_by_another_process_is_adopted(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + _save_pair(access="dbc_at_winner", refresh="dbc_rt_winner") + with ( + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[fixture_response("bearer_access_token_expired_401"), _ok()], + ) as get, + patch("dailybot_cli.api_client.httpx.post") as post, + ): + assert client.get_status() == {"ok": True} + post.assert_not_called() + assert _bearer(get.call_args_list[1]) == "Bearer dbc_at_winner" + + +def test_tokens_never_reach_an_error_message() -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ), + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_refresh_token_expired_401"), + ), + pytest.raises(APIError) as caught, + ): + client.get_status() + for secret in (OLD_ACCESS, OLD_REFRESH): + assert secret not in str(caught.value) + assert secret not in caught.value.detail From 38d8342162eac1de23d8213caad372256ffd03b0 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:10:05 +0000 Subject: [PATCH 07/19] feat(auth): revoke the whole browser session on logout ## Summary `dailybot logout` on a device-flow session sends the Bearer access while it is valid, and the unauthenticated `{"refresh": ...}` body once the access has expired (locally or as the server answers), so logout never needs a refresh first. A legacy token's request is unchanged. When a pair could not be revoked, the CLI says so after removing the local file. ## Change Log - DailyBotClient.logout(refresh=, access_expired=) + _logout_with_refresh - config.is_access_token_expired - docs/CONFIGURATION.md logout note ## Risks - None for legacy sessions: same request, same output Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 29 ++++++- dailybot_cli/commands/auth.py | 27 ++++-- dailybot_cli/config.py | 20 +++++ docs/CONFIGURATION.md | 2 + tests/logout_pair_test.py | 158 ++++++++++++++++++++++++++++++++++ 5 files changed, 228 insertions(+), 8 deletions(-) create mode 100644 tests/logout_pair_test.py diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 84edb39b..a901085d 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -1214,13 +1214,21 @@ def auth_status(self) -> dict[str, Any]: response: httpx.Response = self._request("GET", f"{self.api_url}/v1/cli/auth/status/") return self._handle_response(response) - def logout(self) -> dict[str, Any]: + def logout(self, refresh: str | None = None, *, access_expired: bool = False) -> dict[str, Any]: """POST /v1/cli/auth/logout/ Uses ``_headers`` directly (no fallback) because logout is a Bearer-only lifecycle operation — retrying with an API key would neither succeed nor be semantically meaningful. + + For a device-flow pair (``refresh`` given) the Bearer form revokes the whole + family. When the access token has expired (``access_expired``, or the server + answers ``401 access_token_expired``) the unauthenticated ``{"refresh": ...}`` + body form revokes it instead, without a refresh round-trip. Without + ``refresh`` this is today's call, byte for byte. """ + if refresh and access_expired: + return self._logout_with_refresh(refresh) response: httpx.Response = self._guard_transport( lambda: httpx.post( f"{self.api_url}/v1/cli/auth/logout/", @@ -1229,6 +1237,25 @@ def logout(self) -> dict[str, Any]: ), method="POST", ) + if ( + refresh + and response.status_code == HTTP_UNAUTHORIZED + and _json_field(response, "code") == ACCESS_TOKEN_EXPIRED_CODE + ): + return self._logout_with_refresh(refresh) + return self._handle_response(response) + + def _logout_with_refresh(self, refresh: str) -> dict[str, Any]: + """The unauthenticated logout form: the refresh token in the body is the proof.""" + response: httpx.Response = self._guard_transport( + lambda: httpx.post( + f"{self.api_url}/v1/cli/auth/logout/", + json={"refresh": refresh}, + headers=self._headers(authenticated=False), + timeout=self.timeout, + ), + method="POST", + ) return self._handle_response(response) # --- Update/Status endpoints --- diff --git a/dailybot_cli/commands/auth.py b/dailybot_cli/commands/auth.py index 2e430226..9407ce68 100644 --- a/dailybot_cli/commands/auth.py +++ b/dailybot_cli/commands/auth.py @@ -15,7 +15,9 @@ get_active_env_profile, get_api_key, get_api_url, + get_refresh_token_for, get_token, + is_access_token_expired, load_credentials, load_org_cache, login_token_origin_url, @@ -370,23 +372,34 @@ def logout() -> None: # Revoke every session this invocation knows: a DAILYBOT_CLI_TOKEN on the # current API (the caller's explicit session), and a stored login on the # host that issued it. Best-effort each; local credentials are cleared after. - targets: list[tuple[str, str]] = [] + # A device-flow pair is revoked as a whole family: with the Bearer access, or + # with the refresh token alone once the access has expired. + targets: list[tuple[str, str, str | None]] = [] env_token: str | None = os.environ.get("DAILYBOT_CLI_TOKEN") if env_token: - targets.append((get_api_url(), env_token)) + targets.append((get_api_url(), env_token, None)) stored: dict[str, Any] | None = load_credentials() if stored and stored.get("token"): - targets.append((login_token_origin_url(), str(stored["token"]))) + origin: str = login_token_origin_url() + targets.append((origin, str(stored["token"]), get_refresh_token_for(origin))) if not targets: - targets.append((login_token_origin_url(), token)) - for api_url, session_token in targets: + targets.append((login_token_origin_url(), token, None)) + access_expired: bool = is_access_token_expired() + unrevoked_pair: bool = False + for api_url, session_token, refresh in targets: client: DailyBotClient = DailyBotClient(api_url=api_url, token=session_token) client.api_key = None try: with console.status("Logging out..."): - client.logout() + client.logout(refresh=refresh, access_expired=access_expired and bool(refresh)) except APIError: - pass # Revoke best-effort; clear local credentials regardless + # Revoke best-effort; clear local credentials regardless + unrevoked_pair = unrevoked_pair or bool(refresh) clear_credentials() + if unrevoked_pair: + print_warning( + "Could not revoke the session on the server; it stays valid there until it " + "expires. The local credentials were removed." + ) print_success("Logged out.") diff --git a/dailybot_cli/config.py b/dailybot_cli/config.py index da1cd2e2..cd08d3f3 100644 --- a/dailybot_cli/config.py +++ b/dailybot_cli/config.py @@ -2,6 +2,7 @@ import json import os +from datetime import datetime, timezone from pathlib import Path from typing import Any from urllib.parse import SplitResult, urlsplit @@ -316,6 +317,25 @@ def get_login_token_for(api_url: str) -> str | None: return str(token) if token else None +def is_access_token_expired(now: datetime | None = None) -> bool: + """Whether a device-flow session's stored ``expires_at`` is already in the past. + + ``False`` for a legacy session, a missing or unreadable date: only a known + expiry counts, and the server's answer stays authoritative either way. + """ + creds: dict[str, Any] | None = load_credentials() + raw: Any = (creds or {}).get("expires_at") + if not isinstance(raw, str) or not raw: + return False + try: + expires: datetime = datetime.fromisoformat(raw.replace("Z", "+00:00")) + except ValueError: + return False + if expires.tzinfo is None: + expires = expires.replace(tzinfo=timezone.utc) + return expires <= (now or datetime.now(timezone.utc)) + + def get_refresh_token_for(api_url: str) -> str | None: """The stored refresh token, only when ``api_url`` is the host that issued it. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 4c0a5ac0..66737c2d 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -32,6 +32,8 @@ The Dailybot CLI persists state in `~/.config/dailybot/` by default. The path ca Refresh lifecycle: the CLI refreshes a device-flow session only when a request is refused with `401 access_token_expired`. It rotates the pair once through `POST /v1/cli/auth/refresh/`, writes the new `token`, `refresh`, `expires_at` and `refresh_expires_at` in place (atomically, `0o600`), and replays the request once. The refresh token lasts 90 days from its last use and at most 365 days from the first sign-in; after that, `dailybot login --device` again. Details and failure handling: `docs/SECURITY.md` § Bearer Token Lifecycle. + Logout: `dailybot logout` revokes a device-flow session as a whole (access and refresh). While the access token is valid it sends `Authorization: Bearer `; once `expires_at` has passed, or the server answers `401 access_token_expired`, it sends the body `{"refresh": ""}` with no credential header instead, so logging out never needs a refresh first. The server answers `200` even for an already revoked session. The local file is removed either way; if the server could not be reached or refused, the CLI says the session stays valid there until it expires. A legacy session's logout request is unchanged. + **`config.json`** — extended via `save_config({...})`. Setting a key to `None` removes it. Accessed only through `load_config()` / `save_config()` — never read directly elsewhere. **`agents.json`** — `default` points to a profile slug under `profiles`. Slugs are derived from the agent name via `_slugify` (lowercase, alphanumeric + hyphens). When `save_agent_profile` is called and `default` is unset, the new profile becomes the default automatically. diff --git a/tests/logout_pair_test.py b/tests/logout_pair_test.py new file mode 100644 index 00000000..2d6b72bc --- /dev/null +++ b/tests/logout_pair_test.py @@ -0,0 +1,158 @@ +"""`dailybot logout` revokes a device-flow pair (PLAN_002 T-logout-pair, DEVICE_FLOW_WIRE §5). + +Bearer form while the access token is valid; the `{"refresh": ...}` body form when it +has expired (locally, or as the server answers), with no refresh round-trip. Legacy +tokens keep today's request byte for byte. +""" + +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest +from click.testing import CliRunner, Result + +from dailybot_cli.api_client import DailyBotClient +from dailybot_cli.config import load_credentials, save_credentials +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_response + +API: str = "https://api.example.com" +ACCESS: str = "dbc_at_live-access" +REFRESH: str = "dbc_rt_live-refresh" +LOGOUT_URL: str = f"{API}/v1/cli/auth/logout/" +FUTURE: str = "2999-01-01T00:00:00Z" +PAST: str = "2000-01-01T00:00:00Z" + + +@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) + + +@pytest.fixture +def runner() -> CliRunner: + return CliRunner() + + +def _save_pair(expires_at: str = FUTURE) -> None: + save_credentials( + token=ACCESS, + email="me@example.com", + organization="My Team", + organization_uuid="org-1", + api_url=API, + refresh=REFRESH, + expires_at=expires_at, + refresh_expires_at=FUTURE, + ) + + +def _logout(runner: CliRunner) -> tuple[Result, MagicMock]: + with patch( + "dailybot_cli.api_client.httpx.post", return_value=fixture_response("logout_200") + ) as post: + result: Result = runner.invoke(cli, ["logout"]) + return result, post + + +class TestPairLogout: + def test_a_valid_access_uses_the_bearer_form(self, runner: CliRunner) -> None: + _save_pair() + result, post = _logout(runner) + assert result.exit_code == 0, result.output + assert post.call_count == 1 + assert post.call_args.args[0] == LOGOUT_URL + assert post.call_args.kwargs["headers"]["Authorization"] == f"Bearer {ACCESS}" + assert "json" not in post.call_args.kwargs + assert load_credentials() is None + + def test_an_expired_access_uses_the_refresh_body_without_refreshing( + self, runner: CliRunner + ) -> None: + _save_pair(expires_at=PAST) + result, post = _logout(runner) + assert result.exit_code == 0, result.output + assert [c.args[0] for c in post.call_args_list] == [LOGOUT_URL] + assert post.call_args.kwargs["json"] == {"refresh": REFRESH} + assert "Authorization" not in post.call_args.kwargs["headers"] + assert "X-API-KEY" not in post.call_args.kwargs["headers"] + assert load_credentials() is None + + def test_a_server_expired_access_retries_with_the_refresh_body(self, runner: CliRunner) -> None: + _save_pair() + with patch( + "dailybot_cli.api_client.httpx.post", + side_effect=[ + fixture_response("bearer_access_token_expired_401"), + fixture_response("logout_200"), + ], + ) as post: + result: Result = runner.invoke(cli, ["logout"]) + assert result.exit_code == 0, result.output + assert [c.args[0] for c in post.call_args_list] == [LOGOUT_URL, LOGOUT_URL] + assert post.call_args_list[1].kwargs["json"] == {"refresh": REFRESH} + assert "Authorization" not in post.call_args_list[1].kwargs["headers"] + assert load_credentials() is None + + def test_an_already_revoked_family_still_logs_out(self, runner: CliRunner) -> None: + _save_pair(expires_at=PAST) + result, _post = _logout(runner) + assert result.exit_code == 0 + assert "Logged out" in result.output + assert load_credentials() is None + + def test_a_failed_revocation_says_so(self, runner: CliRunner) -> None: + _save_pair() + with patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_user_disabled_401"), + ): + result: Result = runner.invoke(cli, ["logout"]) + assert result.exit_code == 0 + assert "could not revoke" in result.output.lower() + assert load_credentials() is None + + def test_tokens_never_reach_the_output(self, runner: CliRunner) -> None: + _save_pair(expires_at=PAST) + result, _post = _logout(runner) + assert ACCESS not in result.output + assert REFRESH not in result.output + + +class TestLegacyLogout: + def test_a_legacy_token_keeps_todays_request(self, runner: CliRunner) -> None: + save_credentials( + token="legacy-test-token", + email="me@example.com", + organization="O", + organization_uuid="org-1", + api_url=API, + ) + result, post = _logout(runner) + assert result.exit_code == 0, result.output + assert post.call_count == 1 + assert post.call_args.kwargs["headers"]["Authorization"] == "Bearer legacy-test-token" + assert "json" not in post.call_args.kwargs + assert load_credentials() is None + + +class TestClientLogout: + def test_the_refresh_body_form(self) -> None: + client: DailyBotClient = DailyBotClient(api_url=API, token=ACCESS, api_key="test-key") + with patch( + "dailybot_cli.api_client.httpx.post", return_value=fixture_response("logout_200") + ) as post: + result: dict[str, Any] = client.logout(refresh=REFRESH, access_expired=True) + assert result == {"detail": "Successfully logged out."} + headers: dict[str, str] = post.call_args.kwargs["headers"] + assert "Authorization" not in headers and "X-API-KEY" not in headers + + def test_without_a_refresh_it_is_todays_call(self) -> None: + client: DailyBotClient = DailyBotClient(api_url=API, token="legacy-test-token") + with patch( + "dailybot_cli.api_client.httpx.post", return_value=fixture_response("logout_200") + ) as post: + client.logout() + assert post.call_count == 1 + assert "json" not in post.call_args.kwargs From c8c3cbd1e4070c734a628e99108ac46f9ae832e5 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:11:46 +0000 Subject: [PATCH 08/19] test(tests): make the device-login deadline test cheap Co-Authored-By: Claude Opus 5.5 --- tests/device_login_test.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/device_login_test.py b/tests/device_login_test.py index f4ea89cb..44e11788 100644 --- a/tests/device_login_test.py +++ b/tests/device_login_test.py @@ -157,14 +157,17 @@ def tick(seconds: float) -> None: clock[0] += seconds sleeps.side_effect = tick - pending: list[MagicMock] = [ - fixture_response("device_token_authorization_pending_400") for _ in range(200) - ] + pending: MagicMock = fixture_response("device_token_authorization_pending_400") + start: MagicMock = fixture_response("device_start_200") + + def door(url: str, **_kwargs: Any) -> MagicMock: + return start if url.endswith("/v1/cli/auth/device/") else pending + with ( patch( "dailybot_cli.commands._device_login.time.monotonic", side_effect=lambda: clock[0] ), - patch(POST, side_effect=[fixture_response("device_start_200"), *pending]), + patch(POST, side_effect=door), ): result: Result = _login(runner) assert result.exit_code == 1 From 58cb93748f92fa593b07ce22ec2e70b2a30d330c Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:15:45 +0000 Subject: [PATCH 09/19] feat(client): treat 503 auth_backend_unavailable as transient ## Summary A `503` with `code: auth_backend_unavailable` is retried 3 times, each waiting `min(Retry-After, 5 s)` (2 s when absent), at the send level, so it never reaches the 401 refresh or the API-key fallback and never touches credentials.json. After the budget, commands print "Dailybot sign-in is temporarily unavailable" and exit 6 (wait and retry); logout keeps the local session so it can be retried. Defensive: CLI tokens are DB-validated and should never meet this 503. ## Change Log - AUTH_BACKEND_* constants, _retry_auth_backend in _guard_transport and _dispatch_guarded - ERROR_CODE_MESSAGES entry and exit mapping; logout guard - docs/TROUBLESHOOTING.md: the 503 and the device-login outcomes ## Risks - Other 503s are unchanged (no retry, same rendering) Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 50 +++++- dailybot_cli/commands/auth.py | 8 +- dailybot_cli/commands/public_api_helpers.py | 10 +- docs/TROUBLESHOOTING.md | 8 + tests/auth_backend_unavailable_test.py | 175 ++++++++++++++++++++ 5 files changed, 245 insertions(+), 6 deletions(-) create mode 100644 tests/auth_backend_unavailable_test.py diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index a901085d..4b47b273 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -95,6 +95,15 @@ def _base_headers() -> dict[str, str]: SESSION_REVOKED_CODE: str = "session_revoked" HTTP_UNAUTHORIZED: int = 401 +# 503 auth_backend_unavailable (CONTRACT_SESSION §7, W1, L38): the server's auth +# backend is briefly down. Transient by definition: retried with a bounded wait, +# never treated as an expired session, a refresh trigger or a credential fallback. +AUTH_BACKEND_UNAVAILABLE_CODE: str = "auth_backend_unavailable" +HTTP_SERVICE_UNAVAILABLE: int = 503 +AUTH_BACKEND_MAX_RETRIES: int = 3 +AUTH_BACKEND_MAX_WAIT_SECS: float = 5.0 +AUTH_BACKEND_DEFAULT_RETRY_AFTER_SECS: float = 2.0 + # The person-shaped Tasks doors have a third refusal shape: `400 actor_required`, # meaning "this credential is an organization with nobody to be". It is the same # condition as a 401 — the wrong *kind* of credential was presented — but it does @@ -425,6 +434,39 @@ def _json_field(response: httpx.Response, key: str) -> Any: return body.get(key) if isinstance(body, dict) else None +def _is_auth_backend_unavailable(response: httpx.Response) -> bool: + return ( + response.status_code == HTTP_SERVICE_UNAVAILABLE + and _json_field(response, "code") == AUTH_BACKEND_UNAVAILABLE_CODE + ) + + +def _auth_backend_wait(response: httpx.Response) -> float: + """``Retry-After`` in seconds, defaulted when absent or unreadable, capped at 5 s.""" + raw: Any = response.headers.get("Retry-After") + try: + wait: float = float(raw) if raw is not None else AUTH_BACKEND_DEFAULT_RETRY_AFTER_SECS + except (TypeError, ValueError): + wait = AUTH_BACKEND_DEFAULT_RETRY_AFTER_SECS + return min(max(wait, 0.0), AUTH_BACKEND_MAX_WAIT_SECS) + + +def _retry_auth_backend(send: Callable[[], httpx.Response]) -> httpx.Response: + """Send, retrying a ``503 auth_backend_unavailable`` up to the bounded budget. + + The refusal comes from the authentication layer, before any view runs, so a + retried write is never applied twice. ``time.sleep`` is referenced through the + module so tests can patch it. + """ + response: httpx.Response = send() + attempt: int = 0 + while _is_auth_backend_unavailable(response) and attempt < AUTH_BACKEND_MAX_RETRIES: + time.sleep(_auth_backend_wait(response)) + attempt += 1 + response = send() + return response + + def _invalid_identifier() -> APIError: """The refusal for an identifier that would change which door a path reaches. @@ -856,7 +898,7 @@ def _guard_transport( of the documented transport exit. """ try: - return send() + return _retry_auth_backend(send) except httpx.HTTPError as exc: if timeout_message and isinstance(exc, httpx.TimeoutException): raise TransportTimeout(timeout_message) from exc @@ -879,7 +921,9 @@ def _dispatch_guarded(self, method: str, url: str, **kwargs: Any) -> httpx.Respo isinstance(params, dict) and str(params.get("dry_run")).lower() in {"true", "1"} ) try: - return self._dispatch_http(method, url, **kwargs) + # The one server-signalled exception: a 503 auth_backend_unavailable is + # retried with a bounded wait (`_retry_auth_backend`). + return _retry_auth_backend(lambda: self._dispatch_http(method, url, **kwargs)) except httpx.HTTPError as exc: # No retry on purpose. The bounded 429 backoff in `_send_with_retry` # is the only retry this client has; silently retrying a connection @@ -934,7 +978,7 @@ def _handle_response(self, response: httpx.Response) -> dict[str, Any]: if response.status_code == 401 and self._agent_auth_mode == "bearer": detail = "Session expired. Run 'dailybot login' to re-authenticate." retry_after: float | None = None - if response.status_code == 429: + if response.status_code == 429 or code == AUTH_BACKEND_UNAVAILABLE_CODE: raw_retry: str | None = response.headers.get("Retry-After") if raw_retry: try: diff --git a/dailybot_cli/commands/auth.py b/dailybot_cli/commands/auth.py index 9407ce68..0fefce03 100644 --- a/dailybot_cli/commands/auth.py +++ b/dailybot_cli/commands/auth.py @@ -6,8 +6,9 @@ import click import questionary -from dailybot_cli.api_client import APIError, DailyBotClient +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.config import ( RepoEnvError, clear_credentials, @@ -392,7 +393,10 @@ def logout() -> None: try: with console.status("Logging out..."): client.logout(refresh=refresh, access_expired=access_expired and bool(refresh)) - except APIError: + except APIError as error: + if error.code == AUTH_BACKEND_UNAVAILABLE_CODE: + # Transient: keep the session so logout can be retried and revoke it. + exit_for_api_error(error, json_mode=False) # Revoke best-effort; clear local credentials regardless unrevoked_pair = unrevoked_pair or bool(refresh) diff --git a/dailybot_cli/commands/public_api_helpers.py b/dailybot_cli/commands/public_api_helpers.py index 628c4df4..00db56fb 100644 --- a/dailybot_cli/commands/public_api_helpers.py +++ b/dailybot_cli/commands/public_api_helpers.py @@ -8,7 +8,7 @@ import click import questionary -from dailybot_cli.api_client import APIError, DailyBotClient +from dailybot_cli.api_client import AUTH_BACKEND_UNAVAILABLE_CODE, APIError, DailyBotClient from dailybot_cli.config import get_agent_auth, get_org_plan, get_person_token, load_credentials from dailybot_cli.display import error_console, print_error, print_info @@ -52,6 +52,10 @@ # Server-side error codes from {detail, code} responses. Kept here so command # handlers and tests share a single source of truth. ERROR_CODE_MESSAGES: dict[str, str] = { + # --- Sessions (PLAN_002, CONTRACT_SESSION §7) ----------------------------- + AUTH_BACKEND_UNAVAILABLE_CODE: ( + "Dailybot sign-in is temporarily unavailable. Your session is fine; try again in a moment." + ), # --- Tasks (/v1/plan/*) ------------------------------------------------- # Written against what the server actually returned in the live probe # recorded in the plan's PERMISSION_MATRIX_OBSERVED.md, not against prose. @@ -1087,6 +1091,10 @@ def exit_for_api_error( elif exc.status_code == 400: message = mapped_message or exc.detail exit_code = EXIT_USAGE_ERROR + elif code == AUTH_BACKEND_UNAVAILABLE_CODE: + # Transient: the session is fine, the server's sign-in backend is not. + message = mapped_message or exc.detail + exit_code = EXIT_RATE_LIMITED else: message = mapped_message or exc.detail exit_code = 1 diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 53d48ada..686a68e1 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -41,6 +41,14 @@ 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. +### "Dailybot sign-in is temporarily unavailable" (`auth_backend_unavailable`, exit 6) + +The server answered `503` with `code: auth_backend_unavailable`: its sign-in backend is briefly down. Your session is fine. The CLI already retried 3 times, waiting what the server's `Retry-After` asked for (at most 5 seconds each), before giving up. It never treats this as an expired session: it does not refresh, does not switch to your API key, and does not change `credentials.json`. Wait a moment and run the command again. `dailybot logout` on this error keeps your local session so you can retry the logout and revoke it on the server. + +### `dailybot login --device`: "The sign-in code expired" / "was denied" + +The browser sign-in waits up to 10 minutes for you to approve the code. "Expired" means it was not approved in time; "denied" means someone pressed Deny on the page. Nothing is saved in either case: run `dailybot login --device` again. If the server does not offer browser sign-in yet, the command continues with the email code by itself. + ### Login OTP never arrives - Check spam. diff --git a/tests/auth_backend_unavailable_test.py b/tests/auth_backend_unavailable_test.py new file mode 100644 index 00000000..bf44155f --- /dev/null +++ b/tests/auth_backend_unavailable_test.py @@ -0,0 +1,175 @@ +"""`503 auth_backend_unavailable` is transient, never a logout (PLAN_002 T-auth-backend-503). + +Frozen (W1, L38): `Retry-After: 2`, server range 1-5 s; the CLI retries 3 times, +each waiting `min(Retry-After, 5)`. CLI tokens are DB-validated and should never +meet this 503; the handling is defensive and must never refresh, fall back to the +API key, or touch `credentials.json`. +""" + +import json +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 ( + AUTH_BACKEND_MAX_RETRIES, + AUTH_BACKEND_MAX_WAIT_SECS, + APIError, + DailyBotClient, +) +from dailybot_cli.commands.public_api_helpers import EXIT_RATE_LIMITED, exit_for_api_error +from dailybot_cli.config import save_credentials +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_response + +API: str = "https://api.example.com" +SLEEP: str = "dailybot_cli.api_client.time.sleep" + + +@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) + + +@pytest.fixture +def pair_file(_isolated_environment: Path) -> Path: + save_credentials( + token="dbc_at_access", + email="me@example.com", + organization="My Team", + organization_uuid="org-1", + api_url=API, + refresh="dbc_rt_refresh", + expires_at="2999-01-01T00:00:00Z", + refresh_expires_at="2999-01-01T00:00:00Z", + ) + return _isolated_environment / "credentials.json" + + +def _unavailable(retry_after: str | None = "2") -> MagicMock: + response: MagicMock = fixture_response("auth_backend_unavailable_503") + response.headers = {} if retry_after is None else {"Retry-After": retry_after} + return response + + +def _ok() -> MagicMock: + response: MagicMock = MagicMock() + response.status_code = 200 + response.headers = {} + response.json.return_value = {"ok": True} + return response + + +class TestBoundedRetry: + def test_the_budget_then_a_transient_error(self, pair_file: Path) -> None: + before: bytes = pair_file.read_bytes() + client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") + with ( + patch(SLEEP) as sleep, + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[_unavailable() for _ in range(AUTH_BACKEND_MAX_RETRIES + 1)], + ) as get, + patch("dailybot_cli.api_client.httpx.post") as post, + pytest.raises(APIError) as caught, + ): + client.get_status() + assert caught.value.status_code == 503 + assert caught.value.code == "auth_backend_unavailable" + assert "Session expired" not in caught.value.detail + assert get.call_count == AUTH_BACKEND_MAX_RETRIES + 1 == 4 + assert [c.args[0] for c in sleep.call_args_list] == [2.0, 2.0, 2.0] + post.assert_not_called() # no refresh + for call in get.call_args_list: + assert "X-API-KEY" not in call.kwargs["headers"] # no API-key fallback + assert pair_file.read_bytes() == before + + def test_a_recovery_inside_the_budget_succeeds(self, pair_file: Path) -> None: + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch(SLEEP) as sleep, + patch("dailybot_cli.api_client.httpx.get", side_effect=[_unavailable(), _ok()]), + ): + assert client.get_status() == {"ok": True} + assert sleep.call_count == 1 + + @pytest.mark.parametrize( + "header,wait", [("1", 1.0), ("9", AUTH_BACKEND_MAX_WAIT_SECS), (None, 2.0), ("soon", 2.0)] + ) + def test_retry_after_is_honoured_and_capped( + self, pair_file: Path, header: str | None, wait: float + ) -> None: + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch(SLEEP) as sleep, + patch("dailybot_cli.api_client.httpx.get", side_effect=[_unavailable(header), _ok()]), + ): + client.get_status() + assert sleep.call_args.args[0] == wait + + def test_the_agent_path_retries_too(self, pair_file: Path) -> None: + client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") + with ( + patch(SLEEP), + patch( + "dailybot_cli.api_client.httpx.request", side_effect=[_unavailable(), _ok()] + ) as request, + ): + client.get_agent_health(agent_name="a") + assert request.call_count == 2 + assert ( + request.call_args_list[1].kwargs["headers"]["Authorization"] == "Bearer dbc_at_access" + ) + + def test_a_plain_503_is_not_retried(self, pair_file: Path) -> None: + client: DailyBotClient = DailyBotClient(api_url=API) + plain: MagicMock = _ok() + plain.status_code = 503 + plain.json.return_value = {"detail": "Maintenance."} + with ( + patch(SLEEP) as sleep, + patch("dailybot_cli.api_client.httpx.get", return_value=plain), + pytest.raises(APIError), + ): + client.get_status() + sleep.assert_not_called() + + +class TestRendering: + def test_a_transient_message_and_the_wait_and_retry_exit( + self, capsys: pytest.CaptureFixture[str] + ) -> None: + error: APIError = APIError(503, "x", code="auth_backend_unavailable", retry_after=2.0) + with pytest.raises(SystemExit) as caught: + exit_for_api_error(error, json_mode=False) + assert caught.value.code == EXIT_RATE_LIMITED + err: str = capsys.readouterr().err + assert "temporarily unavailable" in err.lower() + assert "login" not in err.lower() + + def test_json_mode_carries_the_code(self, capsys: pytest.CaptureFixture[str]) -> None: + error: APIError = APIError(503, "x", code="auth_backend_unavailable", retry_after=2.0) + with pytest.raises(SystemExit): + exit_for_api_error(error, json_mode=True) + payload: dict[str, Any] = json.loads(capsys.readouterr().out) + assert payload["code"] == "auth_backend_unavailable" + assert payload["status"] == 503 + + +def test_logout_on_503_keeps_the_credentials(pair_file: Path) -> None: + before: bytes = pair_file.read_bytes() + with ( + patch(SLEEP), + patch( + "dailybot_cli.api_client.httpx.post", + side_effect=[_unavailable() for _ in range(AUTH_BACKEND_MAX_RETRIES + 1)], + ), + ): + result: Result = CliRunner().invoke(cli, ["logout"]) + assert result.exit_code == EXIT_RATE_LIMITED + assert pair_file.read_bytes() == before + assert "Logged out" not in result.output From 35439dec1c58974a15d436fe11b7053eb0358f4a Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:17:08 +0000 Subject: [PATCH 10/19] feat(auth): mark standalone Dailybot organizations in the login picker ## Summary Org selection lists that include standalone organizations (frozen marker `standalone: true`) now label them " (Dailybot)" in the interactive and numbered pickers, so a Slack workspace and the standalone org with the same name are told apart. `--org ` resolves them as any other org; the machine-pipeable `_print_org_list` lines are unchanged, and agents.json is never touched by a login. ## Change Log - org_choice_label + STANDALONE_ORG_HINT in commands/auth.py - tests with the recorded selection fixture (picker, numbered, --org) ## Risks - None: the label is display-only; agent orgs (platform dailybot without the marker) keep their plain name Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/commands/auth.py | 18 +++- tests/standalone_org_login_test.py | 155 +++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+), 2 deletions(-) create mode 100644 tests/standalone_org_login_test.py diff --git a/dailybot_cli/commands/auth.py b/dailybot_cli/commands/auth.py index 0fefce03..f7c4ca6d 100644 --- a/dailybot_cli/commands/auth.py +++ b/dailybot_cli/commands/auth.py @@ -62,11 +62,25 @@ def _warn_if_env_json_redirects_login() -> None: ) +STANDALONE_ORG_HINT: str = " (Dailybot)" + + +def org_choice_label(org: dict[str, Any]) -> str: + """An org's name in a picker, marking a standalone Dailybot organization. + + The frozen marker is ``standalone: true`` (W2), never ``platform == "dailybot"`` + alone: agent organizations are ``dailybot`` too and are not standalone. It tells + apart a Slack workspace and the standalone organization that share a name. + """ + name: str = str(org.get("name", "Unknown")) + return f"{name}{STANDALONE_ORG_HINT}" if org.get("standalone") is True else name + + def _prompt_org_selection_numbered(organizations: list[dict[str, Any]]) -> dict[str, Any]: """Numbered org picker — fallback when questionary TUI is unavailable.""" print_info("You belong to multiple organizations. Select one by number:") for index, org in enumerate(organizations, start=1): - org_name: str = org.get("name", "Unknown") + org_name: str = org_choice_label(org) org_uuid: str = org.get("uuid", "") click.echo(f" {index}. {org_name} (uuid: {org_uuid})") @@ -80,7 +94,7 @@ def _prompt_org_selection_numbered(organizations: list[dict[str, Any]]) -> dict[ def _prompt_org_selection(organizations: list[dict[str, Any]]) -> dict[str, Any]: """Display orgs and prompt the user to pick one.""" choices: list[questionary.Choice] = [ - questionary.Choice(title=org.get("name", "Unknown"), value=org) for org in organizations + questionary.Choice(title=org_choice_label(org), value=org) for org in organizations ] selected: dict[str, Any] | None = questionary.select( "You belong to multiple organizations. Select one:", diff --git a/tests/standalone_org_login_test.py b/tests/standalone_org_login_test.py new file mode 100644 index 00000000..af6c8b16 --- /dev/null +++ b/tests/standalone_org_login_test.py @@ -0,0 +1,155 @@ +"""Email-code login with standalone Dailybot organizations (PLAN_002 T-standalone-org-login). + +Frozen marker (W2): a native entry carries `"platform": "dailybot", "standalone": true`; +legacy entries keep exactly `{id, name, uuid}`. HTTP is mocked at the call site. +""" + +import copy +import json +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.commands.auth import org_choice_label +from dailybot_cli.config import load_credentials +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_body + +POST: str = "dailybot_cli.api_client.httpx.post" +ORGS: list[dict[str, Any]] = fixture_body("verify_code_org_selection_200")["organizations"] +LEGACY_ORG: dict[str, Any] = next(o for o in ORGS if not o.get("standalone")) +NATIVE_ORG: dict[str, Any] = next(o for o in ORGS if o.get("standalone")) + + +@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) + + +@pytest.fixture +def agents_file(_isolated_environment: Path) -> Path: + _isolated_environment.mkdir(parents=True, exist_ok=True) + path: Path = _isolated_environment / "agents.json" + path.write_text(json.dumps({"default": "bot", "profiles": {"bot": {"api_key": "test-key"}}})) + return path + + +def _response(status: int, body: dict[str, Any]) -> MagicMock: + response: MagicMock = MagicMock() + response.status_code = status + response.headers = {} + response.json.return_value = body + response.text = json.dumps(body) + return response + + +def _request_code_multi() -> MagicMock: + return _response(200, {"is_multi_org": True, "organizations": copy.deepcopy(ORGS)}) + + +def _token_for(org: dict[str, Any]) -> MagicMock: + body: dict[str, Any] = copy.deepcopy(fixture_body("verify_code_legacy_200")) + body["organization"] = {"id": org["id"], "name": org["name"], "uuid": org["uuid"]} + return _response(200, body) + + +def _selection_required() -> MagicMock: + return _response(200, copy.deepcopy(fixture_body("verify_code_org_selection_200"))) + + +class TestNonInteractive: + def test_step_one_lists_the_standalone_org_with_its_uuid(self) -> None: + with patch(POST, return_value=_request_code_multi()): + result: Result = CliRunner().invoke(cli, ["login", "--email", "me@example.com"]) + assert result.exit_code == 0, result.output + assert f"{NATIVE_ORG['name']} (uuid: {NATIVE_ORG['uuid']})" in result.output + assert f"{LEGACY_ORG['name']} (uuid: {LEGACY_ORG['uuid']})" in result.output + + def test_org_resolves_the_standalone_uuid(self, agents_file: Path) -> None: + before: bytes = agents_file.read_bytes() + runner: CliRunner = CliRunner() + with patch(POST, side_effect=[_request_code_multi(), _token_for(NATIVE_ORG)]) as post: + runner.invoke(cli, ["login", "--email", "me@example.com"]) + result: Result = runner.invoke( + cli, + [ + "login", + "--email", + "me@example.com", + "--code", + "123456", + "--org", + NATIVE_ORG["uuid"], + ], + ) + assert result.exit_code == 0, result.output + assert post.call_args.kwargs["json"]["organization_id"] == NATIVE_ORG["id"] + creds: dict[str, Any] | None = load_credentials() + assert creds is not None + assert creds["organization"] == NATIVE_ORG["name"] + assert creds["organization_uuid"] == NATIVE_ORG["uuid"] + assert agents_file.read_bytes() == before + + def test_a_selection_answer_lists_both_kinds_unchanged(self) -> None: + with patch(POST, return_value=_selection_required()): + result: Result = CliRunner().invoke( + cli, ["login", "--email", "me@example.com", "--code", "123456"] + ) + assert result.exit_code == 1 + lines: list[str] = [line.strip() for line in result.output.splitlines()] + assert f"{NATIVE_ORG['name']} (uuid: {NATIVE_ORG['uuid']})" in lines + assert f"{LEGACY_ORG['name']} (uuid: {LEGACY_ORG['uuid']})" in lines + + +class TestInteractive: + def test_the_picker_marks_the_standalone_org_and_selects_it(self, agents_file: Path) -> None: + before: bytes = agents_file.read_bytes() + seen: list[str] = [] + + def pick(_message: str, choices: list[Any]) -> MagicMock: + seen.extend(str(c.title) for c in choices) + question: MagicMock = MagicMock() + question.ask.return_value = next(c.value for c in choices if c.value.get("standalone")) + return question + + with ( + patch("dailybot_cli.commands.auth.questionary.select", side_effect=pick), + patch(POST, side_effect=[_request_code_multi(), _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 + assert org_choice_label(NATIVE_ORG) in seen + assert org_choice_label(LEGACY_ORG) in seen + assert post.call_args.kwargs["json"]["organization_id"] == NATIVE_ORG["id"] + assert agents_file.read_bytes() == before + + def test_the_numbered_fallback_selects_it(self) -> None: + question: MagicMock = MagicMock() + question.ask.return_value = 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, + ): + result: Result = CliRunner().invoke( + cli, ["login"], input=f"me@example.com\n{native_index}\n123456\n" + ) + assert result.exit_code == 0, result.output + assert org_choice_label(NATIVE_ORG) in result.output + assert post.call_args.kwargs["json"]["organization_id"] == NATIVE_ORG["id"] + + +class TestLabels: + def test_a_standalone_org_is_marked(self) -> None: + assert org_choice_label(NATIVE_ORG) == f"{NATIVE_ORG['name']} (Dailybot)" + + def test_a_legacy_org_keeps_its_name(self) -> None: + assert org_choice_label(LEGACY_ORG) == LEGACY_ORG["name"] + + def test_an_agent_org_is_not_standalone(self) -> None: + agent_org: dict[str, Any] = {"id": 3, "name": "Bots", "uuid": "u", "platform": "dailybot"} + assert org_choice_label(agent_org) == "Bots" From 1561879e81c90c0ffc78b8ad94659d7a2f3ee874 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:23:23 +0000 Subject: [PATCH 11/19] feat(cli): refresh the cached plan tier from /v1/organization/ ## Summary The cached tier no longer blocks commands the server would allow. On a cached-free hit, and on a `plan_upgrade_required` answer, the CLI re-reads `plan.effective_tier` from `/v1/organization/` (at most once per org every 10 minutes) and updates plan_cache.json; `dailybot org` writes it too. A payload for another org is never cached, an absent `plan` (L43, switched off) keeps the cached tier, and a failed read never blocks. ## Change Log - public_api_helpers: refresh_cached_tier, remember_effective_tier, TIER_REFRESH_MIN_INTERVAL_SECS; enforce_plan_access and exit_for_api_error use them - config: additive `_refreshed_at` throttle key in plan_cache.json - plan_access_test: updated to the L37 contract (one tier read, never the command's own request) - docs: CONFIGURATION.md plan_cache.json, PERFORMANCE.md budget note ## Risks - Paid or unknown tiers make zero extra requests Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/commands/identity.py | 4 + dailybot_cli/commands/public_api_helpers.py | 82 ++++++++- dailybot_cli/config.py | 40 +++++ docs/CONFIGURATION.md | 3 + docs/PERFORMANCE.md | 2 + tests/effective_tier_test.py | 178 ++++++++++++++++++++ tests/plan_access_test.py | 29 +++- 7 files changed, 328 insertions(+), 10 deletions(-) create mode 100644 tests/effective_tier_test.py diff --git a/dailybot_cli/commands/identity.py b/dailybot_cli/commands/identity.py index 3af3bfa9..6a76bfce 100644 --- a/dailybot_cli/commands/identity.py +++ b/dailybot_cli/commands/identity.py @@ -9,8 +9,10 @@ emit_json, enforce_plan_access, exit_for_api_error, + remember_effective_tier, require_auth, ) +from dailybot_cli.config import load_credentials from dailybot_cli.display import console, print_detail_panel _ME_FIELDS: list[tuple[str, str]] = [ @@ -72,6 +74,8 @@ def org(json_mode: bool) -> None: data: dict[str, Any] = client.get_organization() except APIError as exc: exit_for_api_error(exc, json_mode) + creds: dict[str, Any] | None = load_credentials() + remember_effective_tier(data, creds.get("organization_uuid") if creds else None) if json_mode: emit_json(data) return diff --git a/dailybot_cli/commands/public_api_helpers.py b/dailybot_cli/commands/public_api_helpers.py index 00db56fb..2ccc1560 100644 --- a/dailybot_cli/commands/public_api_helpers.py +++ b/dailybot_cli/commands/public_api_helpers.py @@ -2,14 +2,28 @@ import json import re +import time from collections.abc import Callable from typing import Any, NoReturn import click import questionary -from dailybot_cli.api_client import AUTH_BACKEND_UNAVAILABLE_CODE, APIError, DailyBotClient -from dailybot_cli.config import get_agent_auth, get_org_plan, get_person_token, load_credentials +from dailybot_cli.api_client import ( + AUTH_BACKEND_UNAVAILABLE_CODE, + APIError, + DailyBotClient, + TransportError, +) +from dailybot_cli.config import ( + get_agent_auth, + get_org_plan, + get_org_plan_refreshed_at, + get_person_token, + load_credentials, + mark_org_plan_refreshed, + save_org_plan, +) from dailybot_cli.display import error_console, print_error, print_info # Plan tiers the server treats as "free" (matched case-insensitively). Kept @@ -1056,6 +1070,10 @@ def exit_for_api_error( """ code: str | None = getattr(exc, "code", None) extra: dict[str, Any] = getattr(exc, "extra", {}) or {} + if code == PAYWALL_CODE: + # The server says the plan does not allow this: re-read the effective tier + # so the cache matches (throttled; the local short-circuit just read it). + refresh_cached_tier(_signed_in_org_uuid()) mapped_message: str | None = ERROR_CODE_MESSAGES.get(code) if code else None if mapped_message and code: mapped_message = _augment_code_message(mapped_message, code, extra) @@ -1114,6 +1132,56 @@ def exit_for_api_error( raise SystemExit(exit_code) +# The cached tier is re-read from `/v1/organization/` at most this often per org, and +# only on a cached-free hit or a paywall code (L37) — never for a paid/unknown tier. +TIER_REFRESH_MIN_INTERVAL_SECS: float = 600.0 +PAYWALL_CODE: str = "plan_upgrade_required" + + +def remember_effective_tier(organization: dict[str, Any], org_uuid: str | None) -> str | None: + """Cache ``plan.effective_tier`` from an organization payload; return it, or ``None``. + + Only a payload for ``org_uuid`` (the signed-in org) is cached: a repo API key may + resolve to another org. An absent ``plan`` (L43, the field is switched off) leaves + the cache untouched. + """ + if not org_uuid or organization.get("uuid") != org_uuid: + return None + plan: Any = organization.get("plan") + tier: Any = plan.get("effective_tier") or plan.get("tier") if isinstance(plan, dict) else None + if not isinstance(tier, str) or not tier: + return None + save_org_plan(org_uuid, tier) + return tier + + +def refresh_cached_tier(org_uuid: str | None) -> str | None: + """Re-read the org's effective tier, within the throttle; ``None`` when unknown. + + Returns the cached tier when it was read recently or the server omits ``plan``, + and ``None`` when the read fails: a refresh problem never blocks a command. + """ + if not org_uuid: + return None + now: float = time.time() + last: float | None = get_org_plan_refreshed_at(org_uuid) + if last is not None and now - last < TIER_REFRESH_MIN_INTERVAL_SECS: + return get_org_plan(org_uuid) + try: + organization: dict[str, Any] = DailyBotClient().get_organization() + except (APIError, TransportError): + return None + mark_org_plan_refreshed(org_uuid, now) + fresh: str | None = remember_effective_tier(organization, org_uuid) + return fresh if fresh is not None else get_org_plan(org_uuid) + + +def _signed_in_org_uuid() -> str | None: + creds: dict[str, Any] | None = load_credentials() + value: Any = creds.get("organization_uuid") if creds else None + return value if isinstance(value, str) and value else None + + def enforce_plan_access(action: str, *, json_mode: bool = False) -> None: """Short-circuit a non-allowlisted command when the active org is known-free. @@ -1121,17 +1189,21 @@ def enforce_plan_access(action: str, *, json_mode: bool = False) -> None: the source of truth: when the plan tier is **unknown** (the API hasn't exposed it, or no cache yet) this is a no-op and the call proceeds, so a stale/absent cache can never *block* a command the server would allow. + A cached free tier is re-read first (``refresh_cached_tier``): a trial's + effective tier lets the command through, and a failed read never blocks. Allowlisted (agent-scoped / me / org / cli-status) actions never short-circuit. """ if action in FREE_PLAN_ALLOWLIST: return - creds: dict[str, Any] | None = load_credentials() - org_uuid: str | None = creds.get("organization_uuid") if creds else None + org_uuid: str | None = _signed_in_org_uuid() tier: str | None = get_org_plan(org_uuid) + if tier is None or tier.lower() not in FREE_PLAN_TIERS: + return + tier = refresh_cached_tier(org_uuid) if tier is not None and tier.lower() in FREE_PLAN_TIERS: # Reuse the Task 2 upgrade-message renderer + exit code (no second renderer). exit_for_api_error( - APIError(403, "This action requires a paid plan.", code="plan_upgrade_required"), + APIError(403, "This action requires a paid plan.", code=PAYWALL_CODE), json_mode, ) diff --git a/dailybot_cli/config.py b/dailybot_cli/config.py index cd08d3f3..1f2b33b7 100644 --- a/dailybot_cli/config.py +++ b/dailybot_cli/config.py @@ -511,6 +511,46 @@ def save_org_plan(organization_uuid: str, plan: str | None) -> None: _write_secret_file(cache_path, json.dumps(data, indent=2)) +PLAN_REFRESHED_AT_KEY: str = "_refreshed_at" +"""Reserved ``plan_cache.json`` key: ``{org_uuid: epoch seconds}`` of the last tier read. + +Additive (Rule 16): it can never collide with an org UUID, and older CLIs only +read ``data[org_uuid]``. +""" + + +def _load_plan_cache() -> dict[str, Any]: + cache_path: Path = _plan_cache_path() + if not cache_path.exists(): + return {} + try: + loaded: Any = json.loads(cache_path.read_text()) + except (json.JSONDecodeError, OSError): + return {} + return loaded if isinstance(loaded, dict) else {} + + +def get_org_plan_refreshed_at(organization_uuid: str | None) -> float | None: + """When the org's tier was last read from the server, or ``None``.""" + if not organization_uuid: + return None + stamps: Any = _load_plan_cache().get(PLAN_REFRESHED_AT_KEY) + value: Any = stamps.get(organization_uuid) if isinstance(stamps, dict) else None + return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None + + +def mark_org_plan_refreshed(organization_uuid: str, when: float) -> None: + """Record that the org's tier was just read from the server (the refresh throttle).""" + if not organization_uuid: + return + data: dict[str, Any] = _load_plan_cache() + stamps: Any = data.get(PLAN_REFRESHED_AT_KEY) + stamps = dict(stamps) if isinstance(stamps, dict) else {} + stamps[organization_uuid] = when + data[PLAN_REFRESHED_AT_KEY] = stamps + _write_secret_file(_plan_cache_path(), json.dumps(data, indent=2)) + + def get_org_plan(organization_uuid: str | None) -> str | None: """Return the cached plan tier for an org UUID, or None if unknown. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 66737c2d..628829aa 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -9,6 +9,7 @@ The Dailybot CLI persists state in `~/.config/dailybot/` by default. The path ca | `credentials.json` | `dailybot login` | `{ token, email, organization, organization_uuid, api_url }`, plus `{ auth_method, refresh, expires_at, refresh_expires_at }` for a browser (device-flow) session | `0o600` | | `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) | | `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` | @@ -17,6 +18,8 @@ The Dailybot CLI persists state in `~/.config/dailybot/` by default. The path ca ### Schema notes +**`plan_cache.json`** — the effective plan tier per org, used only to skip a request the server would refuse on a free plan. It is written at login (the browser sign-in caches `organization.plan.effective_tier`), by `dailybot org`, and when the CLI re-reads `/v1/organization/`. That re-read happens only on a cached-free hit or a `plan_upgrade_required` answer, at most once per org every 10 minutes (`TIER_REFRESH_MIN_INTERVAL_SECS`; the time is kept under the reserved `_refreshed_at` key, which older CLIs ignore). When the server omits `plan` (the field is switched off for most orgs) the cached tier is kept, and a failed re-read never blocks a command: an unknown tier always lets the server decide. + **`credentials.json`** — created by `save_credentials(...)`. Backwards-compatible additions are safe; `load_credentials()` treats missing keys as absent. The `api_url` field captures which API the user authenticated against, so re-running commands from a different default URL doesn't accidentally use the wrong one. **Browser (device-flow) sessions** add four keys and rename or remove none (Rule 16): diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index bd0b8863..445c6ca0 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -49,6 +49,8 @@ Rules of thumb: - Transport failures (`httpx.HTTPError` and its subclasses) are converted to `TransportError` at the dispatch boundary and are **never retried** — the bounded 429 backoff in `_send_with_retry` remains the only retry. Silently retrying a connection failure hides an outage from the caller and can double-post a non-idempotent write. - Retries are intentionally **not** layered into `api_client.py`. The Dailybot API is idempotent only for the read tier; transparent retry of submits would risk double-posting. If a future read endpoint needs jittered retry, add it as an opt-in helper, not a default. +**Plan-tier re-read (PLAN_002, L37).** The free-plan short-circuit (`enforce_plan_access`) costs **zero** requests for a paid or unknown cached tier. On a cached *free* tier it re-reads `/v1/organization/` once before blocking, at most once per org every `TIER_REFRESH_MIN_INTERVAL_SECS = 600` s (a `plan_upgrade_required` answer shares the same throttle). The re-read replaces the guaranteed-403 roundtrip it used to save only while the throttle is cold; within the window the short-circuit is local again. The brief's "re-read on every command start" was narrowed to this to stay inside the HTTP budget. + ### 3. Terminal rendering budget — `display.py` / `rich` `rich` rendering itself is fast. The risk is **shelling spinners around fast operations** (e.g. wrapping a local file read in `console.status("…")` — flicker without value). diff --git a/tests/effective_tier_test.py b/tests/effective_tier_test.py new file mode 100644 index 00000000..cefb7985 --- /dev/null +++ b/tests/effective_tier_test.py @@ -0,0 +1,178 @@ +"""The cached plan tier follows `plan.effective_tier` (PLAN_002 T-effective-tier, L37, L43). + +The CLI re-reads `/v1/organization/` only on a cached-free hit or a paywall code, +never for a paid or unknown tier. When `plan` is absent (PUBLIC_V1_ORG_PLAN_FIELD +off) the cached tier is kept. A failed refresh never blocks. +""" + +import copy +import json +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import httpx +import pytest +from click.testing import CliRunner, Result + +from dailybot_cli.api_client import APIError +from dailybot_cli.commands import public_api_helpers +from dailybot_cli.commands.public_api_helpers import ( + TIER_REFRESH_MIN_INTERVAL_SECS, + enforce_plan_access, + exit_for_api_error, +) +from dailybot_cli.config import get_org_plan, save_credentials, save_org_plan +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_body + +API: str = "https://api.example.com" +GET: str = "dailybot_cli.api_client.httpx.get" +NATIVE: dict[str, Any] = fixture_body("organization_native_200") +ORG_UUID: str = NATIVE["uuid"] + + +@pytest.fixture(autouse=True) +def _session(monkeypatch: pytest.MonkeyPatch) -> None: + for name in ("DAILYBOT_API_KEY", "DAILYBOT_CLI_TOKEN", "DAILYBOT_API_URL"): + monkeypatch.delenv(name, raising=False) + save_credentials( + token="test-token", + email="me@example.com", + organization="My Team", + organization_uuid=ORG_UUID, + api_url=API, + ) + + +def _org(effective: str | None, uuid: str = ORG_UUID) -> MagicMock: + body: dict[str, Any] = copy.deepcopy(NATIVE) + body["uuid"] = uuid + if effective is None: + body.pop("plan") + else: + body["plan"] = { + "tier": "free", + "effective_tier": effective, + "is_trial": effective != "free", + } + response: MagicMock = MagicMock() + response.status_code = 200 + response.headers = {} + response.json.return_value = body + return response + + +class TestCachedFreeHit: + def test_a_trial_proceeds_after_one_organization_read(self) -> None: + save_org_plan(ORG_UUID, "free") + with patch(GET, return_value=_org("startup")) as get: + enforce_plan_access("form_list") + assert get.call_count == 1 + assert get.call_args.args[0] == f"{API}/v1/organization/" + assert get_org_plan(ORG_UUID) == "startup" + + def test_a_still_free_org_is_blocked(self) -> None: + save_org_plan(ORG_UUID, "free") + with patch(GET, return_value=_org("free")), pytest.raises(SystemExit) as caught: + enforce_plan_access("form_list") + assert caught.value.code == public_api_helpers.EXIT_PERMISSION_DENIED + + def test_an_absent_plan_keeps_the_cached_tier(self) -> None: + save_org_plan(ORG_UUID, "free") + with patch(GET, return_value=_org(None)), pytest.raises(SystemExit): + enforce_plan_access("form_list") + assert get_org_plan(ORG_UUID) == "free" + + @pytest.mark.parametrize( + "failure", + [httpx.ConnectError("offline"), None], + ids=["transport", "server-error"], + ) + def test_a_failed_refresh_never_blocks(self, failure: Exception | None) -> None: + save_org_plan(ORG_UUID, "free") + error_response: MagicMock = MagicMock() + error_response.status_code = 500 + error_response.headers = {} + error_response.json.return_value = {"detail": "boom"} + with ( + patch(GET, side_effect=failure) if failure else patch(GET, return_value=error_response) + ): + enforce_plan_access("form_list") + assert get_org_plan(ORG_UUID) == "free" + + def test_another_orgs_payload_is_never_cached(self) -> None: + save_org_plan(ORG_UUID, "free") + other: str = "00000000-0000-4000-8000-000000000099" + with patch(GET, return_value=_org("business", uuid=other)), pytest.raises(SystemExit): + enforce_plan_access("form_list") + assert get_org_plan(ORG_UUID) == "free" + assert get_org_plan(other) is None + + def test_a_recent_refresh_is_not_repeated(self) -> None: + save_org_plan(ORG_UUID, "free") + with patch(GET, return_value=_org("free")) as get: + for _ in range(3): + with pytest.raises(SystemExit): + enforce_plan_access("form_list") + assert get.call_count == 1 + + def test_the_throttle_expires(self, monkeypatch: pytest.MonkeyPatch) -> None: + save_org_plan(ORG_UUID, "free") + clock: list[float] = [1000.0] + monkeypatch.setattr(public_api_helpers.time, "time", lambda: clock[0]) + with patch(GET, return_value=_org("free")) as get: + with pytest.raises(SystemExit): + enforce_plan_access("form_list") + clock[0] += TIER_REFRESH_MIN_INTERVAL_SECS + 1 + with pytest.raises(SystemExit): + enforce_plan_access("form_list") + assert get.call_count == 2 + + +class TestZeroExtraCalls: + @pytest.mark.parametrize("tier", ["startup", "business", None]) + def test_paid_or_unknown_tiers_never_call(self, tier: str | None) -> None: + if tier: + save_org_plan(ORG_UUID, tier) + with patch(GET) as get: + enforce_plan_access("form_list") + get.assert_not_called() + + def test_allowlisted_actions_never_call(self) -> None: + save_org_plan(ORG_UUID, "free") + with patch(GET) as get: + enforce_plan_access("me") + get.assert_not_called() + + +class TestPaywallCode: + def test_a_paywall_answer_rewrites_the_cache(self) -> None: + save_org_plan(ORG_UUID, "startup") + with patch(GET, return_value=_org("free")) as get, pytest.raises(SystemExit): + exit_for_api_error( + APIError(403, "Upgrade.", code="plan_upgrade_required"), json_mode=False + ) + assert get.call_count == 1 + assert get_org_plan(ORG_UUID) == "free" + + def test_other_codes_never_refresh(self) -> None: + with patch(GET) as get, pytest.raises(SystemExit): + exit_for_api_error(APIError(403, "No.", code="forbidden"), json_mode=False) + get.assert_not_called() + + +def test_dailybot_org_writes_the_effective_tier(_isolated_environment: Path) -> None: + with patch(GET, return_value=_org("startup")): + result: Result = CliRunner().invoke(cli, ["org", "--json"]) + assert result.exit_code == 0, result.output + assert json.loads(result.output)["uuid"] == ORG_UUID + assert get_org_plan(ORG_UUID) == "startup" + + +def test_an_older_cli_still_reads_the_cache(_isolated_environment: Path) -> None: + save_org_plan(ORG_UUID, "free") + with patch(GET, return_value=_org("startup")): + enforce_plan_access("form_list") + data: dict[str, Any] = json.loads((_isolated_environment / "plan_cache.json").read_text()) + assert data[ORG_UUID] == "startup" diff --git a/tests/plan_access_test.py b/tests/plan_access_test.py index 37de2047..127cb43b 100644 --- a/tests/plan_access_test.py +++ b/tests/plan_access_test.py @@ -30,12 +30,28 @@ def _set_org(uuid: str) -> None: ) +def _org_read(uuid: str, effective_tier: str) -> MagicMock: + """`/v1/organization/` as PLAN_002 L37 re-reads it on a cached-free hit.""" + response: MagicMock = MagicMock() + response.status_code = 200 + response.headers = {} + response.json.return_value = { + "uuid": uuid, + "name": "Org", + "plan": {"tier": "free", "effective_tier": effective_tier, "is_trial": False}, + } + return response + + def test_known_free_org_short_circuits_non_allowlisted(tmp_config: Path) -> None: from dailybot_cli.config import save_org_plan _set_org("org-free") save_org_plan("org-free", "free") - with pytest.raises(SystemExit) as excinfo: + with ( + patch("dailybot_cli.api_client.httpx.get", return_value=_org_read("org-free", "free")), + pytest.raises(SystemExit) as excinfo, + ): enforce_plan_access("form_list") assert excinfo.value.code != 0 @@ -63,17 +79,20 @@ def test_paid_plan_never_short_circuits(tmp_config: Path) -> None: enforce_plan_access("form_list") # no raise -def test_form_list_short_circuits_before_any_http(tmp_config: Path) -> None: - """A known-free org must not issue an HTTP call for `form list`.""" +def test_form_list_short_circuits_before_the_forms_request(tmp_config: Path) -> None: + """A known-free org never issues the `form list` request; only the tier re-read.""" from dailybot_cli.commands.form import form from dailybot_cli.config import save_org_plan _set_org("org-free") save_org_plan("org-free", "free") runner = CliRunner() - with patch("dailybot_cli.api_client.httpx.get") as mock_get: + with patch( + "dailybot_cli.api_client.httpx.get", return_value=_org_read("org-free", "free") + ) as mock_get: result = runner.invoke(form, ["list"]) - assert mock_get.call_count == 0 # short-circuited before the roundtrip + # PLAN_002 L37: one tier re-read of /v1/organization/, never the forms roundtrip. + assert [c.args[0] for c in mock_get.call_args_list] == ["http://test/v1/organization/"] assert result.exit_code != 0 assert "plan" in result.output.lower() or "upgrade" in result.output.lower() From 7d30fbcc2593d769fe6d226d23defe0dc5c4e3e0 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:27:19 +0000 Subject: [PATCH 12/19] feat(cli): show the organization's chat platforms in `dailybot org` ## Summary When /v1/organization/ serves `has_external_chat_platform`, `primary_chat_platform` and `chat_platforms` (ChatPlatformSummary, L74), `dailybot org` lists each platform with its name, status, primary marker and full id (the value installation-qualified references use), and says when no external platform is connected. Missing keys mean "unavailable", so the output is byte-identical to today; `--json` passes them through. ## Change Log - display.print_org_chat_platforms (server text neutralized and escaped) - docs/API_REFERENCE.md org fields; README org row ## Risks - None: additive rendering only Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- dailybot_cli/commands/identity.py | 3 +- dailybot_cli/display.py | 43 ++++++++++++ docs/API_REFERENCE.md | 9 ++- tests/org_channels_test.py | 109 ++++++++++++++++++++++++++++++ 5 files changed, 163 insertions(+), 3 deletions(-) create mode 100644 tests/org_channels_test.py diff --git a/README.md b/README.md index 9fde3539..d1d64b63 100644 --- a/README.md +++ b/README.md @@ -849,7 +849,7 @@ Replies to agent emails land as messages retrievable via `dailybot agent message | `dailybot logout` | Log out and revoke token | | `dailybot status` | Show pending check-ins and auth status | | `dailybot me` | Show the authenticated user and org context (`--include-email`, `--json`) | -| `dailybot org` | Show the organization the credential is scoped to (`--json`) | +| `dailybot org` | Show the organization the credential is scoped to, and its chat platforms when the server provides them (`--json`) | | `dailybot update` | Submit a free-text or structured check-in update | | `dailybot config` | Get, set, or remove a stored setting (e.g. API key) | | `dailybot version` | Show version info and optionally check for updates | diff --git a/dailybot_cli/commands/identity.py b/dailybot_cli/commands/identity.py index 6a76bfce..7e72d591 100644 --- a/dailybot_cli/commands/identity.py +++ b/dailybot_cli/commands/identity.py @@ -13,7 +13,7 @@ require_auth, ) from dailybot_cli.config import load_credentials -from dailybot_cli.display import console, print_detail_panel +from dailybot_cli.display import console, print_detail_panel, print_org_chat_platforms _ME_FIELDS: list[tuple[str, str]] = [ ("Name", "full_name"), @@ -80,3 +80,4 @@ def org(json_mode: bool) -> None: emit_json(data) return print_detail_panel("Organization", data, _ORG_FIELDS) + print_org_chat_platforms(data) diff --git a/dailybot_cli/display.py b/dailybot_cli/display.py index 46633d66..16aec51d 100644 --- a/dailybot_cli/display.py +++ b/dailybot_cli/display.py @@ -283,6 +283,49 @@ def print_detail_panel(title: str, data: dict[str, Any], fields: list[tuple[str, console.print(Panel(table, title=title, border_style="cyan", expand=False)) +CHAT_PLATFORM_NAMES: dict[str, str] = { + "dailybot": "Dailybot", + "slack": "Slack", + "msteams": "Microsoft Teams", + "discord": "Discord", + "hangouts": "Google Chat", +} + + +def print_org_chat_platforms(organization: dict[str, Any]) -> None: + """Render an organization's chat platforms (ChatPlatformSummary, L74), when served. + + The keys are appended only when the server's gate is on. A missing key means + "unavailable", not "none", so nothing is printed and the output stays exactly + what it was before these fields existed. Names and ids are server text. + """ + platforms: Any = organization.get("chat_platforms") + if not isinstance(platforms, list): + return + # One block per platform instead of a table: the id is what installation-qualified + # references use, so it is printed whole on its own line, never truncated or folded. + console.print("[bold cyan]Chat platforms[/bold cyan]") + for item in platforms: + if not isinstance(item, dict): + continue + platform: str = str(item.get("platform") or "") + label: str = CHAT_PLATFORM_NAMES.get(platform, platform) + primary: str = " [dim](primary)[/dim]" if item.get("is_primary") is True else "" + status: str = str(item.get("status") or "") + status_style: str = "green" if status == "connected" else "yellow" + status_text: str = ( + f" · [{status_style}]{safe_text(status)}[/{status_style}]" if status else "" + ) + name: str = safe_text(item.get("display_name") or "") + console.print(f" [bold]{safe_text(label)}[/bold]{primary} · {name}{status_text}") + console.print(f" [dim]id[/dim] {safe_text(item.get('id') or '')}", soft_wrap=True) + if organization.get("has_external_chat_platform") is False: + print_info( + "No external chat platform is connected (Slack, Microsoft Teams, Discord or " + "Google Chat). `dailybot chat send` needs one." + ) + + def print_pagination_footer( shown: int, total: int | None = None, diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index ea69a745..2fc65dd7 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -125,6 +125,13 @@ Shows the authenticated user and the org context of the active credential. Calls Shows the organization the credential is scoped to. Calls `GET /v1/organization/`. +When the server serves them (organizations with chat-platform management, and every standalone Dailybot organization), the payload carries three more keys, which `dailybot org` renders under **Chat platforms** and `--json` passes through unchanged: + +- `has_external_chat_platform` — `false` when only the Dailybot platform exists (then `dailybot chat send` has nowhere to deliver). +- `primary_chat_platform` and `chat_platforms[]` — `ChatPlatformSummary` objects: `{ id, platform, display_name, organization_external_id, is_primary, status, capabilities: { directory, reporting, direct_messages } }`. `platform` is `dailybot`, `slack`, `msteams`, `discord` or `hangouts`; `status` is `connected`, `needs_reauth` or `disabled`; `id` is the value an installation-qualified channel reference uses (`:`). + +Missing keys mean the information is unavailable, not that there are no platforms: the output is then exactly what it was before. The optional `plan { tier, effective_tier, is_trial }` object (served for standalone organizations) refreshes the cached plan tier. + --- ### `dailybot checkin` (group) — user-scoped, Bearer or API key auth @@ -719,7 +726,7 @@ key, so all of these commands work with `DAILYBOT_API_KEY` set even without | `GET` | `/v1/mood/track/` | `?date` | `{ ... }` | Read today's mood | | `POST` | `/v1/mood/track/` | `{ score, date? }` | `{ ... }` | `/mood` | | `GET` | `/v1/me/` | — | `{ user: { uuid, full_name, email }, organization: { uuid, name } }` | `dailybot me` | -| `GET` | `/v1/organization/` | — | `{ uuid, name, ... }` | `dailybot org` | +| `GET` | `/v1/organization/` | — | `{ uuid, name, platform, ..., has_external_chat_platform?, primary_chat_platform?, chat_platforms?, plan? }` | `dailybot org`; the optional keys are served only when gated on | | `GET` | `/v1/users/` | — | `{ results: [{ uuid, full_name }], next: url\|null }` | Paginated | | `GET` | `/v1/users//` | — | `{ uuid, full_name, email? }` | `dailybot user get` | | `GET` | `/v1/teams/` | — | `{ results: [{ uuid, name, active, members_count, is_default }], next? }` | Server-scoped: admins see all, members see own | diff --git a/tests/org_channels_test.py b/tests/org_channels_test.py new file mode 100644 index 00000000..04e57c58 --- /dev/null +++ b/tests/org_channels_test.py @@ -0,0 +1,109 @@ +"""`dailybot org` shows the organization's chat platforms (PLAN_002 T-org-channels, L74). + +`/v1/organization/` appends `has_external_chat_platform`, `primary_chat_platform` and +`chat_platforms` (ChatPlatformSummary items) only when gated on. Missing keys mean +"unavailable", never "no platforms": the output is then byte-identical to today. +""" + +import copy +import json +from typing import Any +from unittest.mock import MagicMock + +import click +import pytest +from click.testing import CliRunner, Result + +from dailybot_cli.commands.identity import _ORG_FIELDS +from dailybot_cli.display import print_detail_panel +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_body + +PLATFORM_KEYS: tuple[str, ...] = ( + "has_external_chat_platform", + "primary_chat_platform", + "chat_platforms", +) + + +@pytest.fixture +def client(monkeypatch: pytest.MonkeyPatch) -> MagicMock: + mock: MagicMock = MagicMock() + monkeypatch.setattr("dailybot_cli.commands.public_api_helpers.get_agent_auth", lambda: "tok") + monkeypatch.setattr( + "dailybot_cli.commands.public_api_helpers.DailyBotClient", lambda *a, **k: mock + ) + return mock + + +def _todays_rendering(data: dict[str, Any]) -> str: + @click.command() + def render() -> None: + print_detail_panel("Organization", data, _ORG_FIELDS) + + return CliRunner().invoke(render).output + + +class TestUnavailable: + def test_a_legacy_payload_renders_byte_identical(self, client: MagicMock) -> None: + data: dict[str, Any] = fixture_body("organization_legacy_200") + client.get_organization.return_value = copy.deepcopy(data) + result: Result = CliRunner().invoke(cli, ["org"]) + assert result.exit_code == 0 + assert result.output == _todays_rendering(data) + + def test_missing_keys_never_say_no_platforms(self, client: MagicMock) -> None: + client.get_organization.return_value = fixture_body("organization_legacy_200") + result: Result = CliRunner().invoke(cli, ["org"]) + assert "chat platform" not in result.output.lower() + + +class TestAvailable: + def test_a_connected_org_lists_its_platforms(self, client: MagicMock) -> None: + data: dict[str, Any] = fixture_body("organization_chat_platforms_no_plan_200") + client.get_organization.return_value = data + result: Result = CliRunner().invoke(cli, ["org"]) + assert result.exit_code == 0 + summary: dict[str, Any] = data["chat_platforms"][0] + assert "Chat platforms" in result.output + assert summary["display_name"] in result.output + assert "Slack" in result.output + assert "connected" in result.output + assert summary["id"] in result.output + assert "primary" in result.output.lower() + assert result.output.startswith(_todays_rendering(data)) + + def test_a_native_org_says_no_external_platform(self, client: MagicMock) -> None: + client.get_organization.return_value = fixture_body("organization_native_200") + result: Result = CliRunner().invoke(cli, ["org"]) + assert result.exit_code == 0 + assert "Dailybot" in result.output + assert "no external chat platform" in result.output.lower() + + def test_status_needs_reauth_is_shown(self, client: MagicMock) -> None: + data: dict[str, Any] = copy.deepcopy( + fixture_body("organization_chat_platforms_no_plan_200") + ) + data["chat_platforms"][0]["status"] = "needs_reauth" + client.get_organization.return_value = data + result: Result = CliRunner().invoke(cli, ["org"]) + assert "needs_reauth" in result.output or "reconnect" in result.output.lower() + + def test_names_are_escaped_and_neutralized(self, client: MagicMock) -> None: + data: dict[str, Any] = copy.deepcopy( + fixture_body("organization_chat_platforms_no_plan_200") + ) + data["chat_platforms"][0]["display_name"] = "[bold red]evil[/bold red]\x1b[2J" + client.get_organization.return_value = data + result: Result = CliRunner().invoke(cli, ["org"]) + assert "[bold red]evil[/bold red]" in result.output + assert "\x1b[2J" not in result.output + + def test_json_passes_the_keys_through(self, client: MagicMock) -> None: + data: dict[str, Any] = fixture_body("organization_native_200") + client.get_organization.return_value = copy.deepcopy(data) + result: Result = CliRunner().invoke(cli, ["org", "--json"]) + assert result.exit_code == 0 + out: dict[str, Any] = json.loads(result.output) + for key in PLATFORM_KEYS: + assert out[key] == data[key] From 9379320f24660337a945b9c476c71c2c398727b1 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:28:26 +0000 Subject: [PATCH 13/19] test(tests): pin platform_not_connected for chat send on Dailybot orgs ## Summary `chat send` against an organization with no external chat platform keeps the server's `400 platform_not_connected`: the catalogue message, exit 2, the code in --json, and exactly the user's targets in one request (never a retargeted Dailybot Chat delivery). No code change was needed; the tests pin it so later channel work cannot regress it. ## Change Log - chat_commands_test: TestPlatformNotConnected with the recorded fixture - docs: TROUBLESHOOTING Chat section, API_REFERENCE send-message note ## Risks - None Co-Authored-By: Claude Opus 5.5 --- docs/API_REFERENCE.md | 2 +- docs/TROUBLESHOOTING.md | 6 ++++ tests/chat_commands_test.py | 60 ++++++++++++++++++++++++++++++++++++- 3 files changed, 66 insertions(+), 2 deletions(-) diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 2fc65dd7..cd571ebb 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -752,7 +752,7 @@ key, so all of these commands work with `DAILYBOT_API_KEY` set even without | `POST` | `/v1/agent-email/send/` | `{ agent_name, to, subject, body_html, metadata? }` | `{ sent_count, total_recipients, reply_to? }` | 429 = hourly limit | | `POST` | `/v1/agent-messages/` | `{ agent_name, content, message_type?, metadata?, expires_at?, sender_type?, sender_name? }` | `{ id, agent_name, sender_name, sender_type, message_type, content }` | | | `GET` | `/v1/agent-messages/?agent_name=...&delivered=true|false` | — | `[{ id, message_type, sender_type, sender_name, content, delivered, created_at }]` | Returns a bare array, not a wrapped object | -| `POST` | `/v1/send-message/` | `{ message?/messages?, image_url?, buttons?, thread_responses?, target_users?/target_channels?/target_teams?, platform_settings?, metadata?, skip_users_on_time_off?, send_as_user?, bot_message_id? }` | `{ bot_message_id, thread_responses?: [ids] }` | **X-API-KEY or Bearer** (login, role-scoped); ≥1 target; `thread_responses` posts replies in the parent thread (≤10); `send_as_user` (Slack, admin-only) posts with that user's identity; `bot_message_id` in → edits that message (parent or reply) | +| `POST` | `/v1/send-message/` | `{ message?/messages?, image_url?, buttons?, thread_responses?, target_users?/target_channels?/target_teams?, platform_settings?, metadata?, skip_users_on_time_off?, send_as_user?, bot_message_id? }` | `{ bot_message_id, thread_responses?: [ids] }` | **X-API-KEY or Bearer** (login, role-scoped); ≥1 target; `thread_responses` posts replies in the parent thread (≤10); `send_as_user` (Slack, admin-only) posts with that user's identity; `bot_message_id` in → edits that message (parent or reply); an org with no external chat platform answers `400 platform_not_connected`, and the message is never delivered to Dailybot Chat instead | | `POST` | `/v1/open-conversation/` | `{ users_uuids: [uuid, ...] }` | `{ channel }` | **X-API-KEY or Bearer**; **Slack only** (`406 open_conversation_not_supported` otherwise), **org-admin only** (`403`); idempotent (same users → same channel); `dailybot conversation open` | | `PATCH` | `/v1/agent-messages/read/` | `{ message_ids: [...] }` | `{ updated }` | | diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 686a68e1..7c29d0d0 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -138,6 +138,12 @@ dailybot form response get --json | jq -r '.content[]' | If the printed output has real line breaks (not `\n` literals) and uses `#` rather than `##` / `###`, the webapp will render it correctly. +## Chat + +### `dailybot chat send` → 400 / `platform_not_connected` + +"No chat platform is connected for this organization, so channels and messages are not available." The organization has no Slack, Microsoft Teams, Discord or Google Chat installation (a standalone Dailybot organization starts this way), so there is nowhere to deliver a bot message. The CLI never redirects the message to Dailybot Chat. Run `dailybot org` to see the organization's chat platforms; connect one in the Dailybot web app, then send again. The command exits `2`, and `--json` keeps `"code": "platform_not_connected"`. + ## Teams & Kudos ### `dailybot team list` shows fewer teams than I expect diff --git a/tests/chat_commands_test.py b/tests/chat_commands_test.py index 38054080..951b1767 100644 --- a/tests/chat_commands_test.py +++ b/tests/chat_commands_test.py @@ -1,13 +1,17 @@ """Tests for the `dailybot chat` command group and payload builder.""" +import json +from typing import Any from unittest.mock import MagicMock, patch import pytest from click.testing import CliRunner -from dailybot_cli.api_client import APIError +from dailybot_cli.api_client import APIError, DailyBotClient from dailybot_cli.commands.chat import ChatPayloadError, build_chat_payload +from dailybot_cli.commands.public_api_helpers import ERROR_CODE_MESSAGES, EXIT_USAGE_ERROR from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_response @pytest.fixture @@ -544,3 +548,57 @@ def test_org_admin_required_message(self) -> None: # (chat send overrides it with the --send-as-user hint at the call site). assert "admin" in ERROR_CODE_MESSAGES["org_admin_required"].lower() assert "send_as_user_not_found" in ERROR_CODE_MESSAGES + + +class TestPlatformNotConnected: + """PLAN_002 T-chat-not-connected: a Dailybot-only org never gets a silent Dailybot Chat delivery.""" + + @staticmethod + def _real_client(mock_resolve: MagicMock) -> DailyBotClient: + client: DailyBotClient = DailyBotClient( + api_url="https://api.example.com", api_key="test-key" + ) + mock_resolve.return_value = ("CLI Agent", client, {}) + return client + + @patch("dailybot_cli.commands.chat._resolve_agent_context") + def test_platform_not_connected_renders_the_catalogue_message( + self, mock_resolve: MagicMock, runner: CliRunner + ) -> None: + self._real_client(mock_resolve) + with patch( + "dailybot_cli.api_client.httpx.request", + return_value=fixture_response("send_message_platform_not_connected_400"), + ): + result = runner.invoke(cli, ["chat", "send", "-c", "C0", "-m", "Deploy done"]) + assert result.exit_code == EXIT_USAGE_ERROR + assert ERROR_CODE_MESSAGES["platform_not_connected"] in " ".join(result.output.split()) + + @patch("dailybot_cli.commands.chat._resolve_agent_context") + def test_platform_not_connected_sends_exactly_the_users_targets_once( + self, mock_resolve: MagicMock, runner: CliRunner + ) -> None: + self._real_client(mock_resolve) + with patch( + "dailybot_cli.api_client.httpx.request", + return_value=fixture_response("send_message_platform_not_connected_400"), + ) as request: + runner.invoke(cli, ["chat", "send", "-c", "C0", "-u", "me@example.com", "-m", "hi"]) + assert request.call_count == 1 + body: dict[str, Any] = request.call_args.kwargs["json"] + assert body["target_channels"] == ["C0"] + assert body["target_users"] == ["me@example.com"] + assert "dailybot" not in json.dumps(body).lower() + + @patch("dailybot_cli.commands.chat._resolve_agent_context") + def test_platform_not_connected_in_json_mode_keeps_the_code( + self, mock_resolve: MagicMock, runner: CliRunner + ) -> None: + self._real_client(mock_resolve) + with patch( + "dailybot_cli.api_client.httpx.request", + return_value=fixture_response("send_message_platform_not_connected_400"), + ): + result = runner.invoke(cli, ["chat", "send", "-c", "C0", "-m", "hi", "--json"]) + assert result.exit_code == EXIT_USAGE_ERROR + assert json.loads(result.output)["code"] == "platform_not_connected" From c81ab9d144850f3f8ae1b381ea87a102bb9842ab Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:30:57 +0000 Subject: [PATCH 14/19] feat(auth): show the cli_auth_deprecated notice on email-code sign-in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary While the server's notice is on, the legacy request-code and verify-code answers carry a `deprecation` field on 200 and 400 bodies. The CLI shows one notice per login with the sunset date: `dailybot upgrade` when its version is below `min_version`, otherwise a pointer to `dailybot login --device`. The login completes as before; without the field the output is unchanged. The server's `detail` prose is never rendered. ## Change Log - _handle_response: body `deprecation` → APIError.extra["deprecation"] - auth: is_version_below, _notice_deprecation (once per run) - display.print_cli_auth_deprecation; catalogue entry for the future 410 - docs: TROUBLESHOOTING, API_REFERENCE ## Risks - None: a notice only, never blocks Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 5 + dailybot_cli/commands/auth.py | 55 +++++++ dailybot_cli/commands/public_api_helpers.py | 5 + dailybot_cli/display.py | 21 +++ docs/API_REFERENCE.md | 3 +- docs/TROUBLESHOOTING.md | 4 + tests/cli_auth_deprecation_test.py | 155 ++++++++++++++++++++ 7 files changed, 247 insertions(+), 1 deletion(-) create mode 100644 tests/cli_auth_deprecation_test.py diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 4b47b273..20b51d10 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -965,6 +965,11 @@ def _handle_response(self, response: httpx.Response) -> dict[str, Any]: raw_extra: Any = body.get("extra") if isinstance(raw_extra, dict): extra = dict(raw_extra) + # The legacy login doors carry a `deprecation` object on 400 bodies + # too (W1); surface it so the notice reaches the renderer. + raw_deprecation: Any = body.get("deprecation") + if isinstance(raw_deprecation, dict): + extra["deprecation"] = dict(raw_deprecation) # Plan-gating responses carry upgrade_url at the top level; surface it # in extra so downstream reads a single place. upgrade_url: Any = body.get("upgrade_url") diff --git a/dailybot_cli/commands/auth.py b/dailybot_cli/commands/auth.py index f7c4ca6d..fb06d15f 100644 --- a/dailybot_cli/commands/auth.py +++ b/dailybot_cli/commands/auth.py @@ -1,11 +1,13 @@ """Authentication commands for Dailybot CLI.""" import os +import re from typing import Any import click import questionary +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 @@ -28,12 +30,56 @@ ) from dailybot_cli.display import ( console, + print_cli_auth_deprecation, print_error, print_info, print_success, print_warning, ) +CLI_AUTH_DEPRECATED_CODE: str = "cli_auth_deprecated" +_LEADING_DIGITS: re.Pattern[str] = re.compile(r"^(\d+)") + +# One notice per `dailybot login` run, even when two doors both carry the field. +_deprecation_noticed: bool = False + + +def _version_parts(version: str) -> tuple[int, ...] | None: + """``"3.29.0rc1"`` → ``(3, 29, 0)``; ``None`` when the first part is not numeric.""" + parts: list[int] = [] + for segment in version.strip().split("."): + match: re.Match[str] | None = _LEADING_DIGITS.match(segment) + if match is None: + break + parts.append(int(match.group(1))) + return tuple(parts) if parts else None + + +def is_version_below(current: str, minimum: str) -> bool: + """Whether ``current`` is older than ``minimum``; ``False`` when either is unreadable.""" + have: tuple[int, ...] | None = _version_parts(current) + need: tuple[int, ...] | None = _version_parts(minimum) + if have is None or need is None: + return False + width: int = max(len(have), len(need)) + return have + (0,) * (width - len(have)) < need + (0,) * (width - len(need)) + + +def _notice_deprecation(body: dict[str, Any] | None) -> None: + """Show the `cli_auth_deprecated` notice once, if the body (or error extra) carries it.""" + global _deprecation_noticed + deprecation: Any = (body or {}).get("deprecation") + if _deprecation_noticed or not isinstance(deprecation, dict): + return + if deprecation.get("code") != CLI_AUTH_DEPRECATED_CODE: + return + minimum: str = str(deprecation.get("min_version") or "") + print_cli_auth_deprecation( + sunset=str(deprecation.get("sunset") or ""), + upgrade_to=minimum if minimum and is_version_below(__version__, minimum) else None, + ) + _deprecation_noticed = True + def _warn_if_env_json_redirects_login() -> None: """Warn when an active ``.dailybot/env.json`` profile redirects the login. @@ -141,7 +187,9 @@ def _verify_and_save( ) except APIError as e: print_error(e.detail) + _notice_deprecation(e.extra) raise SystemExit(1) + _notice_deprecation(result) # If the API says org selection is required, auto-select or prompt if result.get("requires_organization_selection"): @@ -214,7 +262,9 @@ def _do_login(email: str) -> None: request_result: dict[str, Any] = client.request_code(email) except APIError as e: print_error(e.detail) + _notice_deprecation(e.extra) raise SystemExit(1) + _notice_deprecation(request_result) print_success(f"Verification code sent to {email}") print_info("Check your inbox (including spam folder).") @@ -254,7 +304,9 @@ def _request_code_non_interactive(email: str) -> None: request_result: dict[str, Any] = client.request_code(email) except APIError as e: print_error(e.detail) + _notice_deprecation(e.extra) raise SystemExit(1) + _notice_deprecation(request_result) print_success(f"Verification code sent to {email}") print_info("Check your inbox (including spam folder).") @@ -336,6 +388,9 @@ def login(email: str | None, code: str | None, org_uuid: str | None, use_device: if use_device and (code is not None or org_uuid is not None): raise click.UsageError("--device cannot be combined with --code or --org.") + global _deprecation_noticed + _deprecation_noticed = False + _warn_if_env_json_redirects_login() browser: bool = use_device or ( diff --git a/dailybot_cli/commands/public_api_helpers.py b/dailybot_cli/commands/public_api_helpers.py index 2ccc1560..59db5e8d 100644 --- a/dailybot_cli/commands/public_api_helpers.py +++ b/dailybot_cli/commands/public_api_helpers.py @@ -70,6 +70,11 @@ AUTH_BACKEND_UNAVAILABLE_CODE: ( "Dailybot sign-in is temporarily unavailable. Your session is fine; try again in a moment." ), + # 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 " + "`dailybot login --device`." + ), # --- Tasks (/v1/plan/*) ------------------------------------------------- # Written against what the server actually returned in the live probe # recorded in the plan's PERMISSION_MATRIX_OBSERVED.md, not against prose. diff --git a/dailybot_cli/display.py b/dailybot_cli/display.py index 16aec51d..7a51f36b 100644 --- a/dailybot_cli/display.py +++ b/dailybot_cli/display.py @@ -62,6 +62,27 @@ def print_device_login_instructions( print_info(f"Or open {plain_text(verification_uri)} and enter the code yourself.") +def print_cli_auth_deprecation(sunset: str, upgrade_to: str | None = None) -> None: + """The one-time notice that email-code sign-in is being retired (`cli_auth_deprecated`). + + ``upgrade_to`` is set only when this CLI is older than the server's ``min_version``. + The server's own ``detail`` prose is never shown: the instruction depends on this + CLI's version, which only the CLI knows. + """ + when: str = plain_text(sunset) if sunset else "a future date" + if upgrade_to: + print_warning( + f"Email-code sign-in is being retired on {when}. Update the Dailybot CLI to " + f"{plain_text(upgrade_to)} or later (`dailybot upgrade`), then sign in with " + "`dailybot login --device`." + ) + return + print_warning( + f"Email-code sign-in is being retired on {when}. Next time, sign in through the " + "browser with `dailybot login --device`." + ) + + def print_raw_value(value: str) -> None: """Print one bare value for a shell variable: no styling, no wrapping, stdout.""" click.echo(value) diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index cd571ebb..aaaf46fa 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -664,7 +664,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: [...] }` | 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 | +| — | 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 | | `POST` | `/v1/cli/auth/device/` | `{ client_id: "dailybot-cli", client_version }` | `{ device_code, user_code, verification_uri, verification_uri_complete, expires_in, interval }` | No auth. `start_device_authorization()`. A 404/405 means the server predates the device flow. | diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 7c29d0d0..9d5f006d 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -49,6 +49,10 @@ The server answered `503` with `code: auth_backend_unavailable`: its sign-in bac The browser sign-in waits up to 10 minutes for you to approve the code. "Expired" means it was not approved in time; "denied" means someone pressed Deny on the page. Nothing is saved in either case: run `dailybot login --device` again. If the server does not offer browser sign-in yet, the command continues with the email code by itself. +### "Email-code sign-in is being retired on …" (`cli_auth_deprecated`) + +Dailybot is retiring the email-code sign-in in favour of the browser sign-in. While the notice is on, the server adds a `deprecation` field to the email-code answers; the CLI shows the sunset date once per `dailybot login` and the login itself works as before. If your CLI is older than the version the server asks for, the notice tells you to run `dailybot upgrade` first; either way, sign in next time with `dailybot login --device`. After the sunset date the email-code doors stop working. + ### Login OTP never arrives - Check spam. diff --git a/tests/cli_auth_deprecation_test.py b/tests/cli_auth_deprecation_test.py new file mode 100644 index 00000000..adc8d4bc --- /dev/null +++ b/tests/cli_auth_deprecation_test.py @@ -0,0 +1,155 @@ +"""The `deprecation` field on the legacy email-code doors (PLAN_002 T-deprecation-code, W1, L48). + +While `CLI_AUTH_DEPRECATION_NOTICE` is on, request-code and verify-code add +`deprecation: {code: "cli_auth_deprecated", min_version, sunset, detail}` to their +200 and 400 bodies. The CLI shows one notice with the sunset date, the upgrade +instruction only below `min_version`, and never blocks a working login. +""" + +import copy +import json +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.auth import is_version_below +from dailybot_cli.commands.public_api_helpers import ERROR_CODE_MESSAGES +from dailybot_cli.config import load_credentials +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_body, fixture_response + +POST: str = "dailybot_cli.api_client.httpx.post" +VERSION: str = "dailybot_cli.commands.auth.__version__" +SUNSET: str = "2027-03-31" + + +@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 _without_deprecation(name: str) -> MagicMock: + response: MagicMock = fixture_response(name) + body: dict[str, Any] = copy.deepcopy(response.json.return_value) + body.pop("deprecation", None) + response.json.return_value = body + response.text = json.dumps(body) + response.headers = {} + return response + + +def _interactive_login(*responses: MagicMock) -> Result: + with patch(POST, side_effect=list(responses)): + return CliRunner().invoke(cli, ["login"], input="me@example.com\n123456\n") + + +class TestNotice: + def test_a_200_completes_the_login_with_one_notice(self) -> None: + with patch(VERSION, "3.29.0"): + result: Result = _interactive_login( + fixture_response("request_code_deprecation_200"), + fixture_response("verify_code_deprecation_200"), + ) + assert result.exit_code == 0, result.output + assert "Logged in as me@example.com" in result.output + assert result.output.count(SUNSET) == 1 + assert load_credentials() is not None + + def test_a_current_cli_suggests_the_browser_sign_in(self) -> None: + with patch(VERSION, "3.29.0"): + result: Result = _interactive_login( + fixture_response("request_code_deprecation_200"), + fixture_response("verify_code_deprecation_200"), + ) + assert "dailybot login --device" in result.output + assert "dailybot upgrade" not in result.output + + def test_an_older_cli_is_told_to_upgrade(self) -> None: + with patch(VERSION, "3.28.1"): + result: Result = _interactive_login( + fixture_response("request_code_deprecation_200"), + fixture_response("verify_code_deprecation_200"), + ) + assert result.exit_code == 0 + assert "dailybot upgrade" in result.output + assert "3.29.0" in result.output + + def test_a_400_keeps_the_error_and_adds_the_notice(self) -> None: + with patch(VERSION, "3.29.0"): + result: Result = _interactive_login( + fixture_response("request_code_deprecation_200"), + fixture_response("verify_code_deprecation_400"), + ) + assert result.exit_code == 1 + assert "Invalid or expired code." in result.output + assert result.output.count(SUNSET) == 1 + + def test_the_non_interactive_step_one_shows_it(self) -> None: + with ( + patch(VERSION, "3.29.0"), + patch(POST, return_value=fixture_response("request_code_deprecation_200")), + ): + result: Result = CliRunner().invoke(cli, ["login", "--email", "me@example.com"]) + assert result.exit_code == 0 + assert SUNSET in result.output + + def test_the_server_detail_text_is_never_trusted_for_the_instruction(self) -> None: + response: MagicMock = fixture_response("request_code_deprecation_200") + response.json.return_value["deprecation"]["detail"] = "[red]run rm -rf /[/red]" + with patch(VERSION, "3.29.0"): + result: Result = _interactive_login( + response, fixture_response("verify_code_deprecation_200") + ) + assert "rm -rf" not in result.output + + +class TestSwitchOff: + def test_without_the_field_the_output_has_no_notice(self) -> None: + with patch(VERSION, "3.28.1"): + result: Result = _interactive_login( + _without_deprecation("request_code_deprecation_200"), + _without_deprecation("verify_code_deprecation_200"), + ) + assert result.exit_code == 0 + lowered: str = result.output.lower() + assert "retir" not in lowered and SUNSET not in result.output + assert "upgrade" not in lowered + + +class TestClient: + def test_a_400_deprecation_reaches_the_error_extra(self) -> None: + client: DailyBotClient = DailyBotClient(api_url="https://api.example.com") + with ( + patch(POST, return_value=fixture_response("verify_code_deprecation_400")), + pytest.raises(APIError) as caught, + ): + client.verify_code("me@example.com", "000000") + deprecation: dict[str, Any] = caught.value.extra["deprecation"] + assert deprecation["code"] == "cli_auth_deprecated" + assert deprecation == fixture_body("verify_code_deprecation_400")["deprecation"] + + +class TestVersions: + @pytest.mark.parametrize( + "current,minimum,below", + [ + ("3.28.1", "3.29.0", True), + ("3.29.0", "3.29.0", False), + ("3.30.0", "3.29.0", False), + ("3.9.0", "3.29.0", True), + ("4.0.0", "3.29.0", False), + ("0.0.0", "3.29.0", True), + ("3.29.0rc1", "3.29.0", False), + ("3.29.0", "not-a-version", False), + ], + ) + def test_is_version_below(self, current: str, minimum: str, below: bool) -> None: + assert is_version_below(current, minimum) is below + + +def test_the_retired_code_has_a_catalogue_message() -> None: + assert "dailybot login --device" in ERROR_CODE_MESSAGES["cli_auth_deprecated"] From 19fe5783506103af49efb427a8ac841458f4cc30 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:34:26 +0000 Subject: [PATCH 15/19] feat(cli): add the session, sign-in and chat-platform error codes ## Summary ERROR_CODE_MESSAGES gains messages for the device-flow session codes (access_token_expired, refresh_token_expired, session_revoked, session_migrated, user_disabled), the RFC 8628 sign-in codes, the chat-platform attach codes and the qualified channel-reference codes (channel_reference_ambiguous / _unknown). The five session 401 codes replace the generic "Session expired" line; every other 401 keeps it, and unknown codes still show the server detail. ## Change Log - catalogue entries + SESSION_401_CODES in public_api_helpers - feature_not_available keeps its existing message (attach is web-only) - docs/API_REFERENCE.md: error translation rows and code table ## Risks - None for existing codes: their messages and exit codes are unchanged Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/commands/public_api_helpers.py | 83 ++++++++++++++- docs/API_REFERENCE.md | 20 ++++ tests/standalone_error_codes_test.py | 107 ++++++++++++++++++++ 3 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 tests/standalone_error_codes_test.py diff --git a/dailybot_cli/commands/public_api_helpers.py b/dailybot_cli/commands/public_api_helpers.py index 59db5e8d..80553d40 100644 --- a/dailybot_cli/commands/public_api_helpers.py +++ b/dailybot_cli/commands/public_api_helpers.py @@ -70,6 +70,69 @@ AUTH_BACKEND_UNAVAILABLE_CODE: ( "Dailybot sign-in is temporarily unavailable. Your session is fine; try again in a moment." ), + "session_revoked": ( + "Your Dailybot session was signed out (a logout elsewhere, or it was revoked). " + "Run `dailybot login` to sign in again." + ), + "session_migrated": ( + "Your Dailybot session was replaced by a newer sign-in. " + "Run `dailybot login` to sign in again." + ), + "refresh_token_expired": ( + "Your Dailybot session has expired. Run `dailybot login` to sign in again." + ), + "access_token_expired": ( + "Your Dailybot session needs renewing. Run the command again, and " + "`dailybot login` if it keeps failing." + ), + "user_disabled": ( + "This Dailybot account is deactivated. Ask an organization admin to reactivate it." + ), + # --- Browser (device-flow) sign-in, RFC 8628 ------------------------------ + "authorization_pending": "The sign-in has not been approved in the browser yet.", + "slow_down": "The CLI checked for the approval too often; wait a few seconds and retry.", + "access_denied": "The sign-in was denied in the browser.", + "expired_token": ( + "The sign-in code expired before it was approved. Run `dailybot login --device` again." + ), + "invalid_grant": ( + "This sign-in request is no longer valid. Run `dailybot login --device` again." + ), + "invalid_client": ( + "The server refused this sign-in request. Update the Dailybot CLI with " + "`dailybot upgrade` and try again." + ), + # --- Chat platforms: attach (web) and qualified channel references ------- + "tenant_already_bound": ( + "That chat workspace is already connected to another Dailybot organization. " + "Disconnect it there first, from the Dailybot web app." + ), + "pending_link": ( + "This chat workspace is waiting for its connection to be confirmed in the Dailybot web app." + ), + "channel_write_forbidden": ( + "This organization's chat platforms are managed in the Dailybot web app; " + "that change is not allowed here." + ), + "tenant_ambiguous": ( + "Dailybot could not tell which chat workspace to use. Connect it from the Dailybot web app." + ), + "channel_attach_unsupported": ( + "This organization cannot connect another chat platform. Manage its chat " + "platforms in the Dailybot web app." + ), + "attach_forbidden": ( + "Only an organization admin can connect a chat platform, from the Dailybot web app." + ), + "channel_reference_ambiguous": ( + "More than one chat platform matches that channel. Qualify it with the platform " + "(`slack:`, `msteams:`, `discord:`, `hangouts:`) or the platform " + "id from `dailybot org` (`:`)." + ), + "channel_reference_unknown": ( + "That chat platform is not connected to this organization. Run `dailybot org` " + "to see the chat platforms you can use." + ), # 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 " @@ -1056,6 +1119,19 @@ def agent_error_message(exc: APIError) -> str: return f"{message}{_throttle_hint(exc, _retry_after_seconds(exc))}" +# 401 codes of the device-flow session (DEVICE_FLOW_WIRE §4, CONTRACT_SESSION §7) +# whose message replaces the generic "Session expired" line. +SESSION_401_CODES: frozenset[str] = frozenset( + { + "session_revoked", + "session_migrated", + "refresh_token_expired", + "access_token_expired", + "user_disabled", + } +) + + def exit_for_api_error( exc: APIError, json_mode: bool, @@ -1086,7 +1162,12 @@ def exit_for_api_error( mapped_message = code_overrides[code] if exc.status_code == 401: - message: str = "Session expired. Run: dailybot login" + # The session codes name why the session ended; any other 401 keeps today's text. + message: str = ( + mapped_message + if code in SESSION_401_CODES and mapped_message + else "Session expired. Run: dailybot login" + ) exit_code: int = EXIT_NOT_AUTHENTICATED elif exc.status_code == 403: message = mapped_message or exc.detail diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index aaaf46fa..1ddef090 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -820,6 +820,26 @@ not a dead session: it keeps the server's `detail` and `code`. | 400 with "ai processing failed" | — | `update.py` rewrites to a support-contact message | | 429 | passes through (`retry_after` from the `Retry-After` header) | A known `code` (`registration_rate_limited`, `free_plan_daily_limit_exceeded`) shows its message plus "Try again in Ns."; without a code, `agent email send` says "Hourly email limit exceeded" and `agent register` says "Rate limited." with the wait | | `httpx.TimeoutException` | propagates from httpx | `update.py` and `interactive.py` catch and emit a "may be processing your update" message | +| 401 `access_token_expired` (device-flow session) | the client refreshes the pair once and replays the request once (`_refresh_session`) | — | +| 503 `auth_backend_unavailable` | retried 3 times, each waiting `min(Retry-After, 5 s)`; never a refresh, an API-key fallback or a credential change | "Dailybot sign-in is temporarily unavailable", exit `6`; `logout` keeps the local session | + +### Session, sign-in and chat-platform codes (PLAN_002) + +`exit_for_api_error` maps each of these codes to its `ERROR_CODE_MESSAGES` entry; the exit code follows the status as for every other code (401 → `3`, 403 → `4`, 400 → `2`, 409 → `1`, 503 → `6`). An unknown code still shows the server's `detail`. Any other 401 keeps "Session expired. Run: dailybot login". + +| Code | Status | Where it comes from | +| --- | --- | --- | +| `access_token_expired` | 401 | any `/v1/*` door with an expired device-flow access token (refreshed transparently first) | +| `refresh_token_expired`, `session_revoked`, `session_migrated`, `user_disabled` | 401 | the refresh door, or any door with an ended session | +| `authorization_pending`, `slow_down`, `access_denied`, `expired_token`, `invalid_grant`, `invalid_client` | 400 | the device-token door (`dailybot login --device` handles them in its polling loop) | +| `auth_backend_unavailable` | 503 + `Retry-After` | web-session doors; defensive for the CLI | +| `cli_auth_deprecated` | a body field today | the legacy email-code doors (see the auth table) | +| `channel_reference_ambiguous` | 409 | `/v1/send-message/`, Tasks routes and channels: a raw id matches more than one chat platform; qualify it | +| `channel_reference_unknown` | 400 | same doors: the qualified platform or platform id is not connected to the organization | +| `platform_not_connected` | 400 | `chat send` / Tasks channel routes on an organization with no external chat platform | +| `tenant_already_bound`, `pending_link`, `tenant_ambiguous`, `channel_attach_unsupported` | 409 | connecting a chat platform in the web app | +| `attach_forbidden`, `feature_not_available` | 403 | connecting a chat platform in the web app | +| `channel_write_forbidden` | 400 | a legacy writer touching an organization whose chat platforms are managed in the web app | ## Plan — `/v1/plan/*` diff --git a/tests/standalone_error_codes_test.py b/tests/standalone_error_codes_test.py new file mode 100644 index 00000000..4731187f --- /dev/null +++ b/tests/standalone_error_codes_test.py @@ -0,0 +1,107 @@ +"""Attach, session, device and channel-reference codes (PLAN_002 T-error-catalogue). + +The CLI dispatches on `code`, never on `detail` prose (AGENTS.md Rule 10). Each new +code has a catalogue message; the exit code follows the status as for every other +code; an unknown code still falls back to the server detail. +""" + +import json + +import pytest + +from dailybot_cli.api_client import APIError +from dailybot_cli.commands.public_api_helpers import ( + ERROR_CODE_MESSAGES, + EXIT_NOT_AUTHENTICATED, + EXIT_PERMISSION_DENIED, + EXIT_USAGE_ERROR, + exit_for_api_error, +) + +# (code, the status its door answers with, the exit code that status maps to) +NEW_CODES: list[tuple[str, int, int]] = [ + ("tenant_already_bound", 409, 1), + ("pending_link", 409, 1), + ("channel_write_forbidden", 400, EXIT_USAGE_ERROR), + ("tenant_ambiguous", 409, 1), + ("channel_attach_unsupported", 409, 1), + ("attach_forbidden", 403, EXIT_PERMISSION_DENIED), + ("feature_not_available", 403, EXIT_PERMISSION_DENIED), + ("session_revoked", 401, EXIT_NOT_AUTHENTICATED), + ("session_migrated", 401, EXIT_NOT_AUTHENTICATED), + ("refresh_token_expired", 401, EXIT_NOT_AUTHENTICATED), + ("access_token_expired", 401, EXIT_NOT_AUTHENTICATED), + ("user_disabled", 401, EXIT_NOT_AUTHENTICATED), + ("invalid_grant", 400, EXIT_USAGE_ERROR), + ("invalid_client", 400, EXIT_USAGE_ERROR), + ("authorization_pending", 400, EXIT_USAGE_ERROR), + ("slow_down", 400, EXIT_USAGE_ERROR), + ("access_denied", 400, EXIT_USAGE_ERROR), + ("expired_token", 400, EXIT_USAGE_ERROR), + ("channel_reference_ambiguous", 409, 1), + ("channel_reference_unknown", 400, EXIT_USAGE_ERROR), +] +DETAIL: str = "server prose that must not be shown when a code maps" + + +def _flat(text: str) -> str: + return " ".join(text.split()) + + +@pytest.mark.parametrize("code,status,exit_code", NEW_CODES, ids=[c[0] for c in NEW_CODES]) +def test_each_code_renders_its_message_and_exit_code( + code: str, status: int, exit_code: int, capsys: pytest.CaptureFixture[str] +) -> None: + assert ERROR_CODE_MESSAGES[code] + with pytest.raises(SystemExit) as caught: + exit_for_api_error(APIError(status, DETAIL, code=code), json_mode=False) + assert caught.value.code == exit_code + err: str = _flat(capsys.readouterr().err) + assert _flat(ERROR_CODE_MESSAGES[code]) in err + assert DETAIL not in err + + +@pytest.mark.parametrize("code,status,exit_code", NEW_CODES, ids=[c[0] for c in NEW_CODES]) +def test_json_mode_keeps_the_code( + code: str, status: int, exit_code: int, capsys: pytest.CaptureFixture[str] +) -> None: + with pytest.raises(SystemExit): + exit_for_api_error(APIError(status, DETAIL, code=code), json_mode=True) + payload: dict[str, object] = json.loads(capsys.readouterr().out) + assert payload["code"] == code + assert payload["status"] == status + + +@pytest.mark.parametrize("code", [c[0] for c in NEW_CODES]) +def test_messages_use_the_brand_spelling(code: str) -> None: + assert "DailyBot" not in ERROR_CODE_MESSAGES[code] + + +def test_an_unknown_code_still_falls_back_to_the_detail(capsys: pytest.CaptureFixture[str]) -> None: + with pytest.raises(SystemExit) as caught: + exit_for_api_error(APIError(409, "Some new conflict.", code="brand_new_code"), False) + assert caught.value.code == 1 + assert "Some new conflict." in capsys.readouterr().err + + +def test_an_existing_401_code_keeps_the_session_expired_text( + capsys: pytest.CaptureFixture[str], +) -> None: + with pytest.raises(SystemExit) as caught: + exit_for_api_error(APIError(401, "x", code="invalid_credentials"), False) + assert caught.value.code == EXIT_NOT_AUTHENTICATED + assert "Session expired. Run: dailybot login" in capsys.readouterr().err + + +def test_a_401_without_a_code_keeps_the_session_expired_text( + capsys: pytest.CaptureFixture[str], +) -> None: + with pytest.raises(SystemExit): + exit_for_api_error(APIError(401, "x"), False) + assert "Session expired. Run: dailybot login" in capsys.readouterr().err + + +def test_qualified_reference_hints_name_the_forms() -> None: + ambiguous: str = ERROR_CODE_MESSAGES["channel_reference_ambiguous"] + assert "slack:" in ambiguous and "dailybot org" in ambiguous + assert "dailybot org" in ERROR_CODE_MESSAGES["channel_reference_unknown"] From cd8c135918cefc29c7d6b02128992241fc85e01b Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:37:39 +0000 Subject: [PATCH 16/19] feat(cli): accept qualified channel references ## Summary `chat send --channel` and the Tasks route/report/notification channel flags accept the frozen grammar: raw ids and names as today, `slack|msteams|discord|hangouts:` (split on the first colon, so a Teams `19:` id stays raw) and `:`. Qualified forms are sent verbatim, only to organizations whose /v1/organization/ serves `chat_platforms` (read once, only when a qualified reference is typed); others get a usage error asking for the raw id. `dailybot:` is refused: a message never goes to Dailybot Chat. The server's channel_reference_ambiguous / _unknown render by code. ## Change Log - _channels.py: parse_channel_reference, check_chat_channel_references, qualified branch in resolve_channel - chat._execute_send checks the targets (send, update, --payload-json) - docs: API_REFERENCE channel-reference table, README rows ## Risks - Raw references are unchanged and cost no extra request Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- dailybot_cli/commands/_channels.py | 120 ++++++++++++++++ dailybot_cli/commands/chat.py | 2 + docs/API_REFERENCE.md | 12 +- tests/qualified_channels_test.py | 218 +++++++++++++++++++++++++++++ 5 files changed, 353 insertions(+), 3 deletions(-) create mode 100644 tests/qualified_channels_test.py diff --git a/README.md b/README.md index d1d64b63..99a097c6 100644 --- a/README.md +++ b/README.md @@ -952,7 +952,7 @@ humans who own them. | `dailybot plan ...` | The one root of **Dailybot Plan** (API root `/v1/plan/`): the `tasks`, `task`, `board`, `project` and `goal` groups all live under it, e.g. `dailybot plan tasks status` | | `dailybot plan tasks timeline` | Dated work in a window: the goals that overlap it, the tasks with start or due dates, the milestones in the window and the projects overlapping it (`--since` / `--until` / `--date` / `--today` / `--last-week`, `--include-unscheduled`, repeatable `--project` and `--milestone`). One document, not a paged list | | `dailybot plan tasks notifications catalog` · `get` · `set` | Personal notification preferences: the kinds (`catalog`), your kind × chat × email matrix and destination (`get`), and a partial `set` (`--kind` repeatable with `--chat/--no-chat`, `--email/--no-email`, and `--dm` or `--channel `, public channels only). **Needs a person: `dailybot login` or a personal API key** | -| `dailybot plan tasks channels search [-q ] [--type public]` | The chat-platform channels you can pick (admins also see the private ones the bot is in); the external id it shows is what routes, reports and `chat send --channel` take. Not `channels list` (report channels) | +| `dailybot plan tasks channels search [-q ] [--type public]` | The chat-platform channels you can pick (admins also see the private ones the bot is in); the external id it shows is what routes, reports and `chat send --channel` take (optionally qualified as `slack:` or `:` on organizations with several chat platforms). Not `channels list` (report channels) | | `dailybot plan tasks routes list` · `get` · `create` · `update` · `delete` · `send-test` · `deliveries` | Post organization events (card created/completed/blocked, project health or lead changed, milestone reached, ...) to a channel: `create --name --channel --kind ...` with optional `--board` / `--project` scope. **Admins write, members read.** `send-test` always previews with a dry run first and posts only after confirmation or `--yes`; `delete` states its consequence | | `dailybot plan tasks reports list` · `get` · `create` · `update` · `delete` · `preview` · `send-test` · `runs` | Scheduled Tasks digests (`daily`, `week_start`, `week_end`) to a channel and/or by email: `--weekdays mon,fri` (weekly kinds take exactly one), `--time 09:00`, `--timezone` (yours by default), `--email-to `. `preview` is the exact document; `send-test` is dry-run first. Admins write, members read | | `dailybot plan tasks briefing get` · `set` · `preview` · `send-test` | Your personal daily briefing (overdue, due today, in progress, blocked, mentions, projects you lead), by DM and/or email, on chosen weekdays and time. Person doors; `send-test` is dry-run first | @@ -1090,7 +1090,7 @@ Works headless for agents (`--json` prints the `bot_message_id`). | Command | Description | |---------|-------------| -| `dailybot chat send` | Send a bot message to users (`-u`), channels (`-c`), and/or teams (`-t`) | +| `dailybot chat send` | Send a bot message to users (`-u`), channels (`-c`, a channel id or a qualified `slack:` / `:`), and/or teams (`-t`) | | `dailybot chat update ` | Edit a previously sent message (parent **or** a thread reply) | | `dailybot conversation open` | Open (or reuse) a Slack group DM with the bot; optionally post a message (`-m`) | diff --git a/dailybot_cli/commands/_channels.py b/dailybot_cli/commands/_channels.py index f10c3836..80ec3e3d 100644 --- a/dailybot_cli/commands/_channels.py +++ b/dailybot_cli/commands/_channels.py @@ -4,13 +4,22 @@ chat-platform id that ``dailybot chat send --channel`` also takes). A person types either that id or the channel's name, so the commands resolve the typed reference through ``tasks channels search``. Channel names are user-authored text: they are quoted as data wherever they appear in a message. + +Qualified references (PLAN_002, frozen grammar W2, L44, L74). Besides a raw id or a name, a channel can +be named on one chat platform of the organization: `slack:C0123` (platform-qualified, split on the first +colon, so `msteams:19:abc@thread.tacv2` keeps its Teams id) or `:C0123`, where the platform +id is a `ChatPlatformSummary.id` from `dailybot org`. A raw Teams id `19:...` stays raw. Qualified forms +are sent only to organizations whose `/v1/organization/` serves `chat_platforms`; raw ids keep working +until the multi-channel release + 90 days. """ import re +from dataclasses import dataclass from typing import Any import click +from dailybot_cli.api_client import APIError, TransportError from dailybot_cli.display import plain_text, present_untrusted PUBLIC_CHANNEL_TYPE: str = "channel" @@ -19,6 +28,89 @@ SINGLE_TOKEN_PATTERN: re.Pattern[str] = re.compile(r"^\S+$") MAX_CANDIDATES_SHOWN: int = 8 +PLATFORM_QUALIFIED_PATTERN: re.Pattern[str] = re.compile(r"^(slack|msteams|discord|hangouts):(.+)$") +INSTALLATION_QUALIFIED_PATTERN: re.Pattern[str] = re.compile( + r"^([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}):(.+)$" +) +# Not a chat send destination in phase 1: an org without an external platform answers +# `platform_not_connected`, and the CLI never routes a message to Dailybot Chat instead. +DAILYBOT_PREFIX_PATTERN: re.Pattern[str] = re.compile(r"^(dailybot):(.*)$") +CHAT_PLATFORMS_KEY: str = "chat_platforms" + + +@dataclass(frozen=True) +class ChannelReference: + """A parsed channel reference: ``kind`` is raw, platform, installation or dailybot.""" + + kind: str + qualifier: str | None + channel_id: str + original: str + + @property + def is_qualified(self) -> bool: + return self.kind in ("platform", "installation") + + +def parse_channel_reference(reference: str) -> ChannelReference: + """Classify a channel reference by the frozen grammar; anything else is raw.""" + for kind, pattern in ( + ("platform", PLATFORM_QUALIFIED_PATTERN), + ("installation", INSTALLATION_QUALIFIED_PATTERN), + ("dailybot", DAILYBOT_PREFIX_PATTERN), + ): + match: re.Match[str] | None = pattern.match(reference) + if match: + return ChannelReference(kind, match.group(1), match.group(2), reference) + return ChannelReference("raw", None, reference, reference) + + +def _org_serves_chat_platforms(client: Any) -> bool | None: + """Whether the organization takes qualified references; ``None`` when it cannot be read. + + The keys are served only when the organization's gate is on (L74), so their presence is + the signal. Read only when a qualified reference was actually typed. + """ + try: + organization: Any = client.get_organization() + except (APIError, TransportError): + return None + return isinstance(organization, dict) and CHAT_PLATFORMS_KEY in organization + + +def _qualified_refused(reference: ChannelReference) -> click.UsageError: + return click.UsageError( + f"This organization does not take platform-qualified channels yet. Pass the channel id " + f"alone: {plain_text(reference.channel_id)}" + ) + + +def check_chat_channel_references(client: Any, payload: dict[str, Any]) -> None: + """Validate the `target_channels` of a chat send payload against the grammar. + + Raw references pass untouched and cost nothing. A `dailybot:` reference is refused. Qualified + references pass verbatim when the organization serves `chat_platforms`, and are refused when it + does not (the server would read them as raw ids). If the organization cannot be read, the payload + goes as typed and the server decides. + """ + targets: Any = payload.get("target_channels") + if not isinstance(targets, list): + return + references: list[ChannelReference] = [] + for target in targets: + raw: Any = target.get("id") if isinstance(target, dict) else target + if isinstance(raw, str): + references.append(parse_channel_reference(raw)) + for reference in references: + if reference.kind == "dailybot": + raise click.UsageError( + "`dailybot:` is not a chat send destination: messages are never delivered to " + "Dailybot Chat. Target a channel on a connected chat platform (see `dailybot org`)." + ) + qualified: list[ChannelReference] = [r for r in references if r.is_qualified] + if qualified and _org_serves_chat_platforms(client) is False: + raise _qualified_refused(qualified[0]) + def _describe(channel: dict[str, Any]) -> str: return f"{present_untrusted(channel.get('name'), limit=40)} ({plain_text(channel.get('external_id'))})" @@ -32,6 +124,9 @@ def resolve_channel(client: Any, reference: str, *, public_only: bool = False) - """ wanted: str = reference.strip() channel_type: str | None = PUBLIC_CHANNEL_TYPE if public_only else None + parsed: ChannelReference = parse_channel_reference(wanted) + if parsed.is_qualified: + return _resolve_qualified(client, parsed, channel_type) def fetch(search: str | None) -> list[dict[str, Any]]: result: Any = client.search_channels( @@ -78,3 +173,28 @@ def _as_reference(channel: dict[str, Any]) -> dict[str, str]: "name": str(channel.get("name", "")), "type": str(channel.get("type", PUBLIC_CHANNEL_TYPE)), } + + +def _resolve_qualified( + client: Any, reference: ChannelReference, channel_type: str | None +) -> dict[str, str]: + """A qualified reference keeps its qualifier on the wire; the list only fills in the name. + + The server owns the platform match (`channel_reference_unknown` / `_ambiguous`), so a channel + the list does not show is still sent as typed. + """ + if _org_serves_chat_platforms(client) is False: + raise _qualified_refused(reference) + result: Any = client.search_channels(search=None, channel_type=channel_type, fetch_all=True) + for channel in result.results: + if isinstance(channel, dict) and str(channel.get("external_id")) == reference.channel_id: + return { + "external_id": reference.original, + "name": str(channel.get("name", "")), + "type": str(channel.get("type", PUBLIC_CHANNEL_TYPE)), + } + return { + "external_id": reference.original, + "name": "", + "type": channel_type or PUBLIC_CHANNEL_TYPE, + } diff --git a/dailybot_cli/commands/chat.py b/dailybot_cli/commands/chat.py index aedfefb9..69c19493 100644 --- a/dailybot_cli/commands/chat.py +++ b/dailybot_cli/commands/chat.py @@ -26,6 +26,7 @@ import click from dailybot_cli.api_client import APIError, DailyBotClient +from dailybot_cli.commands._channels import check_chat_channel_references from dailybot_cli.commands.agent import _merge_repo_metadata, _resolve_agent_context from dailybot_cli.commands.public_api_helpers import ( EXIT_NOT_AUTHENTICATED, @@ -305,6 +306,7 @@ def _execute_send( json_mode: bool = False, ) -> dict[str, Any]: """Call the API with friendly error translation; return the result or exit.""" + check_chat_channel_references(client, payload) if payload.get("platform_settings", {}).get("is_ephemeral") and not payload.get("target_users"): # The API silently skips an ephemeral message with no resolvable user. print_warning( diff --git a/docs/API_REFERENCE.md b/docs/API_REFERENCE.md index 1ddef090..c3102b2d 100644 --- a/docs/API_REFERENCE.md +++ b/docs/API_REFERENCE.md @@ -534,9 +534,19 @@ At least one target is required. Targets: | Flag | Repeatable | Accepts | |------|-----------|---------| | `--user` / `-u` | yes | user UUID, email, or chat external id (delivered as DM) | -| `--channel` / `-c` | yes | channel id | +| `--channel` / `-c` | yes | channel id, or a qualified reference (below) | | `--team` / `-t` | yes | team UUID (expanded to members as DMs) | +**Channel references.** `--channel` here, and `--channel` on `plan tasks routes` / `reports` / `notifications`, take three forms: + +| Form | Example | Meaning | +|------|---------|---------| +| raw | `C024BE91L`, `19:abc@thread.tacv2` | the channel on the organization's chat platform, as today. A Microsoft Teams id starting `19:` is always raw. | +| platform-qualified | `slack:C024BE91L`, `msteams:19:abc@thread.tacv2` | the channel on the organization's `slack`, `msteams`, `discord` or `hangouts` platform. Split on the first colon only. | +| platform-id-qualified | `:C024BE91L` | the channel on one specific chat platform; the platform id is the `id` `dailybot org` lists under **Chat platforms**. | + +Qualified forms are sent verbatim, and only to organizations whose `/v1/organization/` serves `chat_platforms` (the CLI reads it once, and only when a qualified reference was typed); other organizations get a usage error asking for the raw id. `dailybot:` is refused: a message is never delivered to Dailybot Chat. The server answers `409 channel_reference_ambiguous` when a raw id matches more than one platform, and `400 channel_reference_unknown` when the qualified platform is not connected. Raw ids keep working until the multi-channel release plus 90 days. + Content & options: `--text/-m`, `--image-url/-i`, `--link-button "Label::url"` (repeatable), `--button "Label::value"` (interactive, repeatable), `--buttons ''` (full button contract — callbacks, modals, response, diff --git a/tests/qualified_channels_test.py b/tests/qualified_channels_test.py new file mode 100644 index 00000000..16e0b3f8 --- /dev/null +++ b/tests/qualified_channels_test.py @@ -0,0 +1,218 @@ +"""Qualified channel references (PLAN_002 T-qualified-channels, W2 grammar, L44, L74). + +Forms: raw (today's ids and names), platform-qualified `slack|msteams|discord|hangouts:` +split on the first colon, and installation-qualified `:`. +A Teams id `19:…` stays raw; `dailybot:` is not a chat send destination; qualified +forms are sent only when `/v1/organization/` serves `chat_platforms`. +""" + +from typing import Any +from unittest.mock import MagicMock, patch + +import click +import pytest +from click.testing import CliRunner, Result + +from dailybot_cli.api_client import APIError, DailyBotClient, PaginatedResult +from dailybot_cli.commands._channels import ( + ChannelReference, + check_chat_channel_references, + parse_channel_reference, + resolve_channel, +) +from dailybot_cli.main import cli +from tests.wire_fixture_loader import fixture_body, fixture_response + +PLATFORM_ID: str = fixture_body("organization_chat_platforms_no_plan_200")["chat_platforms"][0][ + "id" +] + + +class TestGrammar: + @pytest.mark.parametrize( + "reference,kind,qualifier,channel_id", + [ + ("C024BE91L", "raw", None, "C024BE91L"), + ("19:abc@thread.tacv2", "raw", None, "19:abc@thread.tacv2"), + ("general", "raw", None, "general"), + ("slack:C024BE91L", "platform", "slack", "C024BE91L"), + ("msteams:19:abc@thread.tacv2", "platform", "msteams", "19:abc@thread.tacv2"), + ("discord:123456789012345678", "platform", "discord", "123456789012345678"), + ("hangouts:spaces/AAAA", "platform", "hangouts", "spaces/AAAA"), + (f"{PLATFORM_ID}:C024BE91L", "installation", PLATFORM_ID, "C024BE91L"), + ("dailybot:C1", "dailybot", "dailybot", "C1"), + ("Slack:C1", "raw", None, "Slack:C1"), + ("slack:", "raw", None, "slack:"), + ( + "00000000-0000-4000-8000-00000000002G:C1", + "raw", + None, + "00000000-0000-4000-8000-00000000002G:C1", + ), + ], + ) + def test_the_frozen_forms( + self, reference: str, kind: str, qualifier: str | None, channel_id: str + ) -> None: + parsed: ChannelReference = parse_channel_reference(reference) + assert parsed.kind == kind + assert parsed.qualifier == qualifier + assert parsed.channel_id == channel_id + assert parsed.original == reference + + +def _org_client(body_name: str | None) -> MagicMock: + client: MagicMock = MagicMock(spec=DailyBotClient) + if body_name is None: + client.get_organization.side_effect = APIError(500, "boom") + else: + client.get_organization.return_value = fixture_body(body_name) + return client + + +class TestChatTargets: + def test_raw_targets_never_read_the_organization(self) -> None: + client: MagicMock = _org_client("organization_legacy_200") + payload: dict[str, Any] = {"target_channels": ["C0", "19:abc@thread.tacv2"]} + check_chat_channel_references(client, payload) + client.get_organization.assert_not_called() + assert payload == {"target_channels": ["C0", "19:abc@thread.tacv2"]} + + def test_qualified_targets_pass_when_platforms_are_served(self) -> None: + client: MagicMock = _org_client("organization_chat_platforms_no_plan_200") + payload: dict[str, Any] = { + "target_channels": ["slack:C0", {"id": f"{PLATFORM_ID}:C1", "thread": "1.2"}] + } + check_chat_channel_references(client, payload) + assert payload["target_channels"] == [ + "slack:C0", + {"id": f"{PLATFORM_ID}:C1", "thread": "1.2"}, + ] + client.get_organization.assert_called_once() + + def test_qualified_targets_stop_when_platforms_are_not_served(self) -> None: + client: MagicMock = _org_client("organization_legacy_200") + with pytest.raises(click.UsageError) as caught: + check_chat_channel_references(client, {"target_channels": ["slack:C0"]}) + assert "C0" in str(caught.value.message) + + def test_an_unreadable_organization_leaves_the_decision_to_the_server(self) -> None: + client: MagicMock = _org_client(None) + payload: dict[str, Any] = {"target_channels": ["slack:C0"]} + check_chat_channel_references(client, payload) + assert payload["target_channels"] == ["slack:C0"] + + def test_dailybot_is_not_a_chat_send_destination(self) -> None: + client: MagicMock = _org_client("organization_native_200") + with pytest.raises(click.UsageError) as caught: + check_chat_channel_references(client, {"target_channels": ["dailybot:C1"]}) + assert "Dailybot Chat" in str(caught.value.message) + client.get_organization.assert_not_called() + + +class TestChatSendCommand: + @staticmethod + def _send(*args: str, org: str) -> tuple[Result, MagicMock]: + client: DailyBotClient = DailyBotClient( + api_url="https://api.example.com", api_key="test-key" + ) + sent: MagicMock = MagicMock() + sent.status_code = 200 + sent.headers = {} + sent.json.return_value = {"bot_message_id": "1"} + with ( + patch( + "dailybot_cli.commands.chat._resolve_agent_context", return_value=("A", client, {}) + ), + patch("dailybot_cli.api_client.httpx.get", return_value=fixture_response(org)), + patch("dailybot_cli.api_client.httpx.request", return_value=sent) as request, + ): + result: Result = CliRunner().invoke(cli, ["chat", "send", *args, "-m", "hi"]) + return result, request + + def test_a_qualified_channel_is_sent_verbatim(self) -> None: + result, request = self._send( + "-c", "msteams:19:abc@thread.tacv2", org="organization_chat_platforms_no_plan_200" + ) + assert result.exit_code == 0, result.output + assert request.call_args.kwargs["json"]["target_channels"] == [ + "msteams:19:abc@thread.tacv2" + ] + + def test_a_raw_teams_id_is_sent_unchanged(self) -> None: + result, request = self._send("-c", "19:abc@thread.tacv2", org="organization_legacy_200") + assert result.exit_code == 0, result.output + assert request.call_args.kwargs["json"]["target_channels"] == ["19:abc@thread.tacv2"] + + def test_a_qualified_channel_on_an_org_without_platforms_is_refused_locally(self) -> None: + result, request = self._send("-c", "slack:C0", org="organization_legacy_200") + assert result.exit_code == 2 + request.assert_not_called() + + def test_dailybot_prefix_is_refused(self) -> None: + result, request = self._send("-c", "dailybot:C0", org="organization_native_200") + assert result.exit_code == 2 + request.assert_not_called() + + @pytest.mark.parametrize( + "fixture,code,exit_code", + [ + ("channel_reference_ambiguous_409", "channel_reference_ambiguous", 1), + ("channel_reference_unknown_400", "channel_reference_unknown", 2), + ], + ) + def test_the_server_codes_render_by_code(self, fixture: str, code: str, exit_code: int) -> None: + client: DailyBotClient = DailyBotClient( + api_url="https://api.example.com", api_key="test-key" + ) + with ( + patch( + "dailybot_cli.commands.chat._resolve_agent_context", return_value=("A", client, {}) + ), + patch("dailybot_cli.api_client.httpx.request", return_value=fixture_response(fixture)), + ): + result: Result = CliRunner().invoke(cli, ["chat", "send", "-c", "C0", "-m", "hi"]) + assert result.exit_code == exit_code + assert "dailybot org" in " ".join(result.output.split()) + + +class TestTasksResolver: + @staticmethod + def _client(org: str | None, channels: list[dict[str, Any]]) -> MagicMock: + client: MagicMock = _org_client(org) + client.search_channels.return_value = PaginatedResult( + results=channels, count=len(channels), next=None, previous=None + ) + return client + + def test_a_raw_id_resolves_as_today(self) -> None: + client: MagicMock = self._client( + "organization_legacy_200", [{"external_id": "C0", "name": "general", "type": "channel"}] + ) + assert resolve_channel(client, "C0") == { + "external_id": "C0", + "name": "general", + "type": "channel", + } + client.get_organization.assert_not_called() + + def test_a_qualified_id_keeps_its_qualifier(self) -> None: + client: MagicMock = self._client( + "organization_chat_platforms_no_plan_200", + [{"external_id": "C0", "name": "general", "type": "channel"}], + ) + assert resolve_channel(client, "slack:C0") == { + "external_id": "slack:C0", + "name": "general", + "type": "channel", + } + + def test_a_qualified_id_the_list_does_not_show_goes_to_the_server(self) -> None: + client: MagicMock = self._client("organization_chat_platforms_no_plan_200", []) + resolved: dict[str, str] = resolve_channel(client, f"{PLATFORM_ID}:C9") + assert resolved["external_id"] == f"{PLATFORM_ID}:C9" + + def test_a_qualified_id_without_platforms_is_refused(self) -> None: + client: MagicMock = self._client("organization_legacy_200", []) + with pytest.raises(click.UsageError): + resolve_channel(client, "slack:C0") From a92045bc49ec0822907ba81894ec878d2beaa950 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 14:39:42 +0000 Subject: [PATCH 17/19] docs: describe browser sign-in, standalone orgs and qualified channels ## Summary Reconcile the contributor and product docs with the branch: AGENTS.md structure and test map, ARCHITECTURE (login and refresh paths, stored keys), ECOSYSTEM_CONTEXT (the device-flow doors), PRODUCT_SPEC (sign-in methods) and the README logout row. ## Risks - None: docs only. CHANGELOG.md and the version stay with semantic-release Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 16 ++++++++++++++-- README.md | 2 +- docs/ARCHITECTURE.md | 4 ++-- docs/ECOSYSTEM_CONTEXT.md | 4 ++-- docs/PRODUCT_SPEC.md | 2 +- 5 files changed, 20 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d9ba5c78..f922a57f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ **Dailybot CLI** is a Python command-line tool that bridges **humans** and **agents** with the [Dailybot](https://www.dailybot.com) platform. It provides: -- **For humans** — email-OTP login, **managing Tasks** (`tasks` for the workspace, `task` for one task, plus `board` / `project` / `goal`), viewing pending check-ins, submitting structured/free-text updates, **filling out forms** (one-shot or driven through a workflow state machine: `pre_release → qa → code_review → ready_to_release → released`), **browsing teams** (role-scoped server-side), **giving kudos to users or whole teams**, interactive TUI mode. +- **For humans** — email-OTP or browser (device-flow) login, **managing Tasks** (`tasks` for the workspace, `task` for one task, plus `board` / `project` / `goal`), viewing pending check-ins, submitting structured/free-text updates, **filling out forms** (one-shot or driven through a workflow state machine: `pre_release → qa → code_review → ready_to_release → released`), **browsing teams** (role-scoped server-side), **giving kudos to users or whole teams**, interactive TUI mode. - **For agents (AI assistants, CI jobs, deploy scripts, bots)** — progress reports, milestone tracking, agent health, webhook registration, agent-to-agent messaging, transactional email, standalone agent registration (creates an org without a human Dailybot account), **and the full forms-response lifecycle** (`get / responses / response get / update / transition / delete`) so an agent can drive any form — including workflow-enabled ones — end-to-end after `dailybot login`. It talks exclusively to the Dailybot HTTP API under `/v1/cli/*`, `/v1/agent*/*`, `/v1/forms/*`, `/v1/plan/*`, `/v1/teams/*`, `/v1/kudos/`, `/v1/users/`, and `/v1/checkins/*` endpoints. There is no local database; all state is either in `~/.config/dailybot/` (credentials, agent profiles, config) or fetched from the API. @@ -55,7 +55,8 @@ dailybot_cli/ # Source package ├── ledger.py # Local report ledger (per-repo work signals) for `hook` └── commands/ ├── __init__.py - ├── auth.py # login / logout (email OTP, multi-org) + ├── auth.py # login / logout (email OTP, multi-org; --device browser sign-in) + ├── _device_login.py # RFC 8628 browser sign-in: start, poll, save the token pair ├── status.py # pending check-ins + --auth status ├── update.py # submit human check-in update ├── config.py # get/set/remove stored settings (api_key) @@ -158,6 +159,17 @@ tests/ # pytest suite (file naming: *_test.py) ├── tasks_agent_attribution_test.py # --agent-name stamp: body vs header, encoding, refusal, rendering ├── task_brief_test.py # task brief: embeds, dedicated-door fallback, safe downloads ├── token_host_binding_test.py # a login token only travels to the host that issued it +├── wire_fixtures_test.py # recorded device-flow / standalone wire fixtures (tests/fixtures/device_flow/) +├── device_login_test.py # `login --device`: poll, slow_down, denial, expiry, 404/405 fallback +├── credentials_refresh_test.py # refresh only on 401 access_token_expired; two-process re-read +├── logout_pair_test.py # logout revokes the pair (Bearer or refresh-body form) +├── auth_backend_unavailable_test.py # 503 auth_backend_unavailable: bounded retry, never a logout +├── standalone_org_login_test.py # standalone Dailybot orgs in the login picker +├── effective_tier_test.py # cached plan tier refreshed from /v1/organization/ +├── org_channels_test.py # `dailybot org` chat platforms (ChatPlatformSummary) +├── cli_auth_deprecation_test.py # the cli_auth_deprecated notice on email-code sign-in +├── standalone_error_codes_test.py # session, sign-in and chat-platform error codes +├── qualified_channels_test.py # slack: / : channel references ├── tasks_server_refusal_rendering_test.py # server refusals of agent keys / guests: exit + envelope ├── milestones_updates_test.py # milestone attachments/restore; project update get/edit/delete/attachments ├── tasks_reactions_test.py # reactions: who reacted, project-update react/unreact, full reactor lists diff --git a/README.md b/README.md index 99a097c6..47738a19 100644 --- a/README.md +++ b/README.md @@ -846,7 +846,7 @@ Replies to agent emails land as messages retrievable via `dailybot agent message | Command | Description | |---------|-------------| | `dailybot login` | Authenticate with email OTP, or in the browser with `--device` | -| `dailybot logout` | Log out and revoke token | +| `dailybot logout` | Log out and revoke the session (both tokens of a browser sign-in) | | `dailybot status` | Show pending check-ins and auth status | | `dailybot me` | Show the authenticated user and org context (`--include-email`, `--json`) | | `dailybot org` | Show the organization the credential is scoped to, and its chat platforms when the server provides them (`--json`) | diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2257bf34..59300781 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -67,7 +67,7 @@ The single HTTP boundary. Owns: ### `dailybot_cli/config.py` The on-disk credential and configuration store. Owns: -- `~/.config/dailybot/credentials.json` — login session (token, email, organization, organization_uuid, api_url) +- `~/.config/dailybot/credentials.json` — login session (token, email, organization, organization_uuid, api_url; a browser sign-in adds auth_method, refresh, expires_at, refresh_expires_at) - `~/.config/dailybot/config.json` — stored settings (currently just `api_key`) - `~/.config/dailybot/agents.json` — named agent profiles + default-profile pointer - `~/.config/dailybot/org_cache.json` — temporary cache of the org list during multi-org non-interactive login @@ -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. +- **`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`). - **`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). diff --git a/docs/ECOSYSTEM_CONTEXT.md b/docs/ECOSYSTEM_CONTEXT.md index df700e49..bc569a47 100644 --- a/docs/ECOSYSTEM_CONTEXT.md +++ b/docs/ECOSYSTEM_CONTEXT.md @@ -60,7 +60,7 @@ The Dailybot API exposes three distinct endpoint families that the CLI consumes: ### CLI-personal endpoints — `/v1/cli/status/`, `/v1/cli/updates/` - Authenticate with **either** a Bearer token (`Authorization: Bearer `) **or** an org API key (`X-API-KEY`). -- The Bearer token is issued by the email-OTP flow (`/v1/cli/auth/{request-code,verify-code}`); the API key resolves to its owning user server-side, so scope is identical. +- The Bearer token is issued by the email-OTP flow (`/v1/cli/auth/{request-code,verify-code}`) or by the browser sign-in (`/v1/cli/auth/device/` + `/device/token/`, an access/refresh pair rotated through `/v1/cli/auth/refresh/`); the API key resolves to its owning user server-side, so scope is identical. - Scope: a single user within a single organization. The CLI's `_headers(authenticated=True)` builds these. Used by `status`, `update`. The auth-lifecycle endpoints (`/v1/cli/auth/*`, used by `login` / `logout`) remain Bearer/OTP only. @@ -101,7 +101,7 @@ The CLI itself doesn't receive webhooks. `dailybot agent webhook register --url ### "I should add Slack OAuth to the CLI" -No. Chat-platform OAuth is owned by the Dailybot API. The CLI only ever authenticates against `/v1/cli/auth/...` (email OTP) or carries a pre-existing API key. +No. Chat-platform OAuth is owned by the Dailybot API. The CLI only ever authenticates against `/v1/cli/auth/...` (email OTP, or the browser device-flow sign-in, where the approval happens on a Dailybot web page) or carries a pre-existing API key. ### "The CLI should cache follow-ups locally for offline mode" diff --git a/docs/PRODUCT_SPEC.md b/docs/PRODUCT_SPEC.md index fd0a59a2..9f1d4852 100644 --- a/docs/PRODUCT_SPEC.md +++ b/docs/PRODUCT_SPEC.md @@ -85,7 +85,7 @@ The CLI supports four credential sources, resolved in this order for **agent com 4. Stored API key (`dailybot config key=...`) 5. Login session Bearer token (`dailybot login`) -Every authenticated command — `status`, `update`, `checkin`, `form`, `kudos`, `team`, `user`, `chat`, and the `agent` group — works with **either** the login session Bearer token **or** an org API key. The server resolves the acting user from the API key's owner, so the two credentials are behaviorally identical. The user-scoped commands call `require_auth()` (and `status` / `update` their own equivalent check), which resolves via `get_agent_auth()` and exits non-zero only when neither credential is present. Only `dailybot logout` and the OTP login flow are inherently tied to a Bearer session. +Every authenticated command — `status`, `update`, `checkin`, `form`, `kudos`, `team`, `user`, `chat`, and the `agent` group — works with **either** the login session Bearer token **or** an org API key. The server resolves the acting user from the API key's owner, so the two credentials are behaviorally identical. The user-scoped commands call `require_auth()` (and `status` / `update` their own equivalent check), which resolves via `get_agent_auth()` and exits non-zero only when neither credential is present. Only `dailybot logout` and the login flows are inherently tied to a Bearer session. `dailybot login` signs in with an email code, or through the browser with `--device` (an RFC 8628 device flow: the CLI prints a link and a short code, the user approves it on a Dailybot page, and the CLI receives an access token that renews itself with a refresh token). Standalone Dailybot organizations sign in the same way and are marked "(Dailybot)" in the organization picker. For **standalone agent registration**, no authentication is required — agents complete a math challenge to prove they're not bots. From f2c0f20dc85a1dca36b0c121d698552fc89f75c0 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 16:05:56 +0000 Subject: [PATCH 18/19] fix(auth): address AI review round 1 on the browser sign-in ## Summary Five findings from the PR 145 review, each with a test. ## Change Log - _refresh_session rejects an empty access or refresh, like login's _save_pair, and returns False when update_token_pair cannot persist the pair (no replay with an in-memory-only session) - expires_at / refresh_expires_at are stored only as non-empty strings, else None (config.text_or_none in save_credentials, update_token_pair, _device_login and _refresh_session) - resolve_channel refuses `dailybot:` with the same message as chat send - interactive.py signs in through the same branch as `dailybot login` (browser flow when DEVICE_LOGIN_IS_DEFAULT is on, email code otherwise); the default stays False ## Risks - None: stricter validation and one shared login entry point Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 18 ++++-- dailybot_cli/commands/_channels.py | 14 +++-- dailybot_cli/commands/_device_login.py | 6 +- dailybot_cli/commands/interactive.py | 26 ++++++-- dailybot_cli/config.py | 25 +++++--- tests/config_test.py | 30 +++++++++ tests/credentials_refresh_test.py | 47 ++++++++++++++ tests/device_login_test.py | 85 ++++++++++++++++++++++++++ tests/qualified_channels_test.py | 11 ++++ 9 files changed, 237 insertions(+), 25 deletions(-) diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 20b51d10..5567e9bc 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -24,6 +24,7 @@ get_api_url, get_login_token_for, get_refresh_token_for, + text_or_none, update_token_pair, ) from dailybot_cli.install_method import detect_install_method @@ -813,16 +814,21 @@ def _refresh_session(self) -> bool: finally: # The refresh door is unauthenticated; the replay is a Bearer request again. self._agent_auth_mode = "bearer" - access: Any = pair.get("access") - new_refresh: Any = pair.get("refresh") - if not isinstance(access, str) or not access or not isinstance(new_refresh, str): + # Same bar as login's `_save_pair`: an empty token never replaces a working one. + access: str | None = text_or_none(pair.get("access")) + new_refresh: str | None = text_or_none(pair.get("refresh")) + if access is None or new_refresh is None: return False - update_token_pair( + persisted: bool = update_token_pair( access=access, refresh=new_refresh, - expires_at=pair.get("expires_at"), - refresh_expires_at=pair.get("refresh_expires_at"), + expires_at=text_or_none(pair.get("expires_at")), + refresh_expires_at=text_or_none(pair.get("refresh_expires_at")), ) + if not persisted: + # The session file vanished mid-refresh (a logout elsewhere): do not keep + # using a pair that exists only in this process. + return False self.token = access return True diff --git a/dailybot_cli/commands/_channels.py b/dailybot_cli/commands/_channels.py index 80ec3e3d..cedc6572 100644 --- a/dailybot_cli/commands/_channels.py +++ b/dailybot_cli/commands/_channels.py @@ -85,6 +85,13 @@ def _qualified_refused(reference: ChannelReference) -> click.UsageError: ) +def _dailybot_refused() -> click.UsageError: + return click.UsageError( + "`dailybot:` is not a chat send destination: messages are never delivered to " + "Dailybot Chat. Target a channel on a connected chat platform (see `dailybot org`)." + ) + + def check_chat_channel_references(client: Any, payload: dict[str, Any]) -> None: """Validate the `target_channels` of a chat send payload against the grammar. @@ -103,10 +110,7 @@ def check_chat_channel_references(client: Any, payload: dict[str, Any]) -> None: references.append(parse_channel_reference(raw)) for reference in references: if reference.kind == "dailybot": - raise click.UsageError( - "`dailybot:` is not a chat send destination: messages are never delivered to " - "Dailybot Chat. Target a channel on a connected chat platform (see `dailybot org`)." - ) + raise _dailybot_refused() qualified: list[ChannelReference] = [r for r in references if r.is_qualified] if qualified and _org_serves_chat_platforms(client) is False: raise _qualified_refused(qualified[0]) @@ -125,6 +129,8 @@ def resolve_channel(client: Any, reference: str, *, public_only: bool = False) - wanted: str = reference.strip() channel_type: str | None = PUBLIC_CHANNEL_TYPE if public_only else None parsed: ChannelReference = parse_channel_reference(wanted) + if parsed.kind == "dailybot": + raise _dailybot_refused() if parsed.is_qualified: return _resolve_qualified(client, parsed, channel_type) diff --git a/dailybot_cli/commands/_device_login.py b/dailybot_cli/commands/_device_login.py index 1f3d8e4b..069e7398 100644 --- a/dailybot_cli/commands/_device_login.py +++ b/dailybot_cli/commands/_device_login.py @@ -10,7 +10,7 @@ from typing import Any from dailybot_cli.api_client import APIError, DailyBotClient, TransportError -from dailybot_cli.config import save_credentials, save_org_plan +from dailybot_cli.config import save_credentials, save_org_plan, text_or_none from dailybot_cli.display import ( console, print_device_login_instructions, @@ -127,8 +127,8 @@ def _save_pair(client: DailyBotClient, token: dict[str, Any]) -> tuple[str, str] organization_uuid=org_uuid, api_url=client.api_url, refresh=refresh, - expires_at=token.get("expires_at"), - refresh_expires_at=token.get("refresh_expires_at"), + expires_at=text_or_none(token.get("expires_at")), + refresh_expires_at=text_or_none(token.get("refresh_expires_at")), ) plan: Any = org.get("plan") tier: Any = None diff --git a/dailybot_cli/commands/interactive.py b/dailybot_cli/commands/interactive.py index 354ed924..4b56ca8a 100644 --- a/dailybot_cli/commands/interactive.py +++ b/dailybot_cli/commands/interactive.py @@ -11,6 +11,7 @@ from dailybot_cli import __version__ from dailybot_cli.api_client import APIError, DailyBotClient, resource_uuid +from dailybot_cli.commands import _device_login from dailybot_cli.commands.auth import _do_login from dailybot_cli.commands.chat import ChatPayloadError, build_chat_payload from dailybot_cli.commands.kudos import execute_kudos_give @@ -95,6 +96,25 @@ } +def _login_interactively() -> None: + """Sign in the way a bare `dailybot login` does (`DEVICE_LOGIN_IS_DEFAULT`). + + With the browser flow as the default it starts there and falls back to the + email code on a server that does not offer it; otherwise it asks for the email. + """ + if _device_login.DEVICE_LOGIN_IS_DEFAULT: + try: + _device_login.device_login(DailyBotClient()) + return + except _device_login.DeviceFlowUnsupported: + print_info( + "This Dailybot server does not offer browser sign-in yet. " + "Continuing with an email code." + ) + email: str = click.prompt("Email") + _do_login(email) + + def _checkin_label(checkin: dict[str, Any]) -> str: name: str = str(checkin.get("followup_name") or "Check-in") question_count: int = len(checkin.get("template_questions", [])) @@ -172,9 +192,8 @@ def run_interactive() -> None: console.print() print_info("Let's get you logged in.") console.print() - email: str = click.prompt("Email") try: - _do_login(email) + _login_interactively() except SystemExit: print_error("Login failed.") return @@ -206,9 +225,8 @@ def run_interactive() -> None: "Run: dailybot login" ) console.print() - email = click.prompt("Email") try: - _do_login(email) + _login_interactively() except SystemExit: print_error("Login failed.") return diff --git a/dailybot_cli/config.py b/dailybot_cli/config.py index 1f2b33b7..82acd568 100644 --- a/dailybot_cli/config.py +++ b/dailybot_cli/config.py @@ -120,6 +120,15 @@ def load_credentials() -> dict[str, Any] | None: return None +def text_or_none(value: Any) -> str | None: + """A non-empty string as is; anything else (a number, an object, "") as ``None``. + + Server-sent expiries are stored only in the shape their readers expect, so + :func:`is_access_token_expired` never meets a number or an object. + """ + return value if isinstance(value, str) and value else None + + AUTH_METHOD_DEVICE: str = "device" """``credentials.json::auth_method`` for a device-flow session (access + refresh pair). @@ -137,8 +146,8 @@ def save_credentials( api_url: str = DEFAULT_API_URL, *, refresh: str | None = None, - expires_at: str | None = None, - refresh_expires_at: str | None = None, + expires_at: Any = None, + refresh_expires_at: Any = None, ) -> None: """Save credentials to disk. @@ -159,8 +168,8 @@ def save_credentials( { "auth_method": AUTH_METHOD_DEVICE, "refresh": refresh, - "expires_at": expires_at, - "refresh_expires_at": refresh_expires_at, + "expires_at": text_or_none(expires_at), + "refresh_expires_at": text_or_none(refresh_expires_at), } ) _write_secret_file(creds_path, json.dumps(data, indent=2)) @@ -169,8 +178,8 @@ def save_credentials( def update_token_pair( access: str, refresh: str, - expires_at: str | None, - refresh_expires_at: str | None = None, + expires_at: Any, + refresh_expires_at: Any = None, ) -> bool: """Replace the stored access/refresh pair after a rotation, keeping every other key. @@ -184,8 +193,8 @@ def update_token_pair( "token": access, "auth_method": AUTH_METHOD_DEVICE, "refresh": refresh, - "expires_at": expires_at, - "refresh_expires_at": refresh_expires_at, + "expires_at": text_or_none(expires_at), + "refresh_expires_at": text_or_none(refresh_expires_at), } ) # Atomic: a concurrent CLI process reads either the old pair or the new one, diff --git a/tests/config_test.py b/tests/config_test.py index 0dcd75e7..d5b672ea 100644 --- a/tests/config_test.py +++ b/tests/config_test.py @@ -426,3 +426,33 @@ def spy(src: Any, dst: Any) -> None: assert sorted(p.name for p in tmp_config.iterdir() if p.name.startswith("credentials")) == [ "credentials.json" ] + + +@pytest.mark.parametrize("bad", [123, 1.5, {"at": "x"}, ["x"], "", True]) +def test_expiry_fields_are_stored_only_as_non_empty_strings(tmp_config: Path, bad: Any) -> None: + """AI review fp=f2766c72 / fp=dbaf3967: never a number or object in credentials.json.""" + from dailybot_cli.config import update_token_pair + + save_credentials( + token="dbc_at_a", + email="e", + organization="o", + organization_uuid="u", + refresh="dbc_rt_a", + expires_at=bad, + refresh_expires_at=bad, + ) + raw: dict[str, Any] = json.loads((tmp_config / "credentials.json").read_text()) + assert raw["expires_at"] is None and raw["refresh_expires_at"] is None + update_token_pair(access="dbc_at_b", refresh="dbc_rt_b", expires_at=bad, refresh_expires_at=bad) + raw = json.loads((tmp_config / "credentials.json").read_text()) + assert raw["expires_at"] is None and raw["refresh_expires_at"] is None + update_token_pair( + access="dbc_at_c", + refresh="dbc_rt_c", + expires_at="2030-01-01T00:00:00Z", + refresh_expires_at="2030-04-01T00:00:00Z", + ) + raw = json.loads((tmp_config / "credentials.json").read_text()) + assert raw["expires_at"] == "2030-01-01T00:00:00Z" + assert raw["refresh_expires_at"] == "2030-04-01T00:00:00Z" diff --git a/tests/credentials_refresh_test.py b/tests/credentials_refresh_test.py index 43d8a620..c2e9de35 100644 --- a/tests/credentials_refresh_test.py +++ b/tests/credentials_refresh_test.py @@ -347,3 +347,50 @@ def test_tokens_never_reach_an_error_message() -> None: for secret in (OLD_ACCESS, OLD_REFRESH): assert secret not in str(caught.value) assert secret not in caught.value.detail + + +class TestReviewFixes: + """AI review round 1 on PR 145 (fp=077b35cf, fp=402bf40b).""" + + @pytest.mark.parametrize("field", ["access", "refresh"]) + def test_an_empty_token_in_the_refresh_answer_is_rejected( + self, field: str, _isolated_environment: Path + ) -> None: + _save_pair() + broken: MagicMock = fixture_response("refresh_success_200") + body: dict[str, Any] = dict(broken.json.return_value) + body[field] = "" + broken.json.return_value = body + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ) as get, + patch("dailybot_cli.api_client.httpx.post", return_value=broken), + pytest.raises(APIError), + ): + client.get_status() + assert get.call_count == 1 # no replay with a broken pair + creds: dict[str, Any] | None = load_credentials() + assert creds is not None + assert creds["token"] == OLD_ACCESS and creds["refresh"] == OLD_REFRESH + + def test_a_pair_that_cannot_be_persisted_is_not_used(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API) + with ( + patch( + "dailybot_cli.api_client.httpx.get", + return_value=fixture_response("bearer_access_token_expired_401"), + ) as get, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ), + patch("dailybot_cli.api_client.update_token_pair", return_value=False), + pytest.raises(APIError), + ): + client.get_status() + assert get.call_count == 1 + assert client.token == OLD_ACCESS diff --git a/tests/device_login_test.py b/tests/device_login_test.py index 44e11788..c570515c 100644 --- a/tests/device_login_test.py +++ b/tests/device_login_test.py @@ -307,3 +307,88 @@ def test_a_legacy_login_still_writes_exactly_the_legacy_keys( assert result.exit_code == 0, result.output raw: dict[str, Any] = json.loads(_credentials_file(_isolated_environment).read_text()) assert set(raw) == {"token", "email", "organization", "organization_uuid", "api_url"} + + +@pytest.mark.parametrize("bad", [123, {"at": "x"}, ""]) +def test_device_login_stores_expiries_only_as_strings( + runner: CliRunner, sleeps: MagicMock, bad: Any, _isolated_environment: Path +) -> None: + token: MagicMock = fixture_response("device_token_success_200") + body: dict[str, Any] = dict(token.json.return_value) + body["expires_at"] = bad + body["refresh_expires_at"] = bad + token.json.return_value = body + with patch(POST, side_effect=[fixture_response("device_start_200"), token]): + result: Result = _login(runner) + assert result.exit_code == 0, result.output + raw: dict[str, Any] = json.loads(_credentials_file(_isolated_environment).read_text()) + assert raw["expires_at"] is None and raw["refresh_expires_at"] is None + + +class TestInteractiveFollowsTheDefault: + """AI review fp=ef8269f2: the TUI login takes the same branch as `dailybot login`.""" + + @patch("dailybot_cli.commands.interactive.questionary") + @patch("dailybot_cli.commands.interactive._do_login") + @patch("dailybot_cli.commands.interactive.load_credentials") + @patch("dailybot_cli.commands.interactive.get_token", return_value=None) + def test_off_prompts_for_the_email_code( + self, + _token: MagicMock, + load_creds: MagicMock, + do_login: MagicMock, + tui: MagicMock, + runner: CliRunner, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr(_device_login, "DEVICE_LOGIN_IS_DEFAULT", False) + load_creds.side_effect = [None, {"token": "t", "email": "e", "organization": "o"}] + tui.select.return_value.ask.return_value = "exit" + with patch("dailybot_cli.commands.interactive._device_login.device_login") as device: + runner.invoke(cli, [], input="me@example.com\n") + do_login.assert_called_once_with("me@example.com") + device.assert_not_called() + + @patch("dailybot_cli.commands.interactive.questionary") + @patch("dailybot_cli.commands.interactive._do_login") + @patch("dailybot_cli.commands.interactive.load_credentials") + @patch("dailybot_cli.commands.interactive.get_token", return_value=None) + def test_on_starts_the_browser_sign_in( + self, + _token: MagicMock, + load_creds: MagicMock, + do_login: MagicMock, + tui: MagicMock, + runner: CliRunner, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr(_device_login, "DEVICE_LOGIN_IS_DEFAULT", True) + load_creds.side_effect = [None, {"token": "t", "email": "e", "organization": "o"}] + tui.select.return_value.ask.return_value = "exit" + with patch("dailybot_cli.commands.interactive._device_login.device_login") as device: + runner.invoke(cli, []) + device.assert_called_once() + do_login.assert_not_called() + + @patch("dailybot_cli.commands.interactive.questionary") + @patch("dailybot_cli.commands.interactive._do_login") + @patch("dailybot_cli.commands.interactive.load_credentials") + @patch("dailybot_cli.commands.interactive.get_token", return_value=None) + def test_on_falls_back_to_the_email_code_on_an_older_server( + self, + _token: MagicMock, + load_creds: MagicMock, + do_login: MagicMock, + tui: MagicMock, + runner: CliRunner, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + monkeypatch.setattr(_device_login, "DEVICE_LOGIN_IS_DEFAULT", True) + load_creds.side_effect = [None, {"token": "t", "email": "e", "organization": "o"}] + tui.select.return_value.ask.return_value = "exit" + with patch( + "dailybot_cli.commands.interactive._device_login.device_login", + side_effect=_device_login.DeviceFlowUnsupported, + ): + runner.invoke(cli, [], input="me@example.com\n") + do_login.assert_called_once_with("me@example.com") diff --git a/tests/qualified_channels_test.py b/tests/qualified_channels_test.py index 16e0b3f8..38cbe4a0 100644 --- a/tests/qualified_channels_test.py +++ b/tests/qualified_channels_test.py @@ -216,3 +216,14 @@ def test_a_qualified_id_without_platforms_is_refused(self) -> None: client: MagicMock = self._client("organization_legacy_200", []) with pytest.raises(click.UsageError): resolve_channel(client, "slack:C0") + + +def test_resolve_channel_refuses_dailybot_like_chat_send() -> None: + """AI review fp=d08a1001: routes, reports and notifications refuse `dailybot:` too.""" + client: MagicMock = _org_client("organization_native_200") + with pytest.raises(click.UsageError) as from_resolver: + resolve_channel(client, "dailybot:C1") + with pytest.raises(click.UsageError) as from_chat: + check_chat_channel_references(client, {"target_channels": ["dailybot:C1"]}) + assert from_resolver.value.message == from_chat.value.message + client.search_channels.assert_not_called() From 2524a699088ed3e864f8ad95b2965909c02961cf Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Fri, 13 Nov 2026 16:11:59 +0000 Subject: [PATCH 19/19] fix(client): refresh an expired browser session reached as the fallback credential ## Summary AI review round 1 also flagged (unthreaded, api_client.py:680 and :764) that when a repo key preferred on the login's own host is refused and the client falls back to the Bearer session, an expired access token was never refreshed. Both request paths now refresh once after the fallback too, and replay with the Bearer alone (the refused key is not resent). Never more than one refresh per request. ## Change Log - _request / _agent_request: refresh_tried guard, post-fallback refresh - _bearer_headers, _replay_headers helpers - tests: user path, agent path, single-refresh guard ## Risks - Rule 14 order unchanged: the repo key still goes first; the Bearer stays host-bound Co-Authored-By: Claude Opus 5.5 --- dailybot_cli/api_client.py | 52 ++++++++++++++++---- tests/credentials_refresh_test.py | 80 +++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 8 deletions(-) diff --git a/dailybot_cli/api_client.py b/dailybot_cli/api_client.py index 5567e9bc..535a1860 100644 --- a/dailybot_cli/api_client.py +++ b/dailybot_cli/api_client.py @@ -666,7 +666,11 @@ def _agent_request( lambda: httpx.request(method, url, **kwargs), method=method ) - if self._needs_refresh(response) and self._refresh_session(): + # At most one refresh per request: before the alternate credential when the + # Bearer went first, or after it when the Bearer was the fallback (a repo key + # preferred on the login's own host was refused). + refresh_tried: bool = self._needs_refresh(response) + if refresh_tried and self._refresh_session(): kwargs["headers"] = self._agent_headers() response = self._guard_transport( lambda: httpx.request(method, url, **kwargs), method=method @@ -680,6 +684,12 @@ def _agent_request( lambda: httpx.request(method, url, **kwargs), method=method ) + if not refresh_tried and self._needs_refresh(response) and self._refresh_session(): + kwargs["headers"] = self._bearer_headers() + response = self._guard_transport( + lambda: httpx.request(method, url, **kwargs), method=method + ) + return response def _request( @@ -742,13 +752,10 @@ def _request( response: httpx.Response = self._dispatch_guarded(method, url, **kwargs) - if self._needs_refresh(response) and self._refresh_session(): - replay_headers: dict[str, str] = self._headers() - if files is not None or content is not None: - replay_headers.pop("Content-Type", None) - if extra_headers: - replay_headers.update(extra_headers) - kwargs["headers"] = replay_headers + # At most one refresh per request (see `_agent_request`). + refresh_tried: bool = self._needs_refresh(response) + if refresh_tried and self._refresh_session(): + kwargs["headers"] = self._replay_headers(self._headers(), files, content, extra_headers) response = self._dispatch_guarded(method, url, **kwargs) if _is_auth_retryable(response) and not self._is_final_person_refusal(url, response): @@ -764,8 +771,37 @@ def _request( kwargs["headers"] = retry_headers response = self._dispatch_guarded(method, url, **kwargs) + if not refresh_tried and self._needs_refresh(response) and self._refresh_session(): + kwargs["headers"] = self._replay_headers( + self._bearer_headers(), files, content, extra_headers + ) + response = self._dispatch_guarded(method, url, **kwargs) + return response + @staticmethod + def _replay_headers( + headers: dict[str, str], + files: dict[str, Any] | None, + content: bytes | None, + extra_headers: dict[str, str] | None, + ) -> dict[str, str]: + """Headers for a replay, with the same body rules as the first attempt.""" + replay: dict[str, str] = dict(headers) + if files is not None or content is not None: + replay.pop("Content-Type", None) + if extra_headers: + replay.update(extra_headers) + return replay + + def _bearer_headers(self) -> dict[str, str]: + """The login session's Bearer alone: the replay after a refresh that followed a + fallback to the session, so the refused repo key is not sent again.""" + headers: dict[str, str] = _base_headers() + headers["Authorization"] = f"Bearer {self.token}" + self._agent_auth_mode = "bearer" + return headers + def _needs_refresh(self, response: httpx.Response) -> bool: """A Bearer request refused with ``401 access_token_expired`` (and nothing else).""" return ( diff --git a/tests/credentials_refresh_test.py b/tests/credentials_refresh_test.py index c2e9de35..c74af251 100644 --- a/tests/credentials_refresh_test.py +++ b/tests/credentials_refresh_test.py @@ -394,3 +394,83 @@ def test_a_pair_that_cannot_be_persisted_is_not_used(self) -> None: client.get_status() assert get.call_count == 1 assert client.token == OLD_ACCESS + + +class TestRefreshAfterTheAlternateCredential: + """AI review round 1 (unthreaded warnings at api_client.py:680 and :764). + + A repo key preferred on the login's own host is refused, the client falls back to + the Bearer session, and that access token has expired: the pair refreshes once and + the request is replayed with the new Bearer. + """ + + @staticmethod + def _client() -> DailyBotClient: + _save_pair() + return DailyBotClient(api_url=API, api_key="test-key", prefer_api_key=True) + + def test_the_user_path(self) -> None: + client: DailyBotClient = self._client() + with ( + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[ + _plain(401, {"detail": "Invalid key."}), + fixture_response("bearer_access_token_expired_401"), + _ok(), + ], + ) as get, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ) as post, + ): + assert client.get_status() == {"ok": True} + assert post.call_count == 1 + sent: list[dict[str, str]] = [c.kwargs["headers"] for c in get.call_args_list] + assert sent[0].get("X-API-KEY") == "test-key" + assert sent[1].get("Authorization") == f"Bearer {OLD_ACCESS}" + assert sent[2].get("Authorization") == f"Bearer {NEW['access']}" + assert "X-API-KEY" not in sent[2] + + def test_the_agent_path(self) -> None: + client: DailyBotClient = self._client() + with ( + patch( + "dailybot_cli.api_client.httpx.request", + side_effect=[ + _plain(401, {"detail": "Invalid key."}), + fixture_response("bearer_access_token_expired_401"), + _ok(), + ], + ) as request, + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ), + ): + client.get_agent_health(agent_name="a") + replay: dict[str, str] = request.call_args_list[2].kwargs["headers"] + assert replay.get("Authorization") == f"Bearer {NEW['access']}" + assert "X-API-KEY" not in replay + + def test_never_more_than_one_refresh_per_request(self) -> None: + _save_pair() + client: DailyBotClient = DailyBotClient(api_url=API, api_key="test-key") + with ( + patch( + "dailybot_cli.api_client.httpx.get", + side_effect=[ + fixture_response("bearer_access_token_expired_401"), + fixture_response("bearer_access_token_expired_401"), + _plain(401, {"detail": "Invalid key."}), + ], + ), + patch( + "dailybot_cli.api_client.httpx.post", + return_value=fixture_response("refresh_success_200"), + ) as post, + pytest.raises(APIError), + ): + client.get_status() + assert post.call_count == 1