Skip to content

Python CLI API-key login overwrites saved credentials after transport failure #13191

Closed

Description

@looternikhil-cpu

API-key login can replace an existing saved credential after a connection failure. On f42089f53c8010dd971b3702ece05a231c9c0c66, OmiClient wraps exhausted transport failures as ServerError, and _do_api_key_login catches that as CliError and continues to persist the candidate. This contradicts the documented transport-failure behavior and the existing test_transport_failure_during_login_leaves_saved_config_unchanged regression.

The proposed patch distinguishes transport errors with a ServerError subclass, so login can abort before saving. HTTP 503 retains its existing warn-and-store behavior. Expanded tests exercise the real main() entry point for connection failures and timeouts in plain/JSON modes, checking exit 3, no success output, and byte-identical saved configuration. Four candidate regression cases failed before the fix; all 19 auth tests and the full CLI suite now pass: 279 passed, 1 skipped on Python 3.12. Black, diff checks, and independent code review passed. The repository-wide preflight remains blocked by missing registry-referenced files in the sparse checkout, so this is a reviewable proposed patch, not a merge-ready PR.

@josancamon19, would you approve US$15 for this fix after acceptance and merge, under the contribution guide's bounty-proposal process? This is a request for funding, not an approved bounty or payment claim. Prepared with Codex; all HTTP tests use synthetic credentials and mocked responses.

Complete proposed patch
diff --git a/sdks/python-cli/README.md b/sdks/python-cli/README.md
index bbbff7f..7d65c8d 100644
--- a/sdks/python-cli/README.md
+++ b/sdks/python-cli/README.md
@@ -92,8 +92,9 @@ omi auth logout                 # wipe the credential
 An API-key login candidate is checked before replacing the saved credentials.
 If verification rejects it with HTTP 401 or 403, the existing profile and active
 profile selection remain unchanged. Other HTTP errors retain the existing
-store-and-warn behavior. A transport failure leaves saved credentials unchanged;
-browser OAuth is a separate flow.
+store-and-warn behavior. A transport failure leaves saved credentials unchanged
+and returns exit code `3`; retry login after restoring connectivity. Browser
+OAuth is a separate flow.
 
 You can also set `OMI_API_KEY` in the environment to bypass on-disk config
 entirely — handy in containers and CI:
diff --git a/sdks/python-cli/omi_cli/client.py b/sdks/python-cli/omi_cli/client.py
index fc34c54..9a06bfa 100644
--- a/sdks/python-cli/omi_cli/client.py
+++ b/sdks/python-cli/omi_cli/client.py
@@ -32,7 +32,7 @@ from tenacity import (
 
 from omi_cli import __version__
 from omi_cli.config import Profile
-from omi_cli.errors import CliError, RateLimitError, ServerError, from_status
+from omi_cli.errors import CliError, RateLimitError, ServerError, TransportError, from_status
 
 USER_AGENT = f"omi-cli/{__version__} (+https://github.com/BasedHardware/omi)"
 DEFAULT_TIMEOUT = httpx.Timeout(30.0, connect=10.0)
@@ -159,7 +159,7 @@ class OmiClient:
             # We exhausted retries — convert to the proper CliError now.
             raise self._error_from_response(exc.response)
         except httpx.TransportError as exc:
-            raise ServerError(
+            raise TransportError(
                 message="Connection failed",
                 detail="Unable to reach the Omi API. Check your network connection or try again shortly.",
             ) from exc
diff --git a/sdks/python-cli/omi_cli/commands/auth.py b/sdks/python-cli/omi_cli/commands/auth.py
index 6c31630..caaab07 100644
--- a/sdks/python-cli/omi_cli/commands/auth.py
+++ b/sdks/python-cli/omi_cli/commands/auth.py
@@ -12,7 +12,7 @@ from omi_cli.auth import api_key as api_key_auth
 from omi_cli.auth import oauth as oauth_auth
 from omi_cli.auth.store import clear_credentials
 from omi_cli.client import OmiClient
-from omi_cli.errors import AuthError, CliError, UsageError
+from omi_cli.errors import AuthError, CliError, TransportError, UsageError
 
 if TYPE_CHECKING:
     from omi_cli.main import AppContext
@@ -142,11 +142,12 @@ def _do_api_key_login(ctx: "AppContext", api_key: str) -> None:
     verification_warning = None
 
     # Sanity check on a tolerant endpoint — see the original launch PR's
-    # rationale. AuthError leaves disk unchanged; other CliError warns and keeps.
+    # rationale. Auth and transport failures leave disk unchanged; other
+    # HTTP errors preserve the existing warn-and-store policy.
     try:
         with OmiClient(profile, verbose=ctx.verbose) as client:
             client.get("/v1/dev/user/memories", params={"limit": 1})
-    except AuthError:
+    except (AuthError, TransportError):
         raise
     except CliError as exc:
         verification_warning = f"Could not verify the key right now ({exc.message}). It is stored — try again shortly."
diff --git a/sdks/python-cli/omi_cli/errors.py b/sdks/python-cli/omi_cli/errors.py
index 97f2244..2b457b5 100644
--- a/sdks/python-cli/omi_cli/errors.py
+++ b/sdks/python-cli/omi_cli/errors.py
@@ -91,6 +91,10 @@ class ServerError(CliError):
     exit_code = EXIT_SERVER
 
 
+class TransportError(ServerError):
+    """The request failed at the transport layer, without a usable HTTP response."""
+
+
 class NotFoundError(CliError):
     exit_code = EXIT_NOT_FOUND
 
diff --git a/sdks/python-cli/tests/test_auth_api_key.py b/sdks/python-cli/tests/test_auth_api_key.py
index a2bc9d7..d86eca8 100644
--- a/sdks/python-cli/tests/test_auth_api_key.py
+++ b/sdks/python-cli/tests/test_auth_api_key.py
@@ -142,15 +142,27 @@ def test_api_key_login_keeps_existing_http_server_error_policy(
     assert json.loads(result.stdout)["auth_method"] == "api_key"
 
 
+@pytest.mark.parametrize("json_mode", [False, True])
+@pytest.mark.parametrize("error_name", ["ConnectError", "ReadTimeout"])
 def test_transport_failure_during_login_leaves_saved_config_unchanged(
-    config_path, authed_profile, respx_mock, cli_runner, monkeypatch
+    config_path, authed_profile, respx_mock, capsys, monkeypatch, json_mode, error_name
 ) -> None:
     import httpx
+    from omi_cli.main import main
 
     monkeypatch.setattr("omi_cli.client.MAX_RETRY_ATTEMPTS", 1)
     before = config_path.read_bytes()
-    route = respx_mock.get("/v1/dev/user/memories").mock(side_effect=httpx.ConnectError("Connection unavailable"))
-    result = cli_runner.invoke(app, ["auth", "login", "--api-key", "omi_dev_" + "n" * 32])
-    assert result.exit_code != 0
+    route = respx_mock.get("/v1/dev/user/memories").mock(
+        side_effect=getattr(httpx, error_name)("Connection unavailable")
+    )
+    args = (["--json"] if json_mode else []) + ["auth", "login", "--api-key", "omi_dev_" + "n" * 32]
+    monkeypatch.setattr("sys.argv", ["omi", *args])
+    with pytest.raises(SystemExit) as result:
+        main()
+    assert result.value.code == 3
     assert route.call_count == 1
     assert config_path.read_bytes() == before
+    captured = capsys.readouterr()
+    assert captured.out == ""
+    if json_mode:
+        assert json.loads(captured.err)["error"] == "Connection failed"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions