From b3aacc186f84f5093707863fb1e8828a7202b57f Mon Sep 17 00:00:00 2001 From: openhands Date: Wed, 14 Oct 2026 14:47:37 +0000 Subject: [PATCH 1/5] feat(plugin): add strict plugin fetch preflight Co-authored-by: openhands --- .../openhands/agent_server/plugins_router.py | 67 +++ .../openhands/agent_server/plugins_service.py | 23 + .../openhands/sdk/plugin/__init__.py | 8 + openhands-sdk/openhands/sdk/plugin/fetch.py | 35 +- openhands-sdk/openhands/sdk/plugin/paths.py | 17 + .../openhands/sdk/plugin/strict_fetch.py | 488 ++++++++++++++++++ tests/agent_server/test_plugins_router.py | 78 +++ tests/sdk/plugin/test_plugin_strict_fetch.py | 162 ++++++ 8 files changed, 877 insertions(+), 1 deletion(-) create mode 100644 openhands-sdk/openhands/sdk/plugin/paths.py create mode 100644 openhands-sdk/openhands/sdk/plugin/strict_fetch.py create mode 100644 tests/sdk/plugin/test_plugin_strict_fetch.py diff --git a/openhands-agent-server/openhands/agent_server/plugins_router.py b/openhands-agent-server/openhands/agent_server/plugins_router.py index 10da85a2635..8f6dcdd46f6 100644 --- a/openhands-agent-server/openhands/agent_server/plugins_router.py +++ b/openhands-agent-server/openhands/agent_server/plugins_router.py @@ -19,6 +19,7 @@ PluginSkillSummary, service_disable_plugin, service_enable_plugin, + service_fetch_plugin, service_get_installed_plugin, service_get_plugins_marketplace_catalog, service_install_plugin, @@ -31,6 +32,8 @@ ) from openhands.sdk.extensions.fetch import ExtensionFetchError from openhands.sdk.plugin import InstalledPluginInfo, Plugin, PluginFetchError +from openhands.sdk.plugin.strict_fetch import PluginSourceError +from openhands.sdk.secret import SecretSource plugins_router = APIRouter(prefix="/plugins", tags=["Plugins"]) @@ -114,6 +117,34 @@ class InstallPluginRequest(BaseModel): ) +class FetchPluginRequest(BaseModel): + """Request body for strictly fetching a plugin without installing it.""" + + source: str = Field(min_length=1, description="Plugin git source") + ref: str | None = Field(default=None, description="Branch, tag, or commit") + repo_path: str | None = Field( + default=None, + description="Subdirectory path within the repository (for monorepos)", + ) + secrets: dict[str, SecretSource] = Field( + default_factory=dict, + description="Secrets used to expand ${VAR} placeholders in source and ref", + ) + timeout: int = Field(default=60, ge=1, le=600, description="Git timeout seconds") + + +class FetchPluginResponse(BaseModel): + """Response from strictly fetching a plugin source.""" + + path: str + resolved_ref: str | None + source: str + repo_path: str | None + manifest: dict + skills: list[str] + commands: list[str] + + class InstalledPluginResponse(BaseModel): """Response containing installed plugin information.""" @@ -237,6 +268,42 @@ def get_plugins(request: PluginsRequest) -> PluginsResponse: return PluginsResponse(plugins=[_plugin_info(p) for p in plugins]) +@plugins_router.post( + "/fetch", + response_model=FetchPluginResponse, + responses={ + 422: {"description": "Invalid plugin source, ref, path, or plugin"}, + 502: {"description": "Plugin source unavailable"}, + 504: {"description": "Plugin fetch timed out"}, + }, +) +def fetch_plugin_endpoint(request: FetchPluginRequest) -> FetchPluginResponse: + """Fetch and pin a plugin source without installing or enabling it.""" + try: + checked = service_fetch_plugin( + source=request.source, + ref=request.ref, + repo_path=request.repo_path, + secrets=request.secrets, + timeout=request.timeout, + ) + except PluginSourceError as exc: + raise HTTPException( + status_code=exc.status_code, + detail={"code": exc.code, "message": exc.message}, + ) from exc + + return FetchPluginResponse( + path=str(checked.path), + resolved_ref=checked.resolved_ref, + source=checked.source, + repo_path=checked.repo_path, + manifest=checked.manifest, + skills=checked.skills, + commands=checked.commands, + ) + + @plugins_router.post( "/install", response_model=InstalledPluginResponse, diff --git a/openhands-agent-server/openhands/agent_server/plugins_service.py b/openhands-agent-server/openhands/agent_server/plugins_service.py index 157e3406a10..1f7023c8177 100644 --- a/openhands-agent-server/openhands/agent_server/plugins_service.py +++ b/openhands-agent-server/openhands/agent_server/plugins_service.py @@ -15,6 +15,7 @@ import json import os +from collections.abc import Mapping from pathlib import Path from time import monotonic @@ -23,6 +24,7 @@ from openhands.sdk.logger import get_logger from openhands.sdk.marketplace import Marketplace from openhands.sdk.plugin import ( + CheckedPlugin, InstalledPluginInfo, Plugin, disable_plugin, @@ -33,6 +35,8 @@ uninstall_plugin, update_plugin, ) +from openhands.sdk.plugin.strict_fetch import fetch_plugin_strict +from openhands.sdk.secret import SecretValue from openhands.sdk.skills.skill import ( DEFAULT_MARKETPLACE_PATH, PUBLIC_SKILLS_REF, @@ -70,6 +74,25 @@ def service_install_plugin( ) +def service_fetch_plugin( + source: str, + ref: str | None = None, + repo_path: str | None = None, + secrets: Mapping[str, SecretValue] | None = None, + timeout: int = 60, +) -> CheckedPlugin: + """Strictly fetch a plugin into the immutable plugin cache.""" + return fetch_plugin_strict( + source=source, + ref=ref, + repo_path=repo_path, + secrets=secrets, + timeout=timeout, + allow_local=True, + use_cache=True, + ) + + def service_uninstall_plugin(name: str, installed_dir: Path | None = None) -> bool: """Uninstall a plugin by name. Returns False if it wasn't installed.""" return uninstall_plugin(name, installed_dir=installed_dir) diff --git a/openhands-sdk/openhands/sdk/plugin/__init__.py b/openhands-sdk/openhands/sdk/plugin/__init__.py index 7568e90f7e1..651e4b49228 100644 --- a/openhands-sdk/openhands/sdk/plugin/__init__.py +++ b/openhands-sdk/openhands/sdk/plugin/__init__.py @@ -49,6 +49,11 @@ resolve_source_path, validate_source_path, ) +from openhands.sdk.plugin.strict_fetch import ( + CheckedPlugin, + PluginSourceError, + preflight_plugin, +) from openhands.sdk.plugin.types import ( CommandDefinition, PluginAuthor, @@ -62,6 +67,8 @@ # Plugin classes "Plugin", "PluginFetchError", + "PluginSourceError", + "CheckedPlugin", "PluginManifest", "PluginAuthor", "PluginSource", @@ -75,6 +82,7 @@ # Plugin loading "load_plugins", "fetch_plugin_with_resolution", + "preflight_plugin", # Local plugin discovery (ambient auto-load) "load_user_plugins", "load_project_plugins", diff --git a/openhands-sdk/openhands/sdk/plugin/fetch.py b/openhands-sdk/openhands/sdk/plugin/fetch.py index 2b9bac1f849..898057358ff 100644 --- a/openhands-sdk/openhands/sdk/plugin/fetch.py +++ b/openhands-sdk/openhands/sdk/plugin/fetch.py @@ -7,23 +7,50 @@ from __future__ import annotations +import re from pathlib import Path from openhands.sdk.extensions.fetch import ( ExtensionFetchError, + SourceType, fetch_with_resolution as _ext_fetch_with_resolution, + parse_extension_source, ) from openhands.sdk.git.cached_repo import GitHelper +from openhands.sdk.plugin.paths import get_pinned_plugin_cache_path from openhands.sdk.utils.path import get_user_persistence_dir DEFAULT_CACHE_DIR = get_user_persistence_dir() / "cache" / "plugins" +_FULL_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$") class PluginFetchError(Exception): """Raised when fetching a plugin fails.""" +def _cached_pinned_plugin( + source: str, cache_dir: Path, ref: str, repo_path: str | None +) -> Path | None: + try: + source_type, url = parse_extension_source(source) + except ExtensionFetchError: + return None + if source_type == SourceType.LOCAL: + return None + + cached_root = get_pinned_plugin_cache_path(url, cache_dir, ref.lower()) + if not cached_root.is_dir(): + return None + if repo_path is None: + return cached_root + + candidate = cached_root / repo_path.strip("/") + if candidate.is_dir() and candidate.resolve().is_relative_to(cached_root.resolve()): + return candidate + return None + + def fetch_plugin( source: str, cache_dir: Path | None = None, @@ -98,6 +125,11 @@ def fetch_plugin_with_resolution( PluginFetchError: If fetching fails or repo_path doesn't exist. """ resolved_cache_dir = cache_dir if cache_dir is not None else DEFAULT_CACHE_DIR + if ref is not None and _FULL_SHA_RE.fullmatch(ref): + cached = _cached_pinned_plugin(source, resolved_cache_dir, ref, repo_path) + if cached is not None: + return cached, ref.lower() + try: return _ext_fetch_with_resolution( source=source, @@ -108,5 +140,6 @@ def fetch_plugin_with_resolution( git_helper=git_helper, ) except ExtensionFetchError as exc: - msg = str(exc).replace("extension", "plugin") + msg = re.sub(r"\bextension\b", "plugin", str(exc)) + msg = re.sub(r"\bExtension\b", "Plugin", msg) raise PluginFetchError(msg) from exc diff --git a/openhands-sdk/openhands/sdk/plugin/paths.py b/openhands-sdk/openhands/sdk/plugin/paths.py new file mode 100644 index 00000000000..6a1ac308565 --- /dev/null +++ b/openhands-sdk/openhands/sdk/plugin/paths.py @@ -0,0 +1,17 @@ +"""Filesystem paths shared by plugin fetch implementations.""" + +from __future__ import annotations + +from pathlib import Path + +from openhands.sdk.extensions.fetch import get_cache_path + + +PINNED_REFS_DIR = "resolved-refs" + + +def get_pinned_plugin_cache_path( + source_url: str, cache_dir: Path, resolved_ref: str +) -> Path: + """Return the immutable cache path for a plugin source at a commit SHA.""" + return get_cache_path(source_url, cache_dir) / PINNED_REFS_DIR / resolved_ref diff --git a/openhands-sdk/openhands/sdk/plugin/strict_fetch.py b/openhands-sdk/openhands/sdk/plugin/strict_fetch.py new file mode 100644 index 00000000000..2c07164b240 --- /dev/null +++ b/openhands-sdk/openhands/sdk/plugin/strict_fetch.py @@ -0,0 +1,488 @@ +"""Strict plugin source resolution for pre-flight checks and sandbox fetches.""" + +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import tempfile +from collections.abc import Iterator, Mapping +from contextlib import contextmanager +from pathlib import Path +from typing import Any + +from filelock import FileLock +from pydantic import BaseModel, Field + +from openhands.sdk.extensions.fetch import SourceType, parse_extension_source +from openhands.sdk.plugin.fetch import DEFAULT_CACHE_DIR, PluginFetchError +from openhands.sdk.plugin.paths import get_pinned_plugin_cache_path +from openhands.sdk.plugin.plugin import Plugin +from openhands.sdk.secret import SecretSource, SecretValue +from openhands.sdk.skills.utils import expand_variable_references +from openhands.sdk.utils.path import resolves_within +from openhands.sdk.utils.redact import ( + redact_url_credentials, + redact_url_credentials_in_text, +) + + +_FULL_SHA_RE = re.compile(r"^[0-9a-fA-F]{40}$") +_BRACED_VAR_RE = re.compile(r"\$\{([a-zA-Z_][a-zA-Z0-9_]*)(?::-([^}]*))?\}") + +_ERROR_STATUSES = { + "missing_secret": 422, + "source_not_allowed": 422, + "auth_failed": 422, + "source_unavailable": 502, + "ref_not_found": 422, + "repo_path_not_found": 422, + "invalid_plugin": 422, + "timeout": 504, +} + + +class PluginSourceError(PluginFetchError): + """Raised when strict plugin source resolution fails.""" + + def __init__(self, code: str, message: str): + super().__init__(message) + self.code = code + self.message = message + + @property + def status_code(self) -> int: + return _ERROR_STATUSES.get(self.code, 422) + + +class CheckedPlugin(BaseModel): + """A strictly resolved plugin checkout and its public metadata.""" + + path: Path = Field(description="Path to the resolved plugin directory") + resolved_ref: str | None = Field(description="Resolved git commit SHA") + source: str = Field(description="Original source, with placeholders preserved") + repo_path: str | None = Field(description="Subdirectory path within the repository") + manifest: dict[str, Any] = Field(description="Raw plugin.json contents") + skills: list[str] = Field(default_factory=list) + commands: list[str] = Field(default_factory=list) + + +def plugin_source_error_status(code: str) -> int: + """Return the HTTP status code used for a strict plugin source error.""" + return _ERROR_STATUSES.get(code, 422) + + +@contextmanager +def preflight_plugin( + source: str, + ref: str | None = None, + repo_path: str | None = None, + secrets: Mapping[str, SecretValue] | None = None, + *, + timeout: int = 60, + allow_local: bool = False, +) -> Iterator[CheckedPlugin]: + """Strictly check a plugin source in a throwaway checkout. + + The temporary checkout is deleted when the context exits, including when the + caller raises while inspecting files referenced by the manifest. + """ + with tempfile.TemporaryDirectory(prefix="openhands-plugin-preflight-") as tmp: + yield fetch_plugin_strict( + source=source, + ref=ref, + repo_path=repo_path, + secrets=secrets, + cache_dir=None, + work_dir=Path(tmp), + timeout=timeout, + allow_local=allow_local, + use_cache=False, + ) + + +def fetch_plugin_strict( + *, + source: str, + ref: str | None = None, + repo_path: str | None = None, + secrets: Mapping[str, SecretValue] | None = None, + cache_dir: Path | None = None, + work_dir: Path | None = None, + timeout: int = 60, + allow_local: bool = False, + use_cache: bool = True, +) -> CheckedPlugin: + """Strictly fetch and describe a plugin without installing it.""" + resolved_cache_dir = ( + DEFAULT_CACHE_DIR if use_cache and cache_dir is None else cache_dir + ) + + expanded_source, expanded_ref, secret_values = _expand_source_and_ref( + source, ref, secrets or {} + ) + source_type, url = parse_extension_source(expanded_source) + + if source_type == SourceType.LOCAL: + if not allow_local: + raise PluginSourceError( + "source_not_allowed", + "Local plugin sources are not allowed for this operation.", + ) + plugin_root = _copy_local_source(url, repo_path, work_dir) + return _checked_plugin( + plugin_root=plugin_root, + source=source, + repo_path=repo_path, + resolved_ref=None, + secret_values=secret_values, + ) + + if expanded_source.startswith("file://") and not allow_local: + raise PluginSourceError( + "source_not_allowed", + "file:// plugin sources are not allowed for this operation.", + ) + + resolved_ref = expanded_ref + if ( + use_cache + and resolved_cache_dir is not None + and resolved_ref is not None + and _FULL_SHA_RE.fullmatch(resolved_ref) + ): + cached_root = get_pinned_plugin_cache_path( + url, resolved_cache_dir, resolved_ref.lower() + ) + if cached_root.is_dir(): + plugin_root = _apply_repo_path(cached_root, repo_path) + return _checked_plugin( + plugin_root=plugin_root, + source=source, + repo_path=repo_path, + resolved_ref=resolved_ref.lower(), + secret_values=secret_values, + ) + + temp_ctx: tempfile.TemporaryDirectory[str] | None = None + if work_dir is None: + temp_ctx = tempfile.TemporaryDirectory(prefix="openhands-plugin-fetch-") + work_root = Path(temp_ctx.name) + else: + work_root = work_dir + work_root.mkdir(parents=True, exist_ok=True) + + try: + fetched_root, fetched_ref = _fetch_git_checkout( + url=url, + ref=expanded_ref, + work_root=work_root, + timeout=timeout, + allow_file=allow_local, + secret_values=secret_values, + ) + resolved_ref = fetched_ref.lower() + + if use_cache and resolved_cache_dir is not None: + cached_root = _store_pinned_checkout( + url, resolved_cache_dir, resolved_ref, fetched_root + ) + plugin_root = _apply_repo_path(cached_root, repo_path) + else: + plugin_root = _apply_repo_path(fetched_root, repo_path) + + return _checked_plugin( + plugin_root=plugin_root, + source=source, + repo_path=repo_path, + resolved_ref=resolved_ref, + secret_values=secret_values, + ) + finally: + if temp_ctx is not None: + temp_ctx.cleanup() + + +def _secret_value(value: SecretValue) -> str | None: + if isinstance(value, str): + return value + if isinstance(value, SecretSource): + return value.get_value() + return None + + +def _expand_source_and_ref( + source: str, + ref: str | None, + secrets: Mapping[str, SecretValue], +) -> tuple[str, str | None, list[str]]: + referenced = sorted( + { + match.group(1) + for value in (source, ref or "") + for match in _BRACED_VAR_RE.finditer(value) + } + ) + resolved: dict[str, str] = {} + for name in referenced: + value = secrets.get(name) + plain_value = _secret_value(value) if value is not None else None + if plain_value is None: + raise PluginSourceError("missing_secret", f"Missing secret: {name}") + resolved[name] = plain_value + + expanded_source = expand_variable_references( + source, + variables=resolved, + check_env=False, + support_unbraced=False, + expand_defaults=False, + ) + expanded_ref = ( + expand_variable_references( + ref, + variables=resolved, + check_env=False, + support_unbraced=False, + expand_defaults=False, + ) + if ref is not None + else None + ) + return expanded_source, expanded_ref, list(resolved.values()) + + +def _copy_local_source(url: str, repo_path: str | None, work_dir: Path | None) -> Path: + source_root = Path(url).expanduser().resolve() + plugin_root = _apply_repo_path(source_root, repo_path) + if work_dir is None: + return plugin_root + destination = work_dir / "local-plugin" + shutil.copytree(plugin_root, destination, symlinks=True) + return destination + + +def _fetch_git_checkout( + *, + url: str, + ref: str | None, + work_root: Path, + timeout: int, + allow_file: bool, + secret_values: list[str], +) -> tuple[Path, str]: + repo_dir = work_root / "repo" + if repo_dir.exists(): + shutil.rmtree(repo_dir) + repo_dir.mkdir(parents=True) + + _run_git(["init"], repo_dir, timeout, allow_file, secret_values) + _run_git( + ["remote", "add", "origin", url], repo_dir, timeout, allow_file, secret_values + ) + + fetch_ref = ref or "HEAD" + try: + _run_git( + ["fetch", "--depth", "1", "origin", fetch_ref], + repo_dir, + timeout, + allow_file, + secret_values, + default_code="ref_not_found" if ref else "source_unavailable", + ) + except PluginSourceError as exc: + if exc.code == "source_unavailable": + raise + raise + + resolved_ref = _run_git( + ["rev-parse", "FETCH_HEAD^{commit}"], + repo_dir, + timeout, + allow_file, + secret_values, + default_code="ref_not_found", + ).strip() + if not _FULL_SHA_RE.fullmatch(resolved_ref): + raise PluginSourceError("ref_not_found", f"Ref not found: {ref or 'HEAD'}") + + _run_git( + ["checkout", "--detach", resolved_ref], + repo_dir, + timeout, + allow_file, + secret_values, + default_code="ref_not_found", + ) + return repo_dir, resolved_ref + + +def _run_git( + args: list[str], + cwd: Path, + timeout: int, + allow_file: bool, + secret_values: list[str], + *, + default_code: str = "source_unavailable", +) -> str: + protocol_file = "always" if allow_file else "never" + cmd = [ + "git", + "-c", + "credential.helper=", + "-c", + "core.askPass=", + "-c", + f"protocol.file.allow={protocol_file}", + *args, + ] + env = os.environ.copy() + env.update( + { + "GIT_TERMINAL_PROMPT": "0", + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ASKPASS": "true", + "SSH_ASKPASS": "true", + } + ) + try: + result = subprocess.run( + cmd, + cwd=cwd, + env=env, + capture_output=True, + text=True, + errors="replace", + check=False, + timeout=timeout, + ) + except subprocess.TimeoutExpired as exc: + raise PluginSourceError("timeout", "Git operation timed out.") from exc + except OSError as exc: + raise PluginSourceError("source_unavailable", f"Git failed: {exc}") from exc + + if result.returncode == 0: + return result.stdout + + stderr = _sanitize_message(result.stderr.strip(), secret_values) + raise PluginSourceError(_classify_git_error(stderr, default_code), stderr) + + +def _classify_git_error(stderr: str, default_code: str) -> str: + lower = stderr.lower() + if "authentication failed" in lower or "authentication required" in lower: + return "auth_failed" + if ( + "couldn't find remote ref" in lower + or "could not find remote ref" in lower + or "not our ref" in lower + or "unadvertised object" in lower + or "bad object" in lower + or "needed a single revision" in lower + ): + return "ref_not_found" + if ( + "could not read username" in lower + or "terminal prompts disabled" in lower + or "repository not found" in lower + or "could not resolve host" in lower + or "failed to connect" in lower + or "connection refused" in lower + or "does not appear to be a git repository" in lower + or "access rights" in lower + ): + return "source_unavailable" + return default_code + + +def _sanitize_message(message: str, secret_values: list[str]) -> str: + sanitized = redact_url_credentials_in_text(message) + sanitized = redact_url_credentials(sanitized) + for value in secret_values: + if value: + sanitized = sanitized.replace(value, "****") + return sanitized + + +def _store_pinned_checkout( + source_url: str, cache_dir: Path, resolved_ref: str, fetched_root: Path +) -> Path: + target = get_pinned_plugin_cache_path(source_url, cache_dir, resolved_ref) + target.parent.mkdir(parents=True, exist_ok=True) + lock_path = target.parent / f"{target.name}.lock" + with FileLock(lock_path): + if target.is_dir(): + return target + tmp_target = target.parent / f".{target.name}.{os.getpid()}.tmp" + if tmp_target.exists(): + shutil.rmtree(tmp_target) + shutil.copytree(fetched_root, tmp_target, symlinks=True) + tmp_target.rename(target) + return target + + +def _apply_repo_path(root: Path, repo_path: str | None) -> Path: + if not repo_path: + return root + plugin_root = root / repo_path.strip("/") + if not resolves_within(plugin_root, root) or not plugin_root.is_dir(): + raise PluginSourceError( + "repo_path_not_found", f"repo_path not found: {repo_path}" + ) + return plugin_root + + +def _checked_plugin( + *, + plugin_root: Path, + source: str, + repo_path: str | None, + resolved_ref: str | None, + secret_values: list[str], +) -> CheckedPlugin: + manifest = _read_raw_manifest(plugin_root, secret_values) + try: + plugin = Plugin.load(plugin_root) + except Exception as exc: + message = _sanitize_message(str(exc), secret_values) + raise PluginSourceError("invalid_plugin", f"Invalid plugin: {message}") from exc + + return CheckedPlugin( + path=plugin_root, + resolved_ref=resolved_ref, + source=source, + repo_path=repo_path, + manifest=manifest, + skills=[skill.name for skill in plugin.skills], + commands=[command.name for command in plugin.commands], + ) + + +def _read_raw_manifest(plugin_root: Path, secret_values: list[str]) -> dict[str, Any]: + candidates = [ + plugin_root / "plugin.json", + plugin_root / ".plugin" / "plugin.json", + plugin_root / ".claude-plugin" / "plugin.json", + ] + for candidate in candidates: + if not candidate.is_file() or not resolves_within(candidate, plugin_root): + continue + try: + data = json.loads(candidate.read_text(encoding="utf-8-sig")) + except (json.JSONDecodeError, OSError, UnicodeDecodeError) as exc: + message = _sanitize_message(str(exc), secret_values) + raise PluginSourceError( + "invalid_plugin", f"Invalid plugin manifest: {message}" + ) from exc + if not isinstance(data, dict): + raise PluginSourceError( + "invalid_plugin", + "Invalid plugin manifest: plugin.json must be an object.", + ) + return data + raise PluginSourceError("invalid_plugin", "Invalid plugin: plugin.json not found.") diff --git a/tests/agent_server/test_plugins_router.py b/tests/agent_server/test_plugins_router.py index e7a3e4984ac..20f02cf694a 100644 --- a/tests/agent_server/test_plugins_router.py +++ b/tests/agent_server/test_plugins_router.py @@ -5,6 +5,7 @@ """ import json +import subprocess from pathlib import Path import pytest @@ -182,3 +183,80 @@ def test_list_available_returns_plugin_summaries( } ] } + + +def _git(repo: Path, *args: str) -> str: + result = subprocess.run( + ["git", *args], + cwd=repo, + check=True, + capture_output=True, + text=True, + ) + return result.stdout.strip() + + +def _make_git_plugin_repo(tmp_path: Path) -> tuple[Path, str]: + repo = tmp_path / "git-plugin" + plugin = repo / "plugins" / "demo" + (plugin / ".plugin").mkdir(parents=True) + (plugin / "commands").mkdir() + (plugin / ".plugin" / "plugin.json").write_text( + json.dumps( + { + "name": "demo-plugin", + "version": "1.0.0", + "automation": {"runner": "conversation"}, + } + ) + ) + (plugin / "commands" / "run.md").write_text("---\ndescription: Run\n---\nRun it") + _git(repo, "init") + _git(repo, "config", "user.email", "test@example.com") + _git(repo, "config", "user.name", "Test") + _git(repo, "add", ".") + _git(repo, "commit", "-m", "initial") + return repo, _git(repo, "rev-parse", "HEAD") + + +def test_fetch_endpoint_pins_without_installing( + client: TestClient, tmp_path: Path, monkeypatch +): + repo, sha = _make_git_plugin_repo(tmp_path) + monkeypatch.setattr( + "openhands.sdk.plugin.strict_fetch.DEFAULT_CACHE_DIR", tmp_path / "cache" + ) + + before = client.get("/plugins/installed").json() + resp = client.post( + "/plugins/fetch", + json={ + "source": f"file://{repo}", + "ref": "HEAD", + "repo_path": "plugins/demo", + }, + ) + after = client.get("/plugins/installed").json() + + assert resp.status_code == 200 + body = resp.json() + assert body["resolved_ref"] == sha + assert sha in body["path"] + assert body["source"] == f"file://{repo}" + assert body["repo_path"] == "plugins/demo" + assert body["manifest"]["automation"] == {"runner": "conversation"} + assert body["commands"] == ["run"] + assert before == after + + +def test_fetch_endpoint_returns_structured_error(client: TestClient): + resp = client.post( + "/plugins/fetch", + json={"source": "https://x-access-token:${TOKEN}@example.invalid/repo.git"}, + ) + + assert resp.status_code == 422 + assert resp.json()["detail"] == { + "code": "missing_secret", + "message": "Missing secret: TOKEN", + } diff --git a/tests/sdk/plugin/test_plugin_strict_fetch.py b/tests/sdk/plugin/test_plugin_strict_fetch.py new file mode 100644 index 00000000000..6cb9831e692 --- /dev/null +++ b/tests/sdk/plugin/test_plugin_strict_fetch.py @@ -0,0 +1,162 @@ +"""Tests for strict plugin pre-flight and pinned fetch behavior.""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +import pytest + +from openhands.sdk.plugin import ( + PluginSourceError, + fetch_plugin_with_resolution, + preflight_plugin, +) +from openhands.sdk.plugin.strict_fetch import fetch_plugin_strict + + +def _git(repo: Path, *args: str) -> str: + result = subprocess.run( + ["git", *args], + cwd=repo, + check=True, + capture_output=True, + text=True, + ) + return result.stdout.strip() + + +def _commit(repo: Path, message: str) -> str: + _git(repo, "add", ".") + _git(repo, "commit", "-m", message) + return _git(repo, "rev-parse", "HEAD") + + +def _make_plugin_repo(tmp_path: Path) -> tuple[Path, str, str]: + repo = tmp_path / "repo" + plugin = repo / "plugins" / "demo" + (plugin / ".plugin").mkdir(parents=True) + (plugin / "skills" / "hello").mkdir(parents=True) + (plugin / "commands").mkdir() + (plugin / ".plugin" / "plugin.json").write_text( + json.dumps( + { + "name": "demo-plugin", + "version": "1.0.0", + "description": "Demo", + "automation": {"runner": "conversation"}, + } + ) + ) + (plugin / "skills" / "hello" / "SKILL.md").write_text( + "---\nname: hello\ndescription: Hello\n---\nHello" + ) + (plugin / "commands" / "run.md").write_text("---\ndescription: Run\n---\nRun it") + _git(repo, "init") + _git(repo, "config", "user.email", "test@example.com") + _git(repo, "config", "user.name", "Test") + sha1 = _commit(repo, "v1") + + (plugin / ".plugin" / "plugin.json").write_text( + json.dumps( + { + "name": "demo-plugin", + "version": "2.0.0", + "description": "Demo v2", + "automation": {"runner": "script"}, + } + ) + ) + sha2 = _commit(repo, "v2") + return repo, sha1, sha2 + + +def test_preflight_rejects_file_source_by_default(tmp_path: Path): + repo, _sha1, _sha2 = _make_plugin_repo(tmp_path) + + with pytest.raises(PluginSourceError) as exc_info: + with preflight_plugin( + source=f"file://{repo}", + ref="HEAD", + repo_path="plugins/demo", + ): + pass + + assert exc_info.value.code == "source_not_allowed" + + +def test_preflight_yields_raw_manifest_and_removes_temp_checkout(tmp_path: Path): + repo, _sha1, sha2 = _make_plugin_repo(tmp_path) + + with preflight_plugin( + source=f"file://{repo}", + ref="HEAD", + repo_path="plugins/demo", + allow_local=True, + ) as checked: + checkout_path = checked.path + assert checkout_path.exists() + assert checked.resolved_ref == sha2 + assert checked.source == f"file://{repo}" + assert checked.repo_path == "plugins/demo" + assert checked.manifest["automation"] == {"runner": "script"} + assert checked.skills == ["hello"] + assert checked.commands == ["run"] + + assert not checkout_path.exists() + + +def test_preflight_missing_secret_fails_before_git(tmp_path: Path): + repo, _sha1, _sha2 = _make_plugin_repo(tmp_path) + + with pytest.raises(PluginSourceError) as exc_info: + with preflight_plugin( + source="file://${TOKEN}@" + str(repo), + ref="HEAD", + repo_path="plugins/demo", + allow_local=True, + ): + pass + + assert exc_info.value.code == "missing_secret" + assert "TOKEN" in exc_info.value.message + + +def test_strict_fetch_pins_each_commit_to_an_immutable_cache_path(tmp_path: Path): + repo, sha1, sha2 = _make_plugin_repo(tmp_path) + cache_dir = tmp_path / "cache" + + first = fetch_plugin_strict( + source=f"file://{repo}", + ref=sha1, + repo_path="plugins/demo", + cache_dir=cache_dir, + allow_local=True, + ) + second = fetch_plugin_strict( + source=f"file://{repo}", + ref=sha2, + repo_path="plugins/demo", + cache_dir=cache_dir, + allow_local=True, + ) + + assert sha1 in str(first.path) + assert sha2 in str(second.path) + assert first.path != second.path + assert first.manifest["version"] == "1.0.0" + assert second.manifest["version"] == "2.0.0" + assert ( + json.loads((first.path / ".plugin" / "plugin.json").read_text())["version"] + == "1.0.0" + ) + + cached_path, resolved = fetch_plugin_with_resolution( + source=f"file://{repo}", + ref=sha1, + repo_path="plugins/demo", + cache_dir=cache_dir, + ) + assert cached_path == first.path + assert resolved == sha1 From 10e032d86363a5ced83270dc0a7aa81564e31959 Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 15 Oct 2026 00:58:38 +0000 Subject: [PATCH 2/5] fix(agent-server): type plugin fetch manifest schema Co-authored-by: openhands --- .../openhands/agent_server/plugins_router.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/openhands-agent-server/openhands/agent_server/plugins_router.py b/openhands-agent-server/openhands/agent_server/plugins_router.py index 8f6dcdd46f6..b674a2a80f4 100644 --- a/openhands-agent-server/openhands/agent_server/plugins_router.py +++ b/openhands-agent-server/openhands/agent_server/plugins_router.py @@ -36,6 +36,11 @@ from openhands.sdk.secret import SecretSource +type JSONValue = ( + str | int | float | bool | None | list[JSONValue] | dict[str, JSONValue] +) + + plugins_router = APIRouter(prefix="/plugins", tags=["Plugins"]) # Kebab-case plugin name — matches the SDK's installed-plugin name rule. Guards @@ -140,7 +145,7 @@ class FetchPluginResponse(BaseModel): resolved_ref: str | None source: str repo_path: str | None - manifest: dict + manifest: dict[str, JSONValue] skills: list[str] commands: list[str] From 97845e0d628a514252fc08765d97f301949fc3a7 Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 15 Oct 2026 02:25:51 +0000 Subject: [PATCH 3/5] fix(plugin): sanitize strict fetch failures Co-authored-by: openhands --- .../openhands/sdk/plugin/strict_fetch.py | 22 ++++++-- tests/agent_server/test_plugins_router.py | 23 +++++++++ tests/sdk/plugin/test_plugin_strict_fetch.py | 50 +++++++++++++++++++ 3 files changed, 92 insertions(+), 3 deletions(-) diff --git a/openhands-sdk/openhands/sdk/plugin/strict_fetch.py b/openhands-sdk/openhands/sdk/plugin/strict_fetch.py index 2c07164b240..e76466e5a32 100644 --- a/openhands-sdk/openhands/sdk/plugin/strict_fetch.py +++ b/openhands-sdk/openhands/sdk/plugin/strict_fetch.py @@ -16,7 +16,11 @@ from filelock import FileLock from pydantic import BaseModel, Field -from openhands.sdk.extensions.fetch import SourceType, parse_extension_source +from openhands.sdk.extensions.fetch import ( + ExtensionFetchError, + SourceType, + parse_extension_source, +) from openhands.sdk.plugin.fetch import DEFAULT_CACHE_DIR, PluginFetchError from openhands.sdk.plugin.paths import get_pinned_plugin_cache_path from openhands.sdk.plugin.plugin import Plugin @@ -34,6 +38,7 @@ _ERROR_STATUSES = { "missing_secret": 422, + "invalid_source": 422, "source_not_allowed": 422, "auth_failed": 422, "source_unavailable": 502, @@ -123,7 +128,13 @@ def fetch_plugin_strict( expanded_source, expanded_ref, secret_values = _expand_source_and_ref( source, ref, secrets or {} ) - source_type, url = parse_extension_source(expanded_source) + try: + source_type, url = parse_extension_source(expanded_source) + except ExtensionFetchError: + raise PluginSourceError( + "invalid_source", + "Invalid plugin source.", + ) from None if source_type == SourceType.LOCAL: if not allow_local: @@ -421,7 +432,12 @@ def _store_pinned_checkout( tmp_target = target.parent / f".{target.name}.{os.getpid()}.tmp" if tmp_target.exists(): shutil.rmtree(tmp_target) - shutil.copytree(fetched_root, tmp_target, symlinks=True) + shutil.copytree( + fetched_root, + tmp_target, + symlinks=True, + ignore=shutil.ignore_patterns(".git"), + ) tmp_target.rename(target) return target diff --git a/tests/agent_server/test_plugins_router.py b/tests/agent_server/test_plugins_router.py index 20f02cf694a..13351069e2e 100644 --- a/tests/agent_server/test_plugins_router.py +++ b/tests/agent_server/test_plugins_router.py @@ -260,3 +260,26 @@ def test_fetch_endpoint_returns_structured_error(client: TestClient): "code": "missing_secret", "message": "Missing secret: TOKEN", } + + +def test_fetch_endpoint_invalid_expanded_source_is_structured_and_redacted( + client: TestClient, +): + secret_value = "supersecretvalue" + + resp = client.post( + "/plugins/fetch", + json={ + "source": "${TOKEN}", + "secrets": { + "TOKEN": {"kind": "StaticSecret", "value": secret_value}, + }, + }, + ) + + assert resp.status_code == 422 + assert resp.json()["detail"] == { + "code": "invalid_source", + "message": "Invalid plugin source.", + } + assert secret_value not in resp.text diff --git a/tests/sdk/plugin/test_plugin_strict_fetch.py b/tests/sdk/plugin/test_plugin_strict_fetch.py index 6cb9831e692..42f163eac30 100644 --- a/tests/sdk/plugin/test_plugin_strict_fetch.py +++ b/tests/sdk/plugin/test_plugin_strict_fetch.py @@ -123,6 +123,22 @@ def test_preflight_missing_secret_fails_before_git(tmp_path: Path): assert "TOKEN" in exc_info.value.message +def test_preflight_invalid_expanded_source_hides_secret_value(): + secret_value = "supersecretvalue" + + with pytest.raises(PluginSourceError) as exc_info: + with preflight_plugin( + source="${TOKEN}", + secrets={"TOKEN": secret_value}, + ): + pass + + assert exc_info.value.code == "invalid_source" + assert exc_info.value.message == "Invalid plugin source." + assert secret_value not in str(exc_info.value) + assert exc_info.value.__cause__ is None + + def test_strict_fetch_pins_each_commit_to_an_immutable_cache_path(tmp_path: Path): repo, sha1, sha2 = _make_plugin_repo(tmp_path) cache_dir = tmp_path / "cache" @@ -160,3 +176,37 @@ def test_strict_fetch_pins_each_commit_to_an_immutable_cache_path(tmp_path: Path ) assert cached_path == first.path assert resolved == sha1 + + +def test_strict_fetch_does_not_cache_git_remote_credentials(tmp_path: Path): + repo, sha1, _sha2 = _make_plugin_repo(tmp_path) + cache_dir = tmp_path / "cache" + secret_value = "SUPERSECRET" + source = f"file://x-access-token:${{TOKEN}}@{repo}" + + first = fetch_plugin_strict( + source=source, + ref=sha1, + repo_path="plugins/demo", + secrets={"TOKEN": secret_value}, + cache_dir=cache_dir, + allow_local=True, + ) + second = fetch_plugin_strict( + source=source, + ref=sha1, + repo_path="plugins/demo", + secrets={"TOKEN": secret_value}, + cache_dir=cache_dir, + allow_local=True, + ) + + assert second.path == first.path + pinned_root = first.path.parents[1] + assert not (pinned_root / ".git").exists() + assert not list(pinned_root.rglob(".git")) + assert secret_value not in "\n".join( + path.read_text(errors="ignore") + for path in pinned_root.rglob("*") + if path.is_file() + ) From 69dfd6f4bece6157f58e56ea5372b82f75667e16 Mon Sep 17 00:00:00 2001 From: openhands Date: Thu, 15 Oct 2026 19:55:42 +0000 Subject: [PATCH 4/5] fix(sdk): export agent profile summary models Co-authored-by: openhands --- .../agent_server/agent_profiles_router.py | 18 +-------- .../openhands/sdk/profiles/__init__.py | 4 ++ .../openhands/sdk/profiles/agent_profile.py | 18 +++++++++ tests/sdk/profiles/test_agent_profile.py | 39 +++++++++++++++++++ 4 files changed, 63 insertions(+), 16 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/agent_profiles_router.py b/openhands-agent-server/openhands/agent_server/agent_profiles_router.py index 68725fa3a68..516bba34b65 100644 --- a/openhands-agent-server/openhands/agent_server/agent_profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/agent_profiles_router.py @@ -47,6 +47,8 @@ ACPAgentProfile, AgentProfile, AgentProfileDiagnostics, + AgentProfileInfo, + AgentProfileListResponse, AgentProfileStore, OpenHandsAgentProfile, ProfileLimitExceeded, @@ -73,22 +75,6 @@ ProfileId = Annotated[str, Path(min_length=1, max_length=128)] -class AgentProfileInfo(BaseModel): - """Summary projection of a stored profile (no secret instantiation).""" - - id: str | None = None - name: str - agent_kind: str = "openhands" - revision: int | None = None - llm_profile_ref: str | None = None - mcp_server_refs: list[str] | None = None - - -class AgentProfileListResponse(BaseModel): - profiles: list[AgentProfileInfo] - active_agent_profile_id: str | None = None - - class AgentProfileDetailResponse(BaseModel): name: str profile: dict[str, Any] diff --git a/openhands-sdk/openhands/sdk/profiles/__init__.py b/openhands-sdk/openhands/sdk/profiles/__init__.py index 1dc2bf6b243..94b40c3674d 100644 --- a/openhands-sdk/openhands/sdk/profiles/__init__.py +++ b/openhands-sdk/openhands/sdk/profiles/__init__.py @@ -5,6 +5,8 @@ ACPAgentProfile, AgentProfile, AgentProfileBase, + AgentProfileInfo, + AgentProfileListResponse, LaunchedAgentProfile, OpenHandsAgentProfile, ProfileVerificationSettings, @@ -43,6 +45,8 @@ "ACPAgentProfile", "AgentProfile", "AgentProfileBase", + "AgentProfileInfo", + "AgentProfileListResponse", "AgentProfileDiagnostics", "AgentProfileStore", "AgentProfileStoreProtocol", diff --git a/openhands-sdk/openhands/sdk/profiles/agent_profile.py b/openhands-sdk/openhands/sdk/profiles/agent_profile.py index 82e4686d157..e5da26fd4ce 100644 --- a/openhands-sdk/openhands/sdk/profiles/agent_profile.py +++ b/openhands-sdk/openhands/sdk/profiles/agent_profile.py @@ -84,6 +84,24 @@ def build_profile_verification( ) +class AgentProfileInfo(BaseModel): + """Summary projection of a stored profile (no secret instantiation).""" + + id: str | None = None + name: str + agent_kind: AgentKind = "openhands" + revision: int | None = None + llm_profile_ref: str | None = None + mcp_server_refs: list[str] | None = None + + +class AgentProfileListResponse(BaseModel): + """Response body returned by ``GET /api/agent-profiles``.""" + + profiles: list[AgentProfileInfo] + active_agent_profile_id: str | None = None + + class AgentProfileBase(BaseModel): """Shared identity + provenance fields for every ``AgentProfile`` variant. diff --git a/tests/sdk/profiles/test_agent_profile.py b/tests/sdk/profiles/test_agent_profile.py index f4ca5d50497..a837c7895ab 100644 --- a/tests/sdk/profiles/test_agent_profile.py +++ b/tests/sdk/profiles/test_agent_profile.py @@ -16,6 +16,8 @@ AGENT_PROFILE_SCHEMA_VERSION, ACPAgentProfile, AgentProfile, + AgentProfileInfo, + AgentProfileListResponse, OpenHandsAgentProfile, validate_agent_profile, ) @@ -30,6 +32,43 @@ ) +def test_agent_profile_info_accepts_acp_summary_with_null_llm_ref() -> None: + summary = AgentProfileInfo.model_validate( + { + "id": str(uuid4()), + "name": "codex", + "agent_kind": "acp", + "revision": 7, + "llm_profile_ref": None, + "mcp_server_refs": ["github"], + } + ) + + assert summary.name == "codex" + assert summary.agent_kind == "acp" + assert summary.llm_profile_ref is None + assert summary.mcp_server_refs == ["github"] + + +def test_agent_profile_list_response_validates_profile_summaries() -> None: + response = AgentProfileListResponse.model_validate( + { + "profiles": [ + { + "id": str(uuid4()), + "name": "default", + "agent_kind": "openhands", + "llm_profile_ref": "default", + } + ], + "active_agent_profile_id": None, + } + ) + + assert response.profiles[0].name == "default" + assert response.profiles[0].llm_profile_ref == "default" + + # --------------------------------------------------------------------------- # Construction + round-trip # --------------------------------------------------------------------------- From 906430917242d7f6cb015c6413c6595b61945943 Mon Sep 17 00:00:00 2001 From: openhands Date: Fri, 16 Oct 2026 00:31:02 +0000 Subject: [PATCH 5/5] fix(sdk): keep agent profile summary kind schema open Co-authored-by: openhands --- openhands-sdk/openhands/sdk/profiles/agent_profile.py | 2 +- tests/sdk/profiles/test_agent_profile.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/openhands-sdk/openhands/sdk/profiles/agent_profile.py b/openhands-sdk/openhands/sdk/profiles/agent_profile.py index e5da26fd4ce..d33129fdaac 100644 --- a/openhands-sdk/openhands/sdk/profiles/agent_profile.py +++ b/openhands-sdk/openhands/sdk/profiles/agent_profile.py @@ -89,7 +89,7 @@ class AgentProfileInfo(BaseModel): id: str | None = None name: str - agent_kind: AgentKind = "openhands" + agent_kind: str = "openhands" revision: int | None = None llm_profile_ref: str | None = None mcp_server_refs: list[str] | None = None diff --git a/tests/sdk/profiles/test_agent_profile.py b/tests/sdk/profiles/test_agent_profile.py index a837c7895ab..387b6f8d082 100644 --- a/tests/sdk/profiles/test_agent_profile.py +++ b/tests/sdk/profiles/test_agent_profile.py @@ -32,6 +32,14 @@ ) +def test_agent_profile_info_agent_kind_schema_stays_string_compatible() -> None: + schema = AgentProfileInfo.model_json_schema() + + agent_kind_schema = schema["properties"]["agent_kind"] + assert agent_kind_schema["type"] == "string" + assert "enum" not in agent_kind_schema + + def test_agent_profile_info_accepts_acp_summary_with_null_llm_ref() -> None: summary = AgentProfileInfo.model_validate( {