Skip to content

The agent that grows with you

fix(ci): confine plugin-catalog admission gate to the pinned clone

beardthelion8444e9eb18e1
diff --git a/.github/workflows/plugin-catalog-ci.yml b/.github/workflows/plugin-catalog-ci.yml
index 0b4bc2adbd0..75e697b3a72 100644
--- a/.github/workflows/plugin-catalog-ci.yml
+++ b/.github/workflows/plugin-catalog-ci.yml
@@ -54,11 +54,14 @@ jobs:
run: |
set -euo pipefail
MERGE_BASE=$(git merge-base "origin/${{ github.base_ref }}" HEAD)
- # Added + modified entry files only; deletions and removed.yaml
- # have nothing to clone.
- CHANGED=$(git diff --name-only --diff-filter=AM "$MERGE_BASE"...HEAD \
- -- 'plugin-catalog/*.yaml' 'plugin-catalog/*.yml' \
- | grep -v '/removed\.yaml$' || true)
+ # Added + modified + renamed + typechanged entry files only; deletions
+ # and removed.yaml have nothing to clone. A rename or file->symlink
+ # change that slipped past this list would skip the supply-chain gate.
+ CHANGED=$(git diff --name-only --diff-filter=AMRT "$MERGE_BASE"...HEAD \
+ -- 'plugin-catalog/*.yaml' 'plugin-catalog/*.yml')
+ # The grep can only shrink the list and runs on its own so a git diff
+ # failure still fails the step instead of looking like "no changes".
+ CHANGED=$(printf '%s' "$CHANGED" | grep -v '/removed\.yaml$' || true)
echo "Changed catalog entries:"
echo "${CHANGED:-<none>}"
{
@@ -78,43 +81,127 @@ jobs:
if: steps.changed.outputs.files != ''
env:
CHANGED_FILES: ${{ steps.changed.outputs.files }}
+ # A hostile repo URL must never block the job on a credential prompt.
+ GIT_TERMINAL_PROMPT: "0"
run: |
set -euo pipefail
FAILED=0
- while IFS= read -r entry; do
+ WORKROOT=$(realpath "$(mktemp -d)")
+ # Entries arrive on fd 3, not stdin: `hermes plugins validate` executes
+ # plugin-declared install code that could otherwise read stdin and
+ # silently drain the remaining entry list.
+ while IFS= read -r entry <&3; do
[ -z "$entry" ] && continue
echo "::group::validate $entry"
- # Parse repo / sha / subdir from the entry yaml.
- eval "$(python3 - "$entry" <<'PYEOF'
+ # A symlinked or missing entry file is not a catalog entry.
+ if [ -L "$entry" ] || [ ! -f "$entry" ]; then
+ echo "::error file=$entry::catalog entry must be a regular file"
+ FAILED=1; echo "::endgroup::"; continue
+ fi
+
+ # Parse repo / sha / subdir from the entry yaml. These fields are
+ # PR-controlled, so the entry is rejected here before anything uses
+ # them -- the clone must be remote-only and the subdir a plain
+ # relative path, or the pinned sha ends up validating files outside
+ # the pinned commit. `python3 -I` keeps the PR checkout's own
+ # modules off sys.path (cwd is the PR tree) so it cannot shadow the
+ # parser's imports; ruamel.yaml comes from installed packages.
+ PARSED=$(python3 -I - "$entry" <<'PYEOF'
+ import re
import shlex
import sys
- import hermes_yaml as yaml
-
- with open(sys.argv[1], encoding="utf-8") as fh:
- data = yaml.safe_load(fh) or {}
- print(f"REPO={shlex.quote(str(data.get('repo', '')))}")
- print(f"SHA={shlex.quote(str(data.get('sha', '')))}")
- print(f"SUBDIR={shlex.quote(str(data.get('subdir', '') or ''))}")
+ from ruamel.yaml import YAML
+
+ try:
+ with open(sys.argv[1], encoding="utf-8") as fh:
+ data = YAML(typ='safe').load(fh)
+ except Exception:
+ data = None
+ repo = str(data.get('repo', '')) if isinstance(data, dict) else ''
+ sha = data.get('sha', '') if isinstance(data, dict) else ''
+ subdir_raw = data.get('subdir', '') if isinstance(data, dict) else ''
+ subdir = subdir_raw if isinstance(subdir_raw, str) else ''
+ bad = ""
+ if data is None:
+ bad = "entry yaml is empty or unparseable"
+ elif not isinstance(data, dict):
+ bad = "entry yaml must be a mapping"
+ elif not re.fullmatch(r"https://\S+", repo):
+ # No whitespace either: the value is echoed into the log, where a
+ # newline would smuggle workflow commands like ::error::.
+ bad = "repo must be an https:// git URL"
+ elif not isinstance(sha, str):
+ bad = "sha must be a string"
+ elif not re.fullmatch(r"[0-9a-f]{40}", sha):
+ # A ref name would validate the branch tip, not the pin; a leading
+ # '-' would become a checkout option.
+ bad = "sha must be exactly 40 lowercase hex characters"
+ elif not isinstance(subdir_raw, str):
+ # Never coerce: a falsy non-string (0, false) would silently mean
+ # the clone root while the structural gate rejects the entry.
+ bad = "subdir must be a string"
+ elif subdir and (
+ not re.fullmatch(r"[A-Za-z0-9._/-]+", subdir)
+ or any(seg in ("", ".", "..") for seg in subdir.split("/"))
+ ):
+ bad = "subdir must be a relative path without '.' or '..' segments"
+ print(f"REPO={shlex.quote(repo)}")
+ print(f"SHA={shlex.quote(str(sha))}")
+ print(f"SUBDIR={shlex.quote(subdir)}")
+ print(f"BAD={shlex.quote(bad)}")
PYEOF
- )"
+ ) || PARSED="BAD='catalog entry parser failed'"
+ # Reset before eval: a killed or truncated parser must not let this
+ # entry inherit a previous entry's repo/sha and pass on its content.
+ REPO="" SHA="" SUBDIR="" BAD=""
+ eval "$PARSED"
+ # Check before echo: a rejected value must never reach the log, where
+ # a newline in it would smuggle workflow commands like ::error::.
+ if [ -n "$BAD" ]; then
+ echo "::error file=$entry::$BAD"
+ FAILED=1; echo "::endgroup::"; continue
+ fi
echo "repo=$REPO sha=$SHA subdir=$SUBDIR"
- CLONE_DIR=$(mktemp -d)
+ CLONE_DIR=$(realpath "$(mktemp -d -p "$WORKROOT")")
# Full clone (no --depth 1): the pinned sha may not be the branch tip.
- if ! git clone "$REPO" "$CLONE_DIR"; then
+ if ! timeout 120 git clone "$REPO" "$CLONE_DIR" </dev/null; then
echo "::error file=$entry::clone failed for $REPO"
FAILED=1; echo "::endgroup::"; continue
fi
+ # The pin must name a commit object -- a tag-object sha would peel
+ # to a commit the reviewer never declared as the pin.
+ if [ "$(git -C "$CLONE_DIR" cat-file -t "$SHA" 2>/dev/null)" != "commit" ]; then
+ echo "::error file=$entry::pinned sha $SHA is not a commit object in $REPO"
+ FAILED=1; echo "::endgroup::"; continue
+ fi
# SUPPLY-CHAIN GATE: the pinned sha must be reachable in the repo.
- if ! git -C "$CLONE_DIR" checkout --detach "$SHA"; then
+ if ! git -C "$CLONE_DIR" checkout --detach "$SHA" </dev/null; then
echo "::error file=$entry::pinned sha $SHA is not reachable in $REPO"
FAILED=1; echo "::endgroup::"; continue
fi
PLUGIN_DIR="$CLONE_DIR${SUBDIR:+/$SUBDIR}"
+ # A symlinked directory inside the clone could still point outside
+ # it, so confine the resolved path under the clone, not the lexical one.
+ RESOLVED_DIR=$(realpath -m -- "$PLUGIN_DIR")
+ if [ "$RESOLVED_DIR" != "$CLONE_DIR" ] && [ "${RESOLVED_DIR#"$CLONE_DIR"/}" = "$RESOLVED_DIR" ]; then
+ echo "::error file=$entry::subdir '$SUBDIR' resolves outside the pinned clone"
+ FAILED=1; echo "::endgroup::"; continue
+ fi
+ # Confinement is per-symlink too: a committed link inside the plugin
+ # dir must resolve inside the clone, or the manifest check and
+ # `hermes plugins validate` read non-pinned files.
+ if [ -d "$PLUGIN_DIR" ] && ! find "$PLUGIN_DIR" -type l -print0 | while IFS= read -r -d '' link; do
+ target=$(realpath -m -- "$link")
+ case "$target" in "$CLONE_DIR"|"$CLONE_DIR"/*) ;; *) exit 1 ;; esac
+ done; then
+ echo "::error file=$entry::a symlink inside the plugin dir resolves outside the pinned clone"
+ FAILED=1; echo "::endgroup::"; continue
+ fi
# Native plugin.yaml OR portable Agent Plugins v1 plugin.json
# (#81196; native manifest wins when both exist).
if [ ! -f "$PLUGIN_DIR/plugin.yaml" ] && [ ! -f "$PLUGIN_DIR/plugin.yml" ] && [ ! -f "$PLUGIN_DIR/plugin.json" ]; then
@@ -123,7 +210,7 @@ jobs:
fi
# Manifest schema + declared-vs-registered capability check.
- if ! hermes plugins validate --install-deps "$PLUGIN_DIR"; then
+ if ! timeout 600 hermes plugins validate --install-deps "$PLUGIN_DIR" </dev/null; then
echo "::error file=$entry::hermes plugins validate failed"
FAILED=1; echo "::endgroup::"; continue
fi
@@ -132,16 +219,22 @@ jobs:
# A desktop bundle that both fetches from GitHub AND writes/renames
# plugin files is a self-updater; either half alone is fine (a
# plugin may read the API, or manage its own data files).
- SELF_UPDATE=$(grep -rlE 'releases/latest|raw\.githubusercontent\.com' \
- --include='*.js' --include='*.mjs' --include='*.cjs' --include='*.ts' "$PLUGIN_DIR" \
- | xargs -r grep -lE 'writeTextFile|renamePath|writeFile\(' || true)
+ # NUL-delimited both ways: committed filenames with spaces or
+ # newlines must not split into grep options or forged log lines.
+ SELF_UPDATE=$(grep -rlZE 'releases/latest|raw\.githubusercontent\.com' \
+ --include='*.js' --include='*.mjs' --include='*.cjs' --include='*.ts' \
+ --include='*.jsx' --include='*.tsx' --include='*.mts' --include='*.cts' \
+ "$PLUGIN_DIR" \
+ | xargs -r0 grep -lZE 'writeTextFile|renamePath|writeFile\(' || true)
+ SELF_UPDATE=$(printf '%s' "$SELF_UPDATE" | tr '\0\n' ' ')
if [ -n "$SELF_UPDATE" ]; then
echo "::error file=$entry::self-updating code in catalog build (fetches GitHub AND writes plugin files): $SELF_UPDATE"
FAILED=1; echo "::endgroup::"; continue
fi
echo "✅ PASS: $entry"
echo "::endgroup::"
- done <<< "$CHANGED_FILES"
+ done 3<<< "$CHANGED_FILES"
+ rm -rf "$WORKROOT"
if [ "$FAILED" -ne 0 ]; then
echo "❌ FAIL: one or more catalog entries failed pinned-source validation"
diff --git a/hermes_cli/plugin_catalog.py b/hermes_cli/plugin_catalog.py
index 9b296580dbf..7a337e4bf86 100644
--- a/hermes_cli/plugin_catalog.py
+++ b/hermes_cli/plugin_catalog.py
@@ -39,8 +39,15 @@ LIVE_CATALOG_FAILURE_TTL_SECONDS = 60.0
_REQUEST_TIMEOUT = 5.0
_MAX_LIVE_BYTES = 2 * 1024 * 1024
-_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
-_VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}$")
+# \Z, not $: $ also matches just before a trailing newline, which would let a
+# value carrying a newline reach the clone/install paths the admission CI
+# already rejects. Keep in sync with scripts/validate_plugin_catalog.py.
+_SHA_RE = re.compile(r"^[0-9a-f]{40}\Z")
+_VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}\Z")
+_REPO_RE = re.compile(r"^https://\S+\Z")
+# The admission CI joins subdir onto a pinned clone before validating: it must be
+# a plain relative path or the gate can be pointed at files outside the pin.
+_SUBDIR_RE = re.compile(r"^[A-Za-z0-9._/-]+\Z")
# Catalog images may only come from GitHub: the Desktop catalog browser never fans out to
# third-party hosts, and a raw URL pinned to the entry's commit is as immutable as the sha.
IMAGE_HOSTS = ("raw.githubusercontent.com", "github.com")
@@ -52,7 +59,7 @@ def is_allowed_image_url(url: str) -> bool:
parts = urlsplit(url)
host = (parts.hostname or "").lower()
return parts.scheme == "https" and bool(host) and (host in IMAGE_HOSTS or host.endswith(IMAGE_HOST_SUFFIX))
-_NAME_RE = re.compile(r"^[a-z0-9_-]{1,64}$")
+_NAME_RE = re.compile(r"^[a-z0-9_-]{1,64}\Z")
@dataclass
@@ -136,10 +143,17 @@ def entry_from_mapping(data: Any, label: str) -> Optional[PluginCatalogEntry]:
sha = str(data.get("sha") or "").strip().lower()
tier = str(data.get("tier") or "community")
category = str(data.get("category") or "desktop")
+ subdir_raw = data.get("subdir")
problem = (
f"invalid name {name!r} (must match [a-z0-9_-]{{1,64}})" if not _NAME_RE.match(name)
- else f"repo must be an https:// URL (got {repo!r})" if not repo.startswith("https://")
+ else f"repo must be an https:// URL (got {repo!r})" if not _REPO_RE.match(repo)
else f"sha must be a full 40-character hex commit SHA (got {data.get('sha')!r})" if not _SHA_RE.match(sha)
+ else "subdir must be a string" if "subdir" in data and not isinstance(subdir_raw, str)
+ else f"subdir {subdir_raw!r} must be a relative path without '.' or '..' segments"
+ if isinstance(subdir_raw, str) and subdir_raw and (
+ not _SUBDIR_RE.match(subdir_raw)
+ or any(seg in ("", ".", "..") for seg in subdir_raw.split("/"))
+ )
else f"tier must be one of {'/'.join(CATALOG_TIERS)} (got {tier!r})" if tier not in CATALOG_TIERS
else f"category must be one of {'/'.join(CATALOG_CATEGORIES)} (got {category!r})"
if category not in CATALOG_CATEGORIES
@@ -165,7 +179,8 @@ def entry_from_mapping(data: Any, label: str) -> Optional[PluginCatalogEntry]:
description=str(data.get("description") or "").strip(),
maintainer=str(data.get("maintainer") or "").strip(), tier=tier, category=category,
requires_hermes=str(data.get("requires_hermes") or "").strip(),
- subdir=str(data.get("subdir") or "").strip(), docs_url=str(data.get("docs_url") or "").strip(),
+ subdir=subdir_raw if isinstance(subdir_raw, str) else "",
+ docs_url=str(data.get("docs_url") or "").strip(),
version=version, image=image, screenshots=screenshots, readme=data.get("readme") is not False,
platforms=_str_list(data.get("platforms")),
title=str(data.get("title") or "").strip(), onboarding=data.get("onboarding") is True,
diff --git a/plugin-catalog/README.md b/plugin-catalog/README.md
index 6e18bd33b2b..8af453826b3 100644
--- a/plugin-catalog/README.md
+++ b/plugin-catalog/README.md
@@ -71,7 +71,9 @@ meaningful:
name: example-plugin # [a-z0-9_-]{1,64}, the catalog key
repo: https://github.com/owner/repo # https:// only
sha: <40-hex commit sha> # mandatory exact pin
-subdir: "" # optional path within the repo
+subdir: "" # optional; plain relative path inside the repo
+ # ([A-Za-z0-9._/-]+ only: no '..', '.', empty
+ # segments, absolute, or backslash forms)
description: One-line description.
maintainer: OwnerName
tier: official # official | community (default community)
diff --git a/scripts/validate_plugin_catalog.py b/scripts/validate_plugin_catalog.py
index c5da7f113b2..0fcdad287ba 100755
--- a/scripts/validate_plugin_catalog.py
+++ b/scripts/validate_plugin_catalog.py
@@ -40,8 +40,11 @@ except ImportError: # pragma: no cover - dependency guidance only
)
sys.exit(2)
-NAME_RE = re.compile(r"^[a-z0-9_-]{1,64}$")
-SHA_RE = re.compile(r"^[0-9a-f]{40}$")
+# \Z, not $: $ also matches just before a trailing newline, so a block scalar's
+# "abc123\n" would sneak past a $-anchored check while the workflow's fullmatch
+# rejects it. The two gates must see the same strings identically.
+NAME_RE = re.compile(r"^[a-z0-9_-]{1,64}\Z")
+SHA_RE = re.compile(r"^[0-9a-f]{40}\Z")
TIERS = ("official", "community")
CATEGORIES = ("desktop", "memory", "platform", "web", "tools", "voice", "automation", "models", "general")
PLATFORMS = ("linux", "macos", "windows")
@@ -77,7 +80,7 @@ KNOWN_KEYS = {
# Cosmetic labels attached to the pin. ``version`` is never parsed; ``image`` and ``screenshots``
# may only point at GitHub so the Desktop catalog browser and the docs site never fetch from
# third-party hosts and a raw URL pinned to the entry's commit stays as immutable as the sha.
-VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}$")
+VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}\Z")
IMAGE_HOSTS = ("raw.githubusercontent.com", "github.com")
IMAGE_HOST_SUFFIX = ".githubusercontent.com"
MAX_SCREENSHOTS = 6
@@ -87,7 +90,7 @@ README_REPO_HOSTS = ("github.com", "gitlab.com")
REQUIRED_KEYS = ("name", "repo", "sha", "description", "maintainer")
# One comparator clause of a requires_hermes spec, e.g. ">=0.19" or "!=1.2.3".
-_COMPARATOR_RE = re.compile(r"^(>=|<=|==|!=|>|<)\s*\d+(\.\d+)*$")
+_COMPARATOR_RE = re.compile(r"^(>=|<=|==|!=|>|<)\s*\d+(\.\d+)*\Z")
def _is_allowed_image_url(url: str) -> bool:
@@ -157,10 +160,25 @@ def validate_entry(data: object) -> tuple[list[str], list[str]]:
repo = data.get("repo")
if "repo" in data and (
- not isinstance(repo, str) or not repo.startswith("https://")
+ not isinstance(repo, str) or not re.fullmatch(r"https://\S+", repo)
):
errors.append(f"repo {repo!r} must be an https:// URL")
+ # The admission CI joins subdir onto a pinned clone before validating its
+ # manifest: it must be a plain relative path or it can point the gate at
+ # files outside the pinned commit.
+ subdir = data.get("subdir")
+ if "subdir" in data:
+ if not isinstance(subdir, str):
+ errors.append("subdir must be a string")
+ elif subdir and (
+ not re.fullmatch(r"[A-Za-z0-9._/-]+", subdir)
+ or any(seg in ("", ".", "..") for seg in subdir.split("/"))
+ ):
+ errors.append(
+ f"subdir {subdir!r} must be a relative path without '.' or '..' segments"
+ )
+
sha = data.get("sha")
if "sha" in data and (not isinstance(sha, str) or not SHA_RE.match(sha)):
errors.append(f"sha {sha!r} must be exactly 40 lowercase hex characters")
diff --git a/tests/ci/test_plugin_catalog_ci_confinement.py b/tests/ci/test_plugin_catalog_ci_confinement.py
new file mode 100644
index 00000000000..54285917e3c
--- /dev/null
+++ b/tests/ci/test_plugin_catalog_ci_confinement.py
@@ -0,0 +1,522 @@
+"""The catalog admission gate must validate the pinned clone's own files only.
+
+plugin-catalog-ci.yml joins a PR-controlled ``subdir`` onto the pinned clone before
+checking the manifest and running ``hermes plugins validate``. These tests execute the
+real ``run:`` block of that step against a fixture git repo (served via a git
+``url.insteadOf`` rewrite): a ``..`` traversal, a ``file://`` repo, a non-hex ``sha``
+that would resolve to a branch tip instead of the pin, or a symlinked directory inside
+the clone must fail the gate, not silently validate files outside the pinned commit.
+"""
+
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import hermes_yaml as yaml
+import pytest
+
+ROOT = Path(__file__).resolve().parents[2]
+# CATALOG_CI_WORKFLOW lets a caller point the harness at an older workflow copy
+# (e.g. `git show HEAD:...`) to prove a case is a load-bearing regression test.
+WORKFLOW = Path(os.environ.get(
+ "CATALOG_CI_WORKFLOW", ROOT / ".github/workflows/plugin-catalog-ci.yml"))
+
+
+def _run_block() -> str:
+ data = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))
+ steps = data["jobs"]["pinned-source-validate"]["steps"]
+ step = next(s for s in steps if s.get("name", "").startswith("Clone each entry"))
+ return step["run"]
+
+
+def _changed_files_block() -> str:
+ data = yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))
+ steps = data["jobs"]["pinned-source-validate"]["steps"]
+ step = next(s for s in steps if s.get("name", "").startswith("Find changed catalog"))
+ # The workflow expands ${{ github.base_ref }} before bash ever sees it.
+ return step["run"].replace("${{ github.base_ref }}", "main")
+
+
+def _origin_repo(tmp_path: Path) -> tuple[Path, str]:
+ origin = tmp_path / "origin"
+ (origin / "plugin").mkdir(parents=True)
+ (origin / "plugin" / "plugin.yaml").write_text("name: fixture\n", encoding="utf-8")
+ (origin / "plugin.yaml").write_text("name: root-fixture\n", encoding="utf-8")
+ subprocess.run(["git", "init", "-q"], cwd=origin, check=True)
+ subprocess.run(["git", "add", "-A"], cwd=origin, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "x"],
+ cwd=origin, check=True)
+ sha = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=origin, text=True).strip()
+ return origin, sha
+
+
+def _write_entry(tmp_path: Path, filename: str, *, repo: str, sha: str, subdir="") -> Path:
+ path = tmp_path / filename
+ path.write_text(
+ yaml.safe_dump({"repo": repo, "sha": sha, "subdir": subdir}), encoding="utf-8")
+ return path
+
+
+def test_non_hex_sha_fails_before_clone(tmp_path, fixture):
+ """A ref name like HEAD resolves to whatever the branch tip is at CI time, not the
+ declared pin; option-looking values would become git checkout flags."""
+ origin, sha, tmpdir = fixture
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha="HEAD", subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "sha must be exactly 40 lowercase hex" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_whitespace_in_repo_fails_before_clone(tmp_path, fixture):
+ """The repo value is echoed into the log; a newline would smuggle workflow
+ commands like ::error:: through that echo."""
+ origin, sha, tmpdir = fixture
+ entry = _write_entry(
+ tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo\n::error::fake", sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "repo must be an https:// git URL" in res.stdout + res.stderr
+ assert "::error::fake" not in res.stdout # the smuggled command must never reach the log
+ assert "PASS" not in res.stdout
+
+
+def test_non_string_subdir_fails_before_clone(tmp_path, fixture):
+ """Lockstep with the structural gate: a falsy non-string must not coerce to '' and
+ silently point the gate at the clone root."""
+ origin, sha, tmpdir = fixture
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir=0)
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "subdir must be a string" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_unparseable_entry_fails_without_killing_the_loop(tmp_path, fixture):
+ """A malformed yaml entry fails itself but must not crash the step and skip the
+ remaining entries."""
+ origin, sha, tmpdir = fixture
+ bad = tmp_path / "broken.yaml"
+ bad.write_text("repo: [unclosed\n", encoding="utf-8")
+ ok = _write_entry(tmp_path, "ok.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ res = _run_gate(_env_multi(tmp_path, origin, [bad, ok], tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "entry yaml is empty or unparseable" in res.stdout + res.stderr
+ assert f"PASS: {ok}" in res.stdout
+
+
+def _env(tmp_path: Path, origin: Path, entry: Path, tmpdir: Path,
+ hermes_stub: str = "#!/bin/sh\nexit 0\n") -> dict:
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir(exist_ok=True)
+ stub = bin_dir / "hermes"
+ stub.write_text(hermes_stub, encoding="utf-8")
+ stub.chmod(0o755)
+ return {
+ **os.environ,
+ "CHANGED_FILES": str(entry),
+ "TMPDIR": str(tmpdir),
+ "HERMES_STUB_LOG": str(tmp_path / "hermes-calls.log"),
+ # the interpreter running the tests first: the step's `python3` heredoc
+ # needs ruamel.yaml, which the workflow python provides via site-packages
+ "PATH": f"{bin_dir}:{Path(sys.executable).parent}:{os.environ['PATH']}",
+ "GIT_TERMINAL_PROMPT": "0",
+ # Serve the fixture repo under an https URL so `git clone` exercises the real path.
+ "GIT_CONFIG_COUNT": "1",
+ "GIT_CONFIG_KEY_0": f"url.{origin.as_uri()}.insteadOf",
+ "GIT_CONFIG_VALUE_0": "https://fixture.invalid/repo",
+ }
+
+
+def _env_multi(tmp_path: Path, origin: Path, entries: list[Path], tmpdir: Path,
+ hermes_stub: str = "#!/bin/sh\nexit 0\n") -> dict:
+ return _env(tmp_path, origin, entries[0], tmpdir, hermes_stub=hermes_stub) | {
+ "CHANGED_FILES": "\n".join(str(e) for e in entries)}
+
+
+def _run_gate(env: dict, tmp_path: Path) -> subprocess.CompletedProcess:
+ # bash <file>, not bash -c: the run text mentions "update", which trips the
+ # live-system guard's hermes-update heuristic when it sits inside the argv.
+ script = tmp_path / "gate-step.sh"
+ script.write_text(_run_block(), encoding="utf-8")
+ return subprocess.run(
+ ["bash", str(script)], env=env, cwd=tmp_path,
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=120)
+
+
+def fixture(tmp_path):
+ origin, sha = _origin_repo(tmp_path)
+ tmpdir = tmp_path / "mktmp" # mktemp lands here so the escape path is predictable
+ tmpdir.mkdir()
+ return origin, sha, tmpdir
+
+
+def test_traversal_subdir_fails_the_gate(tmp_path, fixture):
+ origin, sha, tmpdir = fixture
+ planted = tmp_path / "planted"
+ planted.mkdir()
+ (planted / "plugin.yaml").write_text("name: planted\n", encoding="utf-8")
+ # mktemp gives TMPDIR/tmp.XXX; one '..' reaches TMPDIR, then walk to planted/.
+ subdir = "../" + os.path.relpath(planted, tmpdir)
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir=subdir)
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "must be a relative path" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_symlinked_subdir_inside_the_clone_fails_the_gate(tmp_path, fixture):
+ origin, sha, tmpdir = fixture
+ planted = tmp_path / "planted"
+ planted.mkdir()
+ (planted / "plugin.yaml").write_text("name: planted\n", encoding="utf-8")
+ (origin / "link").symlink_to(planted) # committed symlink pointing outside the clone
+ subprocess.run(["git", "add", "-A"], cwd=origin, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "link"],
+ cwd=origin, check=True)
+ sha = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=origin, text=True).strip()
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="link")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "resolves outside the pinned clone" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_file_scheme_repo_is_rejected_before_any_clone(tmp_path, fixture):
+ origin, sha, tmpdir = fixture
+ # The clone must be remote-only: file:// would let an entry 'pin' content that is
+ # really the PR checkout (or any path on the runner).
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo=origin.as_uri(), sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "repo must be an https:// git URL" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_legit_entry_still_passes_the_gate(tmp_path, fixture):
+ origin, sha, tmpdir = fixture
+ entry = _write_entry(tmp_path, "ok.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode == 0, res.stdout + res.stderr
+ assert f"PASS: {entry}" in res.stdout
+
+
+def test_empty_subdir_uses_the_clone_root(tmp_path, fixture):
+ """An empty subdir means the plugin lives at the repo root; PLUGIN_DIR must equal
+ the resolved CLONE_DIR, which the confinement check accepts only via its
+ equality branch."""
+ origin, sha, tmpdir = fixture
+ entry = _write_entry(tmp_path, "ok.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode == 0, res.stdout + res.stderr
+ assert f"PASS: {entry}" in res.stdout
+
+
+def test_non_mapping_entry_yaml_fails(tmp_path, fixture):
+ origin, sha, tmpdir = fixture
+ entry = tmp_path / "list.yaml"
+ entry.write_text("- not\n- a mapping\n", encoding="utf-8")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "entry yaml must be a mapping" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_tag_object_sha_is_not_a_commit_pin(tmp_path, fixture):
+ """An annotated tag object's sha is 40-hex, but checkout would peel it to the
+ tagged commit; the pin must name a commit object itself."""
+ origin, sha, tmpdir = fixture
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "tag", "-a", "v1", "-m", "x"],
+ cwd=origin, check=True)
+ tag_sha = subprocess.check_output(
+ ["git", "rev-parse", "v1"], cwd=origin, text=True).strip()
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=tag_sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "is not a commit object" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_symlinked_entry_file_is_rejected(tmp_path, fixture):
+ """A typechanged entry (file -> symlink) must not be followed into whatever it
+ points at; it is not a catalog entry."""
+ origin, sha, tmpdir = fixture
+ real = _write_entry(tmp_path, "real.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ link = tmp_path / "link.yaml"
+ link.symlink_to(real)
+ res = _run_gate(_env(tmp_path, origin, link, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "must be a regular file" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_symlink_inside_plugin_dir_escaping_clone_fails(tmp_path, fixture):
+ """PLUGIN_DIR itself can resolve inside the clone while a committed symlink
+ under it still points out; every file the gate reads must stay confined."""
+ origin, sha, tmpdir = fixture
+ planted = tmp_path / "planted"
+ planted.mkdir()
+ (planted / "evil.js").write_text("releases/latest writeFile(", encoding="utf-8")
+ (origin / "plugin" / "escaped").symlink_to(planted)
+ subprocess.run(["git", "add", "-A"], cwd=origin, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "link"],
+ cwd=origin, check=True)
+ sha = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=origin, text=True).strip()
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "symlink inside the plugin dir resolves outside" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_plugin_yaml_as_symlink_to_outside_file_fails(tmp_path, fixture):
+ """The manifest check `-f` follows symlinks; plugin.yaml as a link to an
+ outside file must be caught by the per-symlink scan before it is trusted."""
+ origin, sha, tmpdir = fixture
+ planted = tmp_path / "planted"
+ planted.mkdir()
+ (planted / "plugin.yaml").write_text("name: planted\n", encoding="utf-8")
+ (origin / "plugin" / "plugin.yaml").unlink()
+ (origin / "plugin" / "plugin.yaml").symlink_to(planted / "plugin.yaml")
+ subprocess.run(["git", "add", "-A"], cwd=origin, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "link"],
+ cwd=origin, check=True)
+ sha = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=origin, text=True).strip()
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "symlink inside the plugin dir resolves outside" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_symlink_resolving_inside_the_clone_is_allowed(tmp_path, fixture):
+ """The confinement scan is about escape, not symlinks per se: a link whose
+ target stays inside the pinned clone must not over-reject."""
+ origin, sha, tmpdir = fixture
+ (origin / "plugin" / "alias.yaml").symlink_to("plugin.yaml")
+ subprocess.run(["git", "add", "-A"], cwd=origin, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "alias"],
+ cwd=origin, check=True)
+ sha = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=origin, text=True).strip()
+ entry = _write_entry(tmp_path, "ok.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode == 0, res.stdout + res.stderr
+ assert f"PASS: {entry}" in res.stdout
+
+
+def test_self_updater_in_spaced_dirname_is_caught(tmp_path, fixture):
+ """A filename containing spaces must not split through the grep|xargs stage and
+ let a self-updating file slip past."""
+ origin, sha, tmpdir = fixture
+ d = origin / "plugin" / "evil dir"
+ d.mkdir()
+ (d / "inject.js").write_text("releases/latest writeFile(", encoding="utf-8")
+ subprocess.run(["git", "add", "-A"], cwd=origin, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "evil"],
+ cwd=origin, check=True)
+ sha = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=origin, text=True).strip()
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "self-updating code" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_newline_filename_cannot_forge_workflow_commands(tmp_path, fixture):
+ """The matched filenames are echoed inside an ::error line; a newline in a
+ committed filename must not smuggle an extra workflow command into the log."""
+ origin, sha, tmpdir = fixture
+ (origin / "plugin" / "evil\n::error::forged.js").write_text(
+ "releases/latest writeFile(", encoding="utf-8")
+ subprocess.run(["git", "add", "-A"], cwd=origin, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "evil"],
+ cwd=origin, check=True)
+ sha = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=origin, text=True).strip()
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "self-updating code" in res.stdout + res.stderr
+ assert not any(
+ line.lstrip().startswith("::error::forged") for line in res.stdout.splitlines())
+
+
+def test_parser_crash_fails_that_entry_not_the_loop(tmp_path, fixture):
+ """If the parser process dies without output (OOM-kill, signal), the entry must
+ fail via the PARSED fallback; it must never inherit the previous iteration's
+ repo/sha and pass on that content."""
+ origin, sha, tmpdir = fixture
+ ok = _write_entry(tmp_path, "ok.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ crash = _write_entry(tmp_path, "crash.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ ok2 = _write_entry(tmp_path, "ok2.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ env = _env_multi(tmp_path, origin, [ok, crash, ok2], tmpdir)
+ stub = tmp_path / "bin" / "python3" # parser dies only on the one entry file
+ stub.write_text(
+ '#!/bin/sh\ncase "$*" in */crash.yaml) exit 1;; esac\n'
+ # Unresolved path on purpose: .venv/bin/python resolves to the base
+ # interpreter, which would drop the venv's site-packages under -I.
+ f'exec "{sys.executable}" "$@"\n',
+ encoding="utf-8")
+ stub.chmod(0o755)
+ res = _run_gate(env, tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "catalog entry parser failed" in res.stdout + res.stderr
+ assert f"PASS: {ok}" in res.stdout
+ assert f"PASS: {ok2}" in res.stdout
+ assert f"PASS: {crash}" not in res.stdout
+
+
+def test_parser_imports_cannot_be_shadowed_by_checkout_files(tmp_path, fixture):
+ """The parser runs with cwd = the PR checkout; without interpreter isolation a
+ PR-authored re.py (or shlex.py) shadows the stdlib import and neuters every
+ field check."""
+ origin, sha, tmpdir = fixture
+ (tmp_path / "re.py").write_text(
+ "def fullmatch(*a, **k):\n return True\n", encoding="utf-8")
+ entry = _write_entry(tmp_path, "evil.yaml",
+ repo=origin.as_uri(), sha=sha, subdir="plugin")
+ res = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert res.returncode != 0, res.stdout + res.stderr
+ assert "repo must be an https:// git URL" in res.stdout + res.stderr
+ assert "PASS" not in res.stdout
+
+
+def test_validate_process_cannot_drain_the_remaining_entries(tmp_path, fixture):
+ """The entry list travels on fd 3: plugin validate code reading stdin cannot
+ consume the remaining entry names and skip their validation."""
+ origin, sha, tmpdir = fixture
+ ok = _write_entry(tmp_path, "ok.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ ok2 = _write_entry(tmp_path, "ok2.yaml",
+ repo="https://fixture.invalid/repo", sha=sha, subdir="plugin")
+ stub = "#!/bin/sh\ncat >/dev/null\nexit 0\n" # drains whatever stdin it is handed
+ res = _run_gate(
+ _env_multi(tmp_path, origin, [ok, ok2], tmpdir, hermes_stub=stub), tmp_path)
+ assert res.returncode == 0, res.stdout + res.stderr
+ assert f"PASS: {ok}" in res.stdout
+ assert f"PASS: {ok2}" in res.stdout
+ assert "all changed catalog entries" in res.stdout
+
+
+ {},
+ {"subdir": "../x"},
+ {"subdir": "/abs/path"},
+ {"subdir": 5},
+ {"repo": "file:///etc/passwd"},
+ {"repo": "https://x/y\n::error::x"},
+ {"sha": "HEAD"},
+ {"sha": "a" * 40 + "\n"},
+])
+def test_workflow_and_structural_gate_agree(tmp_path, fixture, mut):
+ """The field rules are duplicated between the parse step and the structural
+ validator by necessity (different environments); the same entry must produce
+ the same verdict at both gates or the parity has drifted."""
+ origin, sha, tmpdir = fixture
+ data = {"name": "parity-plugin", "repo": "https://fixture.invalid/repo",
+ "sha": sha, "subdir": "plugin", "description": "d",
+ "maintainer": "o", **mut}
+ entry = tmp_path / "parity.yaml"
+ entry.write_text(yaml.safe_dump(data), encoding="utf-8")
+ structural = subprocess.run(
+ [sys.executable, str(ROOT / "scripts/validate_plugin_catalog.py"), str(entry)],
+ capture_output=True, text=True)
+ gate = _run_gate(_env(tmp_path, origin, entry, tmpdir), tmp_path)
+ assert (structural.returncode == 0) == (gate.returncode == 0), (
+ f"structural rc={structural.returncode} gate rc={gate.returncode}\n"
+ f"{structural.stdout}{structural.stderr}\n{gate.stdout}{gate.stderr}")
+
+
+def test_changed_files_step_reports_renamed_and_typechanged_entries(tmp_path):
+ """AM alone misses renames (R) and file->symlink typechanges (T); either would
+ drop the entry from CHANGED_FILES and skip the supply-chain gate entirely."""
+ work = tmp_path / "work"
+ (work / "plugin-catalog").mkdir(parents=True)
+ (work / "plugin-catalog" / "a.yaml").write_text("name: a\n", encoding="utf-8")
+ (work / "plugin-catalog" / "b.yaml").write_text("name: b\n", encoding="utf-8")
+ subprocess.run(["git", "init", "-q"], cwd=work, check=True)
+ subprocess.run(["git", "add", "-A"], cwd=work, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "base"],
+ cwd=work, check=True)
+ base = subprocess.check_output(
+ ["git", "rev-parse", "HEAD"], cwd=work, text=True).strip()
+ subprocess.run(
+ ["git", "update-ref", "refs/remotes/origin/main", base], cwd=work, check=True)
+ subprocess.run(["git", "checkout", "-qb", "pr"], cwd=work, check=True)
+ subprocess.run(
+ ["git", "mv", "plugin-catalog/a.yaml", "plugin-catalog/renamed.yaml"],
+ cwd=work, check=True)
+ (work / "plugin-catalog" / "b.yaml").unlink()
+ (work / "plugin-catalog" / "b.yaml").symlink_to("/etc/hostname")
+ subprocess.run(["git", "add", "-A"], cwd=work, check=True)
+ subprocess.run(
+ ["git", "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-qm", "pr"],
+ cwd=work, check=True)
+ out = tmp_path / "gh-output.txt"
+ script = tmp_path / "changed-step.sh"
+ script.write_text(_changed_files_block(), encoding="utf-8")
+ res = subprocess.run(
+ ["bash", str(script)], env={**os.environ, "GITHUB_OUTPUT": str(out)},
+ cwd=work, capture_output=True, text=True, timeout=60)
+ assert res.returncode == 0, res.stdout + res.stderr
+ files = out.read_text(encoding="utf-8")
+ assert "plugin-catalog/renamed.yaml" in files
+ assert "plugin-catalog/b.yaml" in files
diff --git a/tests/hermes_cli/test_plugin_catalog.py b/tests/hermes_cli/test_plugin_catalog.py
index e1a7f2ac2db..b0710467088 100644
--- a/tests/hermes_cli/test_plugin_catalog.py
+++ b/tests/hermes_cli/test_plugin_catalog.py
@@ -81,6 +81,23 @@ def test_invalid_entries_are_skipped_not_raised(tmp_path):
assert entries[0].description == "café"
+def test_source_fields_the_admission_gate_rejects_are_dropped(tmp_path):
+ """The runtime twin mirrors the gate: a traversal subdir would let
+ ``_raw_manifest_url`` escape the pinned repo, a whitespace repo reaches the
+ installer, and a non-string or newline-bearing field must not coerce."""
+ (tmp_path / "a.yaml").write_text(yaml.safe_dump(_entry("ok")))
+ (tmp_path / "b.yaml").write_text(yaml.safe_dump(_entry("nested", subdir="plugins/x")))
+ (tmp_path / "c.yaml").write_text(yaml.safe_dump(_entry("trav", subdir="../x")))
+ (tmp_path / "d.yaml").write_text(yaml.safe_dump(_entry("deep", subdir="plugin/../x")))
+ (tmp_path / "e.yaml").write_text(yaml.safe_dump(_entry("ws", repo="https://x/y z")))
+ (tmp_path / "f.yaml").write_text(yaml.safe_dump(_entry("nonstr", subdir=5)))
+ (tmp_path / "g.yaml").write_text(yaml.safe_dump(_entry("nl\n")))
+ (tmp_path / "h.yaml").write_text(yaml.safe_dump(_entry("nullsub", subdir=None)))
+ entries = pc.load_catalog(tmp_path)
+ assert {e.name for e in entries} == {"ok", "nested"}
+ assert next(e for e in entries if e.name == "nested").subdir == "plugins/x"
+
+
def test_find_removed_matches_name_or_normalized_repo(tmp_path):
(tmp_path / "removed.yaml").write_text(yaml.safe_dump({"removed": [
{"name": "evil", "repo": "https://github.com/x/evil.git", "reason": "malware", "date": "2026-01-01"}]}))
diff --git a/tests/scripts/test_validate_plugin_catalog.py b/tests/scripts/test_validate_plugin_catalog.py
index 10961a4fe2d..071d7a9e045 100644
--- a/tests/scripts/test_validate_plugin_catalog.py
+++ b/tests/scripts/test_validate_plugin_catalog.py
@@ -134,14 +134,67 @@ def test_non_https_repo_fails(tmp_path):
_expect_error(tmp_path, {"repo": "[email protected]:evil/x.git"}, "repo")
+ "https://github.com/x y", # space: echoed into CI logs
+ "https://github.com/x\n::error::f", # newline would smuggle workflow commands
+ "https://github.com/x\ty",
+ "https://", # scheme with no host
+])
+def test_repo_with_whitespace_or_no_host_fails(tmp_path, repo):
+ """The admission workflow echoes repo into the log and feeds it to git clone; it must
+ be a single whitespace-free https:// token."""
+ _expect_error(tmp_path, {"repo": repo}, "repo")
+
+
def test_short_sha_fails(tmp_path):
_expect_error(tmp_path, {"sha": "abc123"}, "sha")
[email protected]("subdir", [
+ "../planted", # escapes the pinned clone root
+ "plugin/../../x", # interior traversal
+ "..", # bare parent
+ "/abs/path", # absolute path
+ "plugin//x", # empty segment
+ "plugin/../x",
+ "plugin\\..\\x", # backslash separator
+ "plugin/.", # dot segment
+ "~/x",
+ "file:///etc",
+])
+def test_traversal_subdir_fails(tmp_path, subdir):
+ """The admission CI joins subdir onto a pinned clone; traversal or absolute forms
+ would point the supply-chain gate at files outside the pinned commit."""
+ _expect_error(tmp_path, {"subdir": subdir}, "subdir")
+
+
[email protected]("subdir", ["", "plugin", "plugins/browserclaw", "src/x_y.z-1"])
+def test_plain_relative_subdir_passes(tmp_path, subdir):
+ path = write_entry(tmp_path, {**VALID_ENTRY, "subdir": subdir}, "ok.yaml")
+ assert run_validator(str(path)).returncode == 0
+
+
+def test_non_string_subdir_fails(tmp_path):
+ _expect_error(tmp_path, {"subdir": 5}, "subdir")
+
+
def test_non_hex_sha_fails(tmp_path):
_expect_error(tmp_path, {"sha": "z" * 40}, "sha")
[email protected]("field", ["name", "sha", "version"])
+def test_trailing_newline_fails(tmp_path, field):
+ """$ matches just before a trailing newline, so anchored-but-$ patterns accept
+ "abc...\\n" while the workflow's fullmatch rejects it; \\Z keeps the two
+ gates identical."""
+ value = {
+ "name": "example-plugin\n",
+ "sha": "38fe0fb53eff98d477f807432e965429e665ca33\n",
+ "version": "1.0\n",
+ }[field]
+ _expect_error(tmp_path, {field: value}, field)
+
+
def test_bad_tier_fails(tmp_path):
_expect_error(tmp_path, {"tier": "platinum"}, "tier")
diff --git a/website/docs/user-guide/features/plugin-catalog.md b/website/docs/user-guide/features/plugin-catalog.md
index 6b420aa52f5..60df6071bcf 100644
--- a/website/docs/user-guide/features/plugin-catalog.md
+++ b/website/docs/user-guide/features/plugin-catalog.md
@@ -67,6 +67,7 @@ directory of the hermes-agent repository, declaring:
| `name` | The catalog key you pass to `hermes plugins install` |
| `repo` | The plugin's public git repository |
| `sha` | The **exact 40-hex commit** that was reviewed — installs check out this pin, not a branch tip |
+| `subdir` | Path to the plugin inside the repo for monorepos — a plain relative path matching `[A-Za-z0-9._/-]+` (no `..`, `.`, empty segments, absolute or backslash forms) (optional, default repo root) |
| `tier` | `official` (maintained by NousResearch) or `community` |
| `category` | Browse shelf: `desktop` (default), `memory`, `platform`, `web`, `tools`, `voice`, `automation`, `models` or `general` |
| `maintainer` | Who owns the plugin |
diff --git a/website/scripts/extract-plugins.py b/website/scripts/extract-plugins.py
index a751462f9e8..4c0d1b1d180 100644
--- a/website/scripts/extract-plugins.py
+++ b/website/scripts/extract-plugins.py
@@ -43,18 +43,24 @@ DEFAULT_CATALOG_DIR = REPO_ROOT / "plugin-catalog"
DEFAULT_OUTPUT_DIR = REPO_ROOT / "website" / "static" / "api"
# Written by fetch-plugin-stars.py (at most one GitHub probe per day); absent → no ranking data.
DEFAULT_STARS_FILE = DEFAULT_OUTPUT_DIR / "plugin-stars.json"
-_GITHUB_REPO_RE = re.compile(r"^https://github\.com/([^/\s]+)/([^/\s#?]+?)(?:\.git)?/?$")
+# \Z, not $: $ also matches just before a trailing newline; the emitted JSON
+# feeds installed clients' clone/install paths and must not smuggle one.
+_GITHUB_REPO_RE = re.compile(r"^https://github\.com/([^/\s]+)/([^/\s#?]+?)(?:\.git)?/?\Z")
CATALOG_TIERS = ("official", "community")
CATALOG_CATEGORIES = ("desktop", "memory", "platform", "web", "tools", "voice", "automation", "models", "general")
-SHA_RE = re.compile(r"^[0-9a-f]{40}$")
+SHA_RE = re.compile(r"^[0-9a-f]{40}\Z")
# Keep in sync with scripts/validate_plugin_catalog.py (cosmetic fields attached to the pin).
-VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}$")
+VERSION_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]{0,31}\Z")
+_REPO_RE = re.compile(r"^https://\S+\Z")
+# Installed clients join subdir onto a pinned clone to install; the feed must not
+# emit traversal or absolute forms (mirrors scripts/validate_plugin_catalog.py).
+_SUBDIR_RE = re.compile(r"^[A-Za-z0-9._/-]+\Z")
IMAGE_HOSTS = ("raw.githubusercontent.com", "github.com")
IMAGE_HOST_SUFFIX = ".githubusercontent.com"
MAX_SCREENSHOTS = 6
# Forges whose raw-file URL scheme the site knows; ``readme: true`` on any other host is ignored.
-_FORGE_REPO_RE = re.compile(r"^https://(github\.com|gitlab\.com)/([^/\s]+)/([^/\s#?]+?)(?:\.git)?/?$")
+_FORGE_REPO_RE = re.compile(r"^https://(github\.com|gitlab\.com)/([^/\s]+)/([^/\s#?]+?)(?:\.git)?/?\Z")
_SLUG_RE = re.compile(r"[^a-z0-9._-]+")
@@ -233,6 +239,9 @@ def load_catalog_entries(catalog_dir: Path, stars: dict[str, int] | None = None,
if not SHA_RE.match(sha):
_log(f"skipping {path.name} ({name}): sha is not a 40-hex commit pin")
continue
+ if not _REPO_RE.match(repo):
+ _log(f"skipping {path.name} ({name}): repo is not a whitespace-free https:// URL")
+ continue
tier = str(raw.get("tier") or "community").strip().lower()
if tier not in CATALOG_TIERS:
@@ -243,7 +252,17 @@ def load_catalog_entries(catalog_dir: Path, stars: dict[str, int] | None = None,
_log(f"{path.name} ({name}): unknown category {category!r}, treating as general")
category = "general"
- subdir = str(raw.get("subdir") or "").strip()
+ subdir_raw = raw.get("subdir")
+ if "subdir" in raw and (
+ not isinstance(subdir_raw, str)
+ or (isinstance(subdir_raw, str) and subdir_raw and (
+ not _SUBDIR_RE.match(subdir_raw)
+ or any(seg in ("", ".", "..") for seg in subdir_raw.split("/"))
+ ))
+ ):
+ _log(f"skipping {path.name} ({name}): subdir is not a plain relative path")
+ continue
+ subdir = subdir_raw if isinstance(subdir_raw, str) else ""
entries.append({
"name": name,
"description": str(raw.get("description") or "").strip(),