fix(runtime): reject invalid homes and placeholder OpenAI keys (#863)

Co-authored-by: evan <evan@dazongguandeMac-mini.local>
This commit is contained in:
evan188199-tech
2026-08-16 04:08:33 -07:00
committed by GitHub
parent 179a8a1795
commit cc23cbe3ac
9 changed files with 137 additions and 3 deletions

View File

@@ -9,6 +9,22 @@ DEEPTUTOR_HOME_ENV = "DEEPTUTOR_HOME"
PACKAGE_ROOT = Path(__file__).resolve().parents[2]
def validate_runtime_home(home: str | Path) -> None:
"""Reject runtime homes that point inside this checkout's data tree."""
resolved = Path(home).expanduser().resolve()
invalid_homes = {
PACKAGE_ROOT / "data",
PACKAGE_ROOT / "data" / "user",
}
if resolved in invalid_homes:
raise ValueError(
f"Invalid DeepTutor runtime home: {resolved}. Runtime data must live under "
f"{PACKAGE_ROOT / 'data'} without nesting. Start DeepTutor with "
f"DEEPTUTOR_HOME={PACKAGE_ROOT} from {PACKAGE_ROOT}."
)
def get_runtime_home(home: str | Path | None = None) -> Path:
"""Return the directory that owns runtime data for this process.
@@ -38,4 +54,5 @@ __all__ = [
"PACKAGE_ROOT",
"get_runtime_home",
"get_runtime_data_root",
"validate_runtime_home",
]

View File

@@ -21,7 +21,12 @@ from urllib import parse as urlparse
from urllib import request as urlrequest
from deeptutor.runtime.banner import labels_for, print_banner, resolve_language
from deeptutor.runtime.home import DEEPTUTOR_HOME_ENV, PACKAGE_ROOT, get_runtime_home
from deeptutor.runtime.home import (
DEEPTUTOR_HOME_ENV,
PACKAGE_ROOT,
get_runtime_home,
validate_runtime_home,
)
from deeptutor.runtime.memory_probe import SUPERVISOR_PID_ENV
BACKEND_READY_TIMEOUT = 60
@@ -930,6 +935,10 @@ def _install_signal_handlers(request_shutdown: Callable[[str | None], None]) ->
def start(home: str | Path | None = None, *, dev: bool = False) -> None:
_relax_console_encoding()
runtime_home = get_runtime_home(home)
try:
validate_runtime_home(runtime_home)
except ValueError as exc:
raise SystemExit(str(exc)) from exc
runtime_home.mkdir(parents=True, exist_ok=True)
os.environ[DEEPTUTOR_HOME_ENV] = str(runtime_home)
_reset_runtime_singletons()

View File

@@ -728,8 +728,6 @@ def resolve_llm_runtime_config(
profile, model = _active_profile_and_model(loaded, catalog_service, "llm")
resolved_model = _as_str((model or {}).get("model"))
if not resolved_model:
resolved_model = "gpt-4o-mini"
binding_hint_raw = _as_str((profile or {}).get("binding"))
binding_hint = canonical_provider_name(binding_hint_raw)

View File

@@ -170,6 +170,16 @@ def _get_llm_config_from_resolver() -> LLMConfig:
raise LLMConfigError(
"No effective LLM endpoint resolved. Please configure base_url or provider defaults."
)
is_placeholder_key = resolved.api_key in {"", "no-key", "sk-no-key-required"}
if (
resolved.provider_name == "openai"
and resolved.provider_mode == "standard"
and is_placeholder_key
):
raise LLMConfigError(
"OpenAI API key is not configured. Set it in Settings > Catalog, "
"or select a local provider such as Ollama."
)
return LLMConfig(
model=resolved.model,
api_key=resolved.api_key,

View File

@@ -16,11 +16,28 @@ from deeptutor.services.llm.provider_registry import find_by_name, strip_provide
from deeptutor.services.llm.reasoning_params import default_reasoning_effort_for
from .config import get_token_limit_kwargs
from .exceptions import LLMConfigError
from .utils import extract_response_content
logger = logging.getLogger(__name__)
def _validate_openai_sdk_credentials(
*, provider_name: str | None, api_key: str | None, base_url: str | None
) -> None:
"""Keep placeholder keys from reaching the official OpenAI API."""
provider = (provider_name or "").lower()
endpoint = (base_url or "").rstrip("/")
official_openai = not endpoint or endpoint == "https://api.openai.com/v1"
placeholder = api_key in {None, "", "no-key", "sk-no-key-required"}
if provider == "openai" and official_openai and placeholder:
raise LLMConfigError(
"OpenAI API key is not configured. Set it in Settings > Catalog, "
"or select a local provider such as Ollama."
)
def _is_unsupported_response_format_error(exc: BaseException) -> bool:
"""Detect whether a BadRequestError stems from an unsupported ``response_format``.
@@ -148,6 +165,11 @@ async def sdk_complete(
api_key,
base_url,
)
_validate_openai_sdk_credentials(
provider_name=provider_name,
api_key=effective_key,
base_url=effective_base,
)
default_headers: dict[str, str] = {"x-session-affinity": uuid.uuid4().hex}
if extra_headers:
@@ -218,6 +240,11 @@ async def sdk_stream(
api_key,
base_url,
)
_validate_openai_sdk_credentials(
provider_name=provider_name,
api_key=effective_key,
base_url=effective_base,
)
default_headers: dict[str, str] = {"x-session-affinity": uuid.uuid4().hex}
if extra_headers:

View File

@@ -19,6 +19,7 @@ import json_repair
from openai import AsyncOpenAI
from deeptutor.services.llm.capabilities import disable_response_format_at_runtime
from deeptutor.services.llm.exceptions import LLMConfigError
from deeptutor.services.llm.openai_http_client import openai_client_kwargs
from deeptutor.services.llm.provider_core.base import LLMProvider, LLMResponse, ToolCallRequest
from deeptutor.services.llm.provider_core.openai_responses import (
@@ -130,6 +131,17 @@ class OpenAICompatProvider(LLMProvider):
effective_base = api_base or (spec.default_api_base if spec else None) or None
self._effective_base = effective_base
endpoint = (effective_base or "").rstrip("/")
placeholder_key = api_key in {None, "", "no-key", "sk-no-key-required"}
if (
provider_name == "openai"
and (not endpoint or endpoint == "https://api.openai.com/v1")
and placeholder_key
):
raise LLMConfigError(
"OpenAI API key is not configured. Set it in Settings > Catalog, "
"or select a local provider such as Ollama."
)
default_headers: dict[str, str] = {"x-session-affinity": uuid.uuid4().hex}
if _uses_openrouter(spec, effective_base):
default_headers.update(_DEFAULT_OPENROUTER_HEADERS)

View File

@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
from deeptutor.runtime import launcher
from deeptutor.runtime.home import validate_runtime_home
class _FakeTty:
@@ -38,6 +39,28 @@ def test_packaged_web_cache_replaces_next_public_placeholders(tmp_path: Path) ->
assert "auth='true'" in (runtime / ".next" / "static" / "app.js").read_text(encoding="utf-8")
def test_runtime_home_rejects_project_data_paths(monkeypatch, tmp_path: Path) -> None:
package_root = tmp_path / "package"
monkeypatch.setattr("deeptutor.runtime.home.PACKAGE_ROOT", package_root)
with pytest.raises(ValueError, match="Invalid DeepTutor runtime home"):
validate_runtime_home(package_root / "data")
with pytest.raises(ValueError, match="Invalid DeepTutor runtime home"):
validate_runtime_home(package_root / "data" / "user")
def test_start_does_not_create_nested_data_tree(monkeypatch, tmp_path: Path) -> None:
package_root = tmp_path / "package"
bad_home = package_root / "data" / "user"
monkeypatch.setattr("deeptutor.runtime.home.PACKAGE_ROOT", package_root)
monkeypatch.setattr(launcher, "get_runtime_home", lambda _home=None: bad_home)
with pytest.raises(SystemExit, match="Invalid DeepTutor runtime home"):
launcher.start(bad_home)
assert not bad_home.exists()
def test_packaged_web_cache_refreshes_when_public_settings_change(tmp_path: Path) -> None:
packaged = tmp_path / "pkg"
(packaged / ".next").mkdir(parents=True)

View File

@@ -348,6 +348,19 @@ def test_llm_local_fallback() -> None:
assert resolved.api_key == "sk-no-key-required"
def test_llm_empty_catalog_does_not_fallback_to_openai() -> None:
catalog = _build_catalog()
catalog["services"]["llm"] = {
"active_profile_id": None,
"active_model_id": None,
"profiles": [],
}
resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.model == ""
def test_llm_minimax_binding_uses_global_endpoint() -> None:
catalog = _build_catalog(
llm_profile={

View File

@@ -171,3 +171,28 @@ def test_resolver_missing_model_raises(monkeypatch) -> None:
)
with pytest.raises(LLMConfigError):
config_module.get_llm_config()
def test_official_openai_without_real_key_raises(monkeypatch) -> None:
_reset_config_cache()
monkeypatch.setattr(
config_module,
"resolve_llm_runtime_config",
lambda: ResolvedLLMConfig(
model="gpt-4o-mini",
provider_name="openai",
provider_mode="standard",
binding_hint="openai",
binding="openai",
api_key="",
base_url="https://api.openai.com/v1",
effective_url="https://api.openai.com/v1",
api_version=None,
extra_headers={},
reasoning_effort=None,
context_window=None,
),
)
with pytest.raises(LLMConfigError, match="OpenAI API key is not configured"):
config_module.get_llm_config()