Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

7.8 KB
Raw Blame
"""Grok Build auth service — status / login parsing, isolated worker home."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

from dodaios.grok_build_auth import (
    GrokBuildAuthService,
    GrokBuildAuthStatus,
    _derive_auth,
    _email_from_auth,
    grok_build_install_command,
    grok_build_login_in,
    grok_build_provider_ready,
    prepare_worker_home,
)

_CLI_SCOPE = "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"


@pytest.fixture(autouse=True)
def isolated_auth_scope(monkeypatch):
    for prefix in ("GROK_OIDC", "GROK_OAUTH2"):
        for suffix in ("ISSUER", "CLIENT_ID"):
            monkeypatch.delenv(f"{prefix}_{suffix}", raising=False)


def test_current_cli_store_connects_cards_and_agent_picker(monkeypatch, tmp_path):
    from dodaios.ui.web.agent_chat_routes import _cli_subscription_connected

    (tmp_path / "auth.json").write_text(
        json.dumps(
            {
                _CLI_SCOPE: {
                    "key": "test-bearer",
                    "auth_mode": "oidc",
                    "refresh_token": "test-refresh",
                    "email": "[email protected]",
                },
                "https://other.example::client": {
                    "key": "other",
                    "auth_mode": "oidc",
                    "email": "[email protected]",
                },
            }
        ),
        encoding="utf-8",
    )
    service = GrokBuildAuthService(grok_home_dir=tmp_path)
    monkeypatch.setattr(service, "_resolve_binary", lambda: "grok")
    monkeypatch.setattr(service, "_probe_version", lambda _: "grok 1.0.13")
    status = service.status()
    assert grok_build_provider_ready(status)
    assert _cli_subscription_connected("grok-cli", status)
    assert status.user_email == "[email protected]"
    assert "test-bearer" not in json.dumps(status.to_dict())
    assert "test-refresh" not in json.dumps(status.to_dict())


@pytest.mark.parametrize(
    "record",
    [
        {},
        None,
        "invalid",
        {"email": "[email protected]"},
        {"auth_mode": "oidc", "key": " "},
        {"auth_mode": "external", "key": "test-key", "refresh_token": "test-refresh"},
        {"auth_mode": "web_login", "key": "test-key"},
    ],
)
def test_scoped_invalid_or_unsupported_login_is_disconnected(record):
    assert _derive_auth({_CLI_SCOPE: record}) == (False, "unknown")


def test_scoped_api_key_is_never_a_subscription():
    assert _derive_auth(
        {
            "xai::api_key": {
                "key": "test-api-key",
                "auth_mode": "api_key",
                "refresh_token": "test-refresh",
            }
        }
    ) == (True, "api_key")


def test_cli_scope_does_not_borrow_another_login(monkeypatch):
    auth = {_CLI_SCOPE: {"key": "test-bearer", "auth_mode": "oidc"}}
    monkeypatch.setenv("GROK_OIDC_ISSUER", "https://tenant.example/")
    monkeypatch.setenv("GROK_OIDC_CLIENT_ID", "test-client")
    assert _derive_auth(auth) == (False, "unknown")
    auth["https://tenant.example::test-client"] = {
        "key": "tenant-test-bearer",
        "auth_mode": "oidc",
        "email": "[email protected]",
    }
    assert _derive_auth(auth) == (True, "subscription")
    assert _email_from_auth(auth) == "[email protected]"


def test_scoped_refreshable_login_is_recognized():
    assert _derive_auth(
        {
            _CLI_SCOPE: {
                "auth_mode": "oidc",
                "refresh_token": "test-refresh",
            }
        }
    ) == (True, "subscription")


def test_derive_auth_subscription_tokens() -> None:
    connected, mode = _derive_auth({"tokens": {"access_token": "tok", "refresh_token": "ref"}})
    assert connected is True
    assert mode == "subscription"


def test_derive_auth_api_key_field() -> None:
    connected, mode = _derive_auth({"XAI_API_KEY": "xai-test"})
    assert connected is True
    assert mode == "api_key"


def test_derive_auth_empty() -> None:
    assert _derive_auth({}) == (False, "unknown")
    assert _derive_auth(None) == (False, "unknown")


def test_derive_auth_identity_without_token_is_disconnected() -> None:
    """Leftover profile JSON after logout must not paint Ready."""
    assert _derive_auth({"user": {"email": "[email protected]"}}) == (False, "unknown")
    assert _derive_auth({"account": {"id": "u1", "username": "ada"}}) == (
        False,
        "unknown",
    )


def test_email_from_user_object() -> None:
    assert _email_from_auth({"user": {"email": "[email protected]"}}) == "[email protected]"


def test_login_in_reads_one_home(tmp_path: Path) -> None:
    (tmp_path / "auth.json").write_text(
        json.dumps({"tokens": {"access_token": "tok"}, "user": {"email": "[email protected]"}}),
        encoding="utf-8",
    )
    connected, mode, email = grok_build_login_in(tmp_path)
    assert connected is True
    assert mode == "subscription"
    assert email == "[email protected]"


def test_login_in_missing_file(tmp_path: Path) -> None:
    assert grok_build_login_in(tmp_path) == (False, "unknown", None)


def test_provider_ready_requires_installed_subscription() -> None:
    assert grok_build_provider_ready(GrokBuildAuthStatus()) is False
    assert (
        grok_build_provider_ready(
            GrokBuildAuthStatus(installed=True, connected=True, mode="api_key")
        )
        is False
    )
    assert (
        grok_build_provider_ready(
            GrokBuildAuthStatus(installed=True, connected=True, mode="subscription")
        )
        is True
    )


def test_install_command_is_os_specific() -> None:
    assert "install.ps1" in grok_build_install_command("win32")
    assert "install.sh" in grok_build_install_command("linux")


def test_prepare_worker_home_copies_auth_not_hooks(tmp_path: Path) -> None:
    src = tmp_path / "src"
    dest = tmp_path / "dest"
    src.mkdir()
    (src / "auth.json").write_text(
        json.dumps({"tokens": {"access_token": "tok"}}),
        encoding="utf-8",
    )
    (src / "hooks").mkdir()
    (src / "hooks" / "evil.json").write_text("{}", encoding="utf-8")
    isolated = prepare_worker_home(src_home=src, dest_root=dest)
    assert isolated == dest
    assert (dest / "auth.json").is_file()
    assert not (dest / "hooks").exists()
    assert "[cli]" in (dest / "config.toml").read_text(encoding="utf-8")


def test_prepare_worker_home_wipes_stale_copy_after_logout(tmp_path: Path) -> None:
    src = tmp_path / "src"
    dest = tmp_path / "dest"
    src.mkdir()
    dest.mkdir()
    (dest / "auth.json").write_text(
        json.dumps({"tokens": {"access_token": "stale"}}),
        encoding="utf-8",
    )
    (dest / ".jarvis_src_mtime").write_text("1.0", encoding="utf-8")
    isolated = prepare_worker_home(src_home=src, dest_root=dest)
    assert isolated is None
    assert not (dest / "auth.json").exists()
    assert not (dest / ".jarvis_src_mtime").exists()


def test_status_not_installed(monkeypatch, tmp_path: Path) -> None:
    service = GrokBuildAuthService(binary_path="grok-missing-binary", grok_home_dir=tmp_path)
    monkeypatch.setattr(service, "_resolve_binary", lambda: None)
    status = service.status()
    assert status.installed is False
    assert status.connected is False
    assert "not found" in status.message.lower() or "Install" in status.message


def test_status_connected_from_auth_file(monkeypatch, tmp_path: Path) -> None:
    (tmp_path / "auth.json").write_text(
        json.dumps({"tokens": {"access_token": "tok"}, "user": {"email": "[email protected]"}}),
        encoding="utf-8",
    )
    service = GrokBuildAuthService(binary_path="grok", grok_home_dir=tmp_path)
    monkeypatch.setattr(service, "_resolve_binary", lambda: str(tmp_path / "grok"))
    monkeypatch.setattr(service, "_probe_version", lambda _binary: "grok 0.2.0")
    status = service.status()
    assert status.installed is True
    assert status.connected is True
    assert status.mode == "subscription"
    assert status.user_email == "[email protected]"