Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

9.0 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""The httpx client must follow the opt-in switch live, or it refuses connections the owner allowed."""

from pathlib import Path
import sys

import time

import pytest

_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
    sys.path.insert(0, _BACKEND_DIR)

from core.inference import external_provider
from utils.account_context import OWNER, AccountContext, bind_account, reset_account

ALICE = AccountContext("a" * 32, "alice")
BOB = AccountContext("b" * 32, "bob")


@pytest.fixture(autouse = True)
def fresh_singleton(monkeypatch):
    monkeypatch.setattr(external_provider, "_managed_clients", {}, raising = False)
    monkeypatch.setattr(external_provider, "_retired_accounts", set(), raising = False)
    yield
    external_provider._managed_clients = {}
    external_provider._retired_accounts = set()


@pytest.fixture
def switch(monkeypatch):
    state = {"allowed": False}
    from utils import managed_provider_url_settings

    # Patch the settings module: _client imports the helper per call.
    monkeypatch.setattr(
        managed_provider_url_settings,
        "get_managed_private_provider_urls_allowed",
        lambda: state["allowed"],
    )
    return state


def client_as(account):
    token = bind_account(account)
    try:
        return external_provider._client()
    finally:
        reset_account(token)


def is_pinned(client) -> bool:
    """Public-only. Exact type: the allowed-private screen subclasses this, so isinstance would
    call that pinned too and every assertion below would stop meaning anything."""
    return type(getattr(client, "_transport", None)) is external_provider._PinnedPublicTransport


def test_owner_always_gets_the_shared_client(switch):
    for allowed in (False, True):
        switch["allowed"] = allowed
        assert client_as(OWNER) is external_provider._http_client


def test_managed_account_is_pinned_by_default(switch):
    assert is_pinned(client_as(ALICE))


def test_managed_account_stops_being_held_to_public_when_allowed(switch):
    """The public pin comes off; a screen that still refuses metadata replaces it."""
    switch["allowed"] = True
    client = client_as(ALICE)
    assert not is_pinned(client)
    assert isinstance(client._transport, external_provider._PinnedNonMetadataTransport)
    assert client is not external_provider._http_client


def test_the_choice_follows_a_live_flip(switch):
    """A stale module-level singleton must not outlive the setting that selected it."""
    assert is_pinned(client_as(ALICE))
    switch["allowed"] = True
    assert isinstance(client_as(ALICE)._transport, external_provider._PinnedNonMetadataTransport)
    switch["allowed"] = False
    assert is_pinned(client_as(ALICE))


def test_the_pinning_client_is_reused_not_rebuilt(switch):
    """Rebuilding per call would drop every pooled connection."""
    assert client_as(ALICE) is client_as(ALICE)


def test_two_managed_accounts_never_share_a_client(switch):
    """httpx persists cookies per client, so one shared by two accounts carries a gateway
    session from one to the other. https://www.python-httpx.org/advanced/clients/"""
    for allowed in (False, True):
        switch["allowed"] = allowed
        alice, bob = client_as(ALICE), client_as(BOB)
        assert alice is not bob

        alice.cookies.set("gateway_session", "ALICE", domain = "gw.example")
        try:
            assert bob.cookies.get("gateway_session", domain = "gw.example") is None
        finally:
            alice.cookies.clear()


def test_an_unbound_thread_defaults_to_owner(switch):
    """The account ContextVar fails open: a worker thread that forgot run_as reads as the owner.
    Unchanged by the switch, and load-bearing for any _client() caller off the request path."""
    import threading

    seen = []

    def worker():
        seen.append(external_provider._client())

    token = bind_account(ALICE)
    try:
        thread = threading.Thread(target = worker)
        thread.start()
        thread.join()
    finally:
        reset_account(token)
    assert seen[0] is external_provider._http_client


def test_the_allowed_client_is_never_the_owners_object(switch):
    """An httpx client carries a cookie jar, so sharing the object shares Set-Cookie across accounts."""
    switch["allowed"] = True
    managed = client_as(ALICE)
    assert managed is not external_provider._http_client
    assert managed.cookies is not external_provider._http_client.cookies

    external_provider._http_client.cookies.set("owner_session", "SECRET", domain = "gw.example")
    try:
        assert managed.cookies.get("owner_session", domain = "gw.example") is None
    finally:
        external_provider._http_client.cookies.clear()


def test_the_allowed_client_still_screens_every_connection(switch):
    """The switch opens private addresses, not the host's credentials endpoint."""
    switch["allowed"] = True
    managed = client_as(ALICE)
    transport = managed._transport
    assert isinstance(transport, external_provider._PinnedNonMetadataTransport)

    from core.inference.providers import provider_address_excluding_metadata

    assert provider_address_excluding_metadata("http://127.0.0.1:11434/v1") == "127.0.0.1"
    assert provider_address_excluding_metadata("http://192.168.1.50:8000/v1") == "192.168.1.50"
    for metadata in (
        "http://169.254.169.254/v1",
        "http://2852039166/v1",
        "http://[fd00:ec2::254]/v1",
    ):
        with pytest.raises(ValueError) as refusal:
            provider_address_excluding_metadata(metadata)
        assert "metadata" in str(refusal.value).lower()


def test_a_retired_account_stops_being_held(switch):
    """Deleting an account has to drop its clients, or the cache is bounded by accounts ever
    created rather than accounts that exist, and a deleted one's cookie jar outlives it."""
    for allowed in (False, True):
        switch["allowed"] = allowed
        client_as(ALICE)
    client_as(BOB)
    assert sum(1 for key in external_provider._managed_clients if key[0] == ALICE.account_id) == 2

    assert external_provider.retire_account_clients(ALICE.account_id) == 2
    assert not [key for key in external_provider._managed_clients if key[0] == ALICE.account_id]
    assert [key for key in external_provider._managed_clients if key[0] == BOB.account_id]
    assert external_provider.retire_account_clients(ALICE.account_id) == 0


def test_account_retirement_calls_it(switch):
    """The route is where it has to happen; a helper nobody calls fixes nothing."""
    import inspect

    import routes.accounts as accounts_routes

    source = inspect.getsource(accounts_routes.retire_account_roots)
    assert "retire_account_clients" in source


def test_a_request_after_retirement_is_served_but_not_cached(switch):
    """A request that authenticated before deletion can reach _client() after the sweep; it
    gets a working client, and nothing is left behind for an account nothing sweeps again."""
    client_as(ALICE)
    external_provider.retire_account_clients(ALICE.account_id)

    late = client_as(ALICE)
    assert late is not None
    assert not [key for key in external_provider._managed_clients if key[0] == ALICE.account_id]
    assert client_as(ALICE) is not late


def test_retirement_from_a_worker_thread_closes_on_the_owning_loop(switch):
    """Deletion is a synchronous route, so it runs with no loop of its own. Dropping the last
    reference does not close an httpx pool; the close has to reach the loop that opened it."""
    import asyncio
    import threading

    loop = asyncio.new_event_loop()
    ready = threading.Event()

    def run_loop():
        asyncio.set_event_loop(loop)
        loop.call_soon(ready.set)
        loop.run_forever()

    thread = threading.Thread(target = run_loop, daemon = True)
    thread.start()
    ready.wait(5)
    try:
        client = asyncio.run_coroutine_threadsafe(_make_client_as(ALICE), loop).result(timeout = 10)
        assert not client.is_closed

        assert external_provider.retire_account_clients(ALICE.account_id) == 1
        deadline = time.time() + 10
        while time.time() < deadline and not client.is_closed:
            time.sleep(0.05)
        assert client.is_closed, "the client was dropped rather than closed"
    finally:
        loop.call_soon_threadsafe(loop.stop)
        thread.join(timeout = 5)


async def _make_client_as(account):
    return client_as(account)


def test_reactivation_lifts_the_tombstone(switch):
    """A failed delete must leave no tombstone, so the account stays reactivatable."""
    client_as(ALICE)
    external_provider.retire_account_clients(ALICE.account_id)
    assert client_as(ALICE) is not client_as(ALICE)

    external_provider.restore_account_clients(ALICE.account_id)
    assert client_as(ALICE) is client_as(ALICE)


def test_reactivation_route_calls_it(switch):
    import inspect

    import routes.accounts as accounts_routes
    assert "restore_account_clients" in inspect.getsource(accounts_routes.set_account_active)